4 * Copyright(c) 2006-2007, Ext JS, LLC.
6 * Originally Released Under LGPL - original licence link has changed is not relivant.
9 * <script type="text/javascript">
17 window["undefined"] = window["undefined"];
21 * Roo core utilities and functions.
26 * Copies all the properties of config to obj.
27 * @param {Object} obj The receiver of the properties
28 * @param {Object} config The source of the properties
29 * @param {Object} defaults A different object that will also be applied for default values
30 * @return {Object} returns obj
35 Roo.apply = function(o, c, defaults){
37 // no "this" reference for friendly out of scope calls
38 Roo.apply(o, defaults);
40 if(o && c && typeof c == 'object'){
51 var ua = navigator.userAgent.toLowerCase();
53 var isStrict = document.compatMode == "CSS1Compat",
54 isOpera = ua.indexOf("opera") > -1,
55 isSafari = (/webkit|khtml/).test(ua),
56 isIE = ua.indexOf("msie") > -1,
57 isIE7 = ua.indexOf("msie 7") > -1,
58 isGecko = !isSafari && ua.indexOf("gecko") > -1,
59 isBorderBox = isIE && !isStrict,
60 isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1),
61 isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1),
62 isLinux = (ua.indexOf("linux") != -1),
63 isSecure = window.location.href.toLowerCase().indexOf("https") === 0;
65 // remove css image flicker
68 document.execCommand("BackgroundImageCache", false, true);
74 * True if the browser is in strict mode
79 * True if the page is running over SSL
84 * True when the document is fully initialized and ready for action
89 * Turn on debugging output (currently only the factory uses this)
96 * True to automatically uncache orphaned Roo.Elements periodically (defaults to true)
99 enableGarbageCollector : true,
102 * True to automatically purge event listeners after uncaching an element (defaults to false).
103 * Note: this only happens if enableGarbageCollector is true.
106 enableListenerCollection:false,
109 * URL to a blank file used by Roo when in secure mode for iframe src and onReady src to prevent
110 * the IE insecure content warning (defaults to javascript:false).
113 SSL_SECURE_URL : "javascript:false",
116 * URL to a 1x1 transparent gif image used by Roo to create inline icons with CSS background images. (Defaults to
117 * "http://Roojs.com/s.gif" and you should change this to a URL on your server).
120 BLANK_IMAGE_URL : "http:/"+"/localhost/s.gif",
122 emptyFn : function(){},
125 * Copies all the properties of config to obj if they don't already exist.
126 * @param {Object} obj The receiver of the properties
127 * @param {Object} config The source of the properties
128 * @return {Object} returns obj
130 applyIf : function(o, c){
133 if(typeof o[p] == "undefined"){ o[p] = c[p]; }
140 * Applies event listeners to elements by selectors when the document is ready.
141 * The event name is specified with an @ suffix.
144 // add a listener for click on all anchors in element with id foo
145 '#foo a@click' : function(e, t){
149 // add the same listener to multiple selectors (separated by comma BEFORE the @)
150 '#foo a, #bar span.some-class@mouseover' : function(){
155 * @param {Object} obj The list of behaviors to apply
157 addBehaviors : function(o){
159 Roo.onReady(function(){
164 var cache = {}; // simple cache for applying multiple behaviors to same selector does query multiple times
166 var parts = b.split('@');
167 if(parts[1]){ // for Object prototype breakers
170 cache[s] = Roo.select(s);
172 cache[s].on(parts[1], o[b]);
179 * Generates unique ids. If the element already has an id, it is unchanged
180 * @param {String/HTMLElement/Element} el (optional) The element to generate an id for
181 * @param {String} prefix (optional) Id prefix (defaults "Roo-gen")
182 * @return {String} The generated Id.
184 id : function(el, prefix){
185 prefix = prefix || "roo-gen";
187 var id = prefix + (++idSeed);
188 return el ? (el.id ? el.id : (el.id = id)) : id;
193 * Extends one class with another class and optionally overrides members with the passed literal. This class
194 * also adds the function "override()" to the class that can be used to override
195 * members on an instance.
196 * @param {Object} subclass The class inheriting the functionality
197 * @param {Object} superclass The class being extended
198 * @param {Object} overrides (optional) A literal with members
203 var io = function(o){
208 return function(sb, sp, overrides){
209 if(typeof sp == 'object'){ // eg. prototype, rather than function constructor..
212 sb = function(){sp.apply(this, arguments);};
214 var F = function(){}, sbp, spp = sp.prototype;
216 sbp = sb.prototype = new F();
220 if(spp.constructor == Object.prototype.constructor){
225 sb.override = function(o){
229 Roo.override(sb, overrides);
235 * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name.
237 Roo.override(MyClass, {
238 newMethod1: function(){
241 newMethod2: function(foo){
246 * @param {Object} origclass The class to override
247 * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal
248 * containing one or more methods.
251 override : function(origclass, overrides){
253 var p = origclass.prototype;
254 for(var method in overrides){
255 p[method] = overrides[method];
260 * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
262 Roo.namespace('Company', 'Company.data');
263 Company.Widget = function() { ... }
264 Company.data.CustomStore = function(config) { ... }
266 * @param {String} namespace1
267 * @param {String} namespace2
268 * @param {String} etc
271 namespace : function(){
272 var a=arguments, o=null, i, j, d, rt;
273 for (i=0; i<a.length; ++i) {
277 eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
278 for (j=1; j<d.length; ++j) {
279 o[d[j]]=o[d[j]] || {};
285 * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
287 Roo.factory({ xns: Roo.data, xtype : 'Store', .....});
288 Roo.factory(conf, Roo.data);
290 * @param {String} classname
291 * @param {String} namespace (optional)
295 factory : function(c, ns)
297 // no xtype, no ns or c.xns - or forced off by c.xns
298 if (!c.xtype || (!ns && !c.xns) || (c.xns === false)) { // not enough info...
301 ns = c.xns ? c.xns : ns; // if c.xns is set, then use that..
302 if (c.constructor == ns[c.xtype]) {// already created...
306 if (Roo.debug) Roo.log("Roo.Factory(" + c.xtype + ")");
307 var ret = new ns[c.xtype](c);
311 c.xns = false; // prevent recursion..
315 * Logs to console if it can.
317 * @param {String|Object} string
322 if ((typeof(console) == 'undefined') || (typeof(console.log) == 'undefined')) {
329 * Takes an object and converts it to an encoded URL. e.g. Roo.urlEncode({foo: 1, bar: 2}); would return "foo=1&bar=2". Optionally, property values can be arrays, instead of keys and the resulting string that's returned will contain a name/value pair for each array value.
333 urlEncode : function(o){
339 var ov = o[key], k = encodeURIComponent(key);
340 var type = typeof ov;
341 if(type == 'undefined'){
343 }else if(type != "function" && type != "object"){
344 buf.push(k, "=", encodeURIComponent(ov), "&");
345 }else if(ov instanceof Array){
347 for(var i = 0, len = ov.length; i < len; i++) {
348 buf.push(k, "=", encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
360 * Takes an encoded URL and and converts it to an object. e.g. Roo.urlDecode("foo=1&bar=2"); would return {foo: 1, bar: 2} or Roo.urlDecode("foo=1&bar=2&bar=3&bar=4", true); would return {foo: 1, bar: [2, 3, 4]}.
361 * @param {String} string
362 * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
363 * @return {Object} A literal with members
365 urlDecode : function(string, overwrite){
366 if(!string || !string.length){
370 var pairs = string.split('&');
371 var pair, name, value;
372 for(var i = 0, len = pairs.length; i < len; i++){
373 pair = pairs[i].split('=');
374 name = decodeURIComponent(pair[0]);
375 value = decodeURIComponent(pair[1]);
376 if(overwrite !== true){
377 if(typeof obj[name] == "undefined"){
379 }else if(typeof obj[name] == "string"){
380 obj[name] = [obj[name]];
381 obj[name].push(value);
383 obj[name].push(value);
393 * Iterates an array calling the passed function with each item, stopping if your function returns false. If the
394 * passed array is not really an array, your function is called once with it.
395 * The supplied function is called with (Object item, Number index, Array allItems).
396 * @param {Array/NodeList/Mixed} array
397 * @param {Function} fn
398 * @param {Object} scope
400 each : function(array, fn, scope){
401 if(typeof array.length == "undefined" || typeof array == "string"){
404 for(var i = 0, len = array.length; i < len; i++){
405 if(fn.call(scope || array[i], array[i], i, array) === false){ return i; };
410 combine : function(){
411 var as = arguments, l = as.length, r = [];
412 for(var i = 0; i < l; i++){
414 if(a instanceof Array){
416 }else if(a.length !== undefined && !a.substr){
417 r = r.concat(Array.prototype.slice.call(a, 0));
426 * Escapes the passed string for use in a regular expression
427 * @param {String} str
430 escapeRe : function(s) {
431 return s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1");
435 callback : function(cb, scope, args, delay){
436 if(typeof cb == "function"){
438 cb.defer(delay, scope, args || []);
440 cb.apply(scope, args || []);
446 * Return the dom node for the passed string (id), dom node, or Roo.Element
447 * @param {String/HTMLElement/Roo.Element} el
448 * @return HTMLElement
450 getDom : function(el){
454 return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
458 * Shorthand for {@link Roo.ComponentMgr#get}
460 * @return Roo.Component
462 getCmp : function(id){
463 return Roo.ComponentMgr.get(id);
466 num : function(v, defaultValue){
467 if(typeof v != 'number'){
473 destroy : function(){
474 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
478 as.removeAllListeners();
482 if(typeof as.purgeListeners == 'function'){
485 if(typeof as.destroy == 'function'){
492 // inpired by a similar function in mootools library
494 * Returns the type of object that is passed in. If the object passed in is null or undefined it
495 * return false otherwise it returns one of the following values:<ul>
496 * <li><b>string</b>: If the object passed is a string</li>
497 * <li><b>number</b>: If the object passed is a number</li>
498 * <li><b>boolean</b>: If the object passed is a boolean value</li>
499 * <li><b>function</b>: If the object passed is a function reference</li>
500 * <li><b>object</b>: If the object passed is an object</li>
501 * <li><b>array</b>: If the object passed is an array</li>
502 * <li><b>regexp</b>: If the object passed is a regular expression</li>
503 * <li><b>element</b>: If the object passed is a DOM Element</li>
504 * <li><b>nodelist</b>: If the object passed is a DOM NodeList</li>
505 * <li><b>textnode</b>: If the object passed is a DOM text node and contains something other than whitespace</li>
506 * <li><b>whitespace</b>: If the object passed is a DOM text node and contains only whitespace</li>
507 * @param {Mixed} object
511 if(o === undefined || o === null){
518 if(t == 'object' && o.nodeName) {
520 case 1: return 'element';
521 case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace';
524 if(t == 'object' || t == 'function') {
525 switch(o.constructor) {
526 case Array: return 'array';
527 case RegExp: return 'regexp';
529 if(typeof o.length == 'number' && typeof o.item == 'function') {
537 * Returns true if the passed value is null, undefined or an empty string (optional).
538 * @param {Mixed} value The value to test
539 * @param {Boolean} allowBlank (optional) Pass true if an empty string is not considered empty
542 isEmpty : function(v, allowBlank){
543 return v === null || v === undefined || (!allowBlank ? v === '' : false);
557 isBorderBox : isBorderBox,
559 isWindows : isWindows,
566 * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
567 * you may want to set this to true.
570 useShims : ((isIE && !isIE7) || (isGecko && isMac))
576 Roo.namespace("Roo", "Roo.util", "Roo.grid", "Roo.dd", "Roo.tree", "Roo.data",
577 "Roo.form", "Roo.menu", "Roo.state", "Roo.lib", "Roo.layout", "Roo.app", "Roo.ux");
580 * Ext JS Library 1.1.1
581 * Copyright(c) 2006-2007, Ext JS, LLC.
583 * Originally Released Under LGPL - original licence link has changed is not relivant.
586 * <script type="text/javascript">
590 // wrappedn so fnCleanup is not in global scope...
592 function fnCleanUp() {
593 var p = Function.prototype;
594 delete p.createSequence;
596 delete p.createDelegate;
597 delete p.createCallback;
598 delete p.createInterceptor;
600 window.detachEvent("onunload", fnCleanUp);
602 window.attachEvent("onunload", fnCleanUp);
609 * These functions are available on every Function object (any JavaScript function).
611 Roo.apply(Function.prototype, {
613 * Creates a callback that passes arguments[0], arguments[1], arguments[2], ...
614 * Call directly on any function. Example: <code>myFunction.createCallback(myarg, myarg2)</code>
615 * Will create a function that is bound to those 2 args.
616 * @return {Function} The new function
618 createCallback : function(/*args...*/){
619 // make args available, in function below
620 var args = arguments;
623 return method.apply(window, args);
628 * Creates a delegate (callback) that sets the scope to obj.
629 * Call directly on any function. Example: <code>this.myFunction.createDelegate(this)</code>
630 * Will create a function that is automatically scoped to this.
631 * @param {Object} obj (optional) The object for which the scope is set
632 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
633 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
634 * if a number the args are inserted at the specified position
635 * @return {Function} The new function
637 createDelegate : function(obj, args, appendArgs){
640 var callArgs = args || arguments;
641 if(appendArgs === true){
642 callArgs = Array.prototype.slice.call(arguments, 0);
643 callArgs = callArgs.concat(args);
644 }else if(typeof appendArgs == "number"){
645 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
646 var applyArgs = [appendArgs, 0].concat(args); // create method call params
647 Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
649 return method.apply(obj || window, callArgs);
654 * Calls this function after the number of millseconds specified.
655 * @param {Number} millis The number of milliseconds for the setTimeout call (if 0 the function is executed immediately)
656 * @param {Object} obj (optional) The object for which the scope is set
657 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
658 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
659 * if a number the args are inserted at the specified position
660 * @return {Number} The timeout id that can be used with clearTimeout
662 defer : function(millis, obj, args, appendArgs){
663 var fn = this.createDelegate(obj, args, appendArgs);
665 return setTimeout(fn, millis);
671 * Create a combined function call sequence of the original function + the passed function.
672 * The resulting function returns the results of the original function.
673 * The passed fcn is called with the parameters of the original function
674 * @param {Function} fcn The function to sequence
675 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
676 * @return {Function} The new function
678 createSequence : function(fcn, scope){
679 if(typeof fcn != "function"){
684 var retval = method.apply(this || window, arguments);
685 fcn.apply(scope || this || window, arguments);
691 * Creates an interceptor function. The passed fcn is called before the original one. If it returns false, the original one is not called.
692 * The resulting function returns the results of the original function.
693 * The passed fcn is called with the parameters of the original function.
695 * @param {Function} fcn The function to call before the original
696 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
697 * @return {Function} The new function
699 createInterceptor : function(fcn, scope){
700 if(typeof fcn != "function"){
707 if(fcn.apply(scope || this || window, arguments) === false){
710 return method.apply(this || window, arguments);
716 * Ext JS Library 1.1.1
717 * Copyright(c) 2006-2007, Ext JS, LLC.
719 * Originally Released Under LGPL - original licence link has changed is not relivant.
722 * <script type="text/javascript">
725 Roo.applyIf(String, {
730 * Escapes the passed string for ' and \
731 * @param {String} string The string to escape
732 * @return {String} The escaped string
735 escape : function(string) {
736 return string.replace(/('|\\)/g, "\\$1");
740 * Pads the left side of a string with a specified character. This is especially useful
741 * for normalizing number and date strings. Example usage:
743 var s = String.leftPad('123', 5, '0');
744 // s now contains the string: '00123'
746 * @param {String} string The original string
747 * @param {Number} size The total length of the output string
748 * @param {String} char (optional) The character with which to pad the original string (defaults to empty string " ")
749 * @return {String} The padded string
752 leftPad : function (val, size, ch) {
753 var result = new String(val);
754 if(ch === null || ch === undefined || ch === '') {
757 while (result.length < size) {
758 result = ch + result;
764 * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
765 * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
767 var cls = 'my-class', text = 'Some text';
768 var s = String.format('<div class="{0}">{1}</div>', cls, text);
769 // s now contains the string: '<div class="my-class">Some text</div>'
771 * @param {String} string The tokenized string to be formatted
772 * @param {String} value1 The value to replace token {0}
773 * @param {String} value2 Etc...
774 * @return {String} The formatted string
777 format : function(format){
778 var args = Array.prototype.slice.call(arguments, 1);
779 return format.replace(/\{(\d+)\}/g, function(m, i){
780 return Roo.util.Format.htmlEncode(args[i]);
786 * Utility function that allows you to easily switch a string between two alternating values. The passed value
787 * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
788 * they are already different, the first value passed in is returned. Note that this method returns the new value
789 * but does not change the current string.
791 // alternate sort directions
792 sort = sort.toggle('ASC', 'DESC');
794 // instead of conditional logic:
795 sort = (sort == 'ASC' ? 'DESC' : 'ASC');
797 * @param {String} value The value to compare to the current string
798 * @param {String} other The new value to use if the string already equals the first value passed in
799 * @return {String} The new value
802 String.prototype.toggle = function(value, other){
803 return this == value ? other : value;
806 * Ext JS Library 1.1.1
807 * Copyright(c) 2006-2007, Ext JS, LLC.
809 * Originally Released Under LGPL - original licence link has changed is not relivant.
812 * <script type="text/javascript">
818 Roo.applyIf(Number.prototype, {
820 * Checks whether or not the current number is within a desired range. If the number is already within the
821 * range it is returned, otherwise the min or max value is returned depending on which side of the range is
822 * exceeded. Note that this method returns the constrained value but does not change the current number.
823 * @param {Number} min The minimum number in the range
824 * @param {Number} max The maximum number in the range
825 * @return {Number} The constrained value if outside the range, otherwise the current value
827 constrain : function(min, max){
828 return Math.min(Math.max(this, min), max);
832 * Ext JS Library 1.1.1
833 * Copyright(c) 2006-2007, Ext JS, LLC.
835 * Originally Released Under LGPL - original licence link has changed is not relivant.
838 * <script type="text/javascript">
843 Roo.applyIf(Array.prototype, {
845 * Checks whether or not the specified object exists in the array.
846 * @param {Object} o The object to check for
847 * @return {Number} The index of o in the array (or -1 if it is not found)
849 indexOf : function(o){
850 for (var i = 0, len = this.length; i < len; i++){
851 if(this[i] == o) return i;
857 * Removes the specified object from the array. If the object is not found nothing happens.
858 * @param {Object} o The object to remove
860 remove : function(o){
861 var index = this.indexOf(o);
863 this.splice(index, 1);
867 * Map (JS 1.6 compatibility)
868 * @param {Function} function to call
872 var len = this.length >>> 0;
873 if (typeof fun != "function")
874 throw new TypeError();
876 var res = new Array(len);
877 var thisp = arguments[1];
878 for (var i = 0; i < len; i++)
881 res[i] = fun.call(thisp, this[i], i, this);
892 * Ext JS Library 1.1.1
893 * Copyright(c) 2006-2007, Ext JS, LLC.
895 * Originally Released Under LGPL - original licence link has changed is not relivant.
898 * <script type="text/javascript">
904 * The date parsing and format syntax is a subset of
905 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
906 * supported will provide results equivalent to their PHP versions.
908 * Following is the list of all currently supported formats:
911 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
913 Format Output Description
914 ------ ---------- --------------------------------------------------------------
915 d 10 Day of the month, 2 digits with leading zeros
916 D Wed A textual representation of a day, three letters
917 j 10 Day of the month without leading zeros
918 l Wednesday A full textual representation of the day of the week
919 S th English ordinal day of month suffix, 2 chars (use with j)
920 w 3 Numeric representation of the day of the week
921 z 9 The julian date, or day of the year (0-365)
922 W 01 ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
923 F January A full textual representation of the month
924 m 01 Numeric representation of a month, with leading zeros
925 M Jan Month name abbreviation, three letters
926 n 1 Numeric representation of a month, without leading zeros
927 t 31 Number of days in the given month
928 L 0 Whether it's a leap year (1 if it is a leap year, else 0)
929 Y 2007 A full numeric representation of a year, 4 digits
930 y 07 A two digit representation of a year
931 a pm Lowercase Ante meridiem and Post meridiem
932 A PM Uppercase Ante meridiem and Post meridiem
933 g 3 12-hour format of an hour without leading zeros
934 G 15 24-hour format of an hour without leading zeros
935 h 03 12-hour format of an hour with leading zeros
936 H 15 24-hour format of an hour with leading zeros
937 i 05 Minutes with leading zeros
938 s 01 Seconds, with leading zeros
939 O -0600 Difference to Greenwich time (GMT) in hours
940 T CST Timezone setting of the machine running the code
941 Z -21600 Timezone offset in seconds (negative if west of UTC, positive if east)
944 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
946 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
947 document.write(dt.format('Y-m-d')); //2007-01-10
948 document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
949 document.write(dt.format('l, \\t\\he dS of F Y h:i:s A')); //Wednesday, the 10th of January 2007 03:05:01 PM
952 * Here are some standard date/time patterns that you might find helpful. They
953 * are not part of the source of Date.js, but to use them you can simply copy this
954 * block of code into any script that is included after Date.js and they will also become
955 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
958 ISO8601Long:"Y-m-d H:i:s",
959 ISO8601Short:"Y-m-d",
961 LongDate: "l, F d, Y",
962 FullDateTime: "l, F d, Y g:i:s A",
966 SortableDateTime: "Y-m-d\\TH:i:s",
967 UniversalSortableDateTime: "Y-m-d H:i:sO",
975 document.write(dt.format(Date.patterns.ShortDate));
980 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
981 * They generate precompiled functions from date formats instead of parsing and
982 * processing the pattern every time you format a date. These functions are available
983 * on every Date object (any javascript function).
985 * The original article and download are here:
986 * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
993 Returns the number of milliseconds between this date and date
994 @param {Date} date (optional) Defaults to now
995 @return {Number} The diff in milliseconds
996 @member Date getElapsed
998 Date.prototype.getElapsed = function(date) {
999 return Math.abs((date || new Date()).getTime()-this.getTime());
1001 // was in date file..
1005 Date.parseFunctions = {count:0};
1007 Date.parseRegexes = [];
1009 Date.formatFunctions = {count:0};
1012 Date.prototype.dateFormat = function(format) {
1013 if (Date.formatFunctions[format] == null) {
1014 Date.createNewFormat(format);
1016 var func = Date.formatFunctions[format];
1017 return this[func]();
1022 * Formats a date given the supplied format string
1023 * @param {String} format The format string
1024 * @return {String} The formatted date
1027 Date.prototype.format = Date.prototype.dateFormat;
1030 Date.createNewFormat = function(format) {
1031 var funcName = "format" + Date.formatFunctions.count++;
1032 Date.formatFunctions[format] = funcName;
1033 var code = "Date.prototype." + funcName + " = function(){return ";
1034 var special = false;
1036 for (var i = 0; i < format.length; ++i) {
1037 ch = format.charAt(i);
1038 if (!special && ch == "\\") {
1043 code += "'" + String.escape(ch) + "' + ";
1046 code += Date.getFormatCode(ch);
1049 /** eval:var:zzzzzzzzzzzzz */
1050 eval(code.substring(0, code.length - 3) + ";}");
1054 Date.getFormatCode = function(character) {
1055 switch (character) {
1057 return "String.leftPad(this.getDate(), 2, '0') + ";
1059 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
1061 return "this.getDate() + ";
1063 return "Date.dayNames[this.getDay()] + ";
1065 return "this.getSuffix() + ";
1067 return "this.getDay() + ";
1069 return "this.getDayOfYear() + ";
1071 return "this.getWeekOfYear() + ";
1073 return "Date.monthNames[this.getMonth()] + ";
1075 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
1077 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
1079 return "(this.getMonth() + 1) + ";
1081 return "this.getDaysInMonth() + ";
1083 return "(this.isLeapYear() ? 1 : 0) + ";
1085 return "this.getFullYear() + ";
1087 return "('' + this.getFullYear()).substring(2, 4) + ";
1089 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
1091 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
1093 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
1095 return "this.getHours() + ";
1097 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
1099 return "String.leftPad(this.getHours(), 2, '0') + ";
1101 return "String.leftPad(this.getMinutes(), 2, '0') + ";
1103 return "String.leftPad(this.getSeconds(), 2, '0') + ";
1105 return "this.getGMTOffset() + ";
1107 return "this.getTimezone() + ";
1109 return "(this.getTimezoneOffset() * -60) + ";
1111 return "'" + String.escape(character) + "' + ";
1116 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
1117 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
1118 * the date format that is not specified will default to the current date value for that part. Time parts can also
1119 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
1120 * string or the parse operation will fail.
1123 //dt = Fri May 25 2007 (current date)
1124 var dt = new Date();
1126 //dt = Thu May 25 2006 (today's month/day in 2006)
1127 dt = Date.parseDate("2006", "Y");
1129 //dt = Sun Jan 15 2006 (all date parts specified)
1130 dt = Date.parseDate("2006-1-15", "Y-m-d");
1132 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
1133 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
1135 * @param {String} input The unparsed date as a string
1136 * @param {String} format The format the date is in
1137 * @return {Date} The parsed date
1140 Date.parseDate = function(input, format) {
1141 if (Date.parseFunctions[format] == null) {
1142 Date.createParser(format);
1144 var func = Date.parseFunctions[format];
1145 return Date[func](input);
1150 Date.createParser = function(format) {
1151 var funcName = "parse" + Date.parseFunctions.count++;
1152 var regexNum = Date.parseRegexes.length;
1153 var currentGroup = 1;
1154 Date.parseFunctions[format] = funcName;
1156 var code = "Date." + funcName + " = function(input){\n"
1157 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
1158 + "var d = new Date();\n"
1159 + "y = d.getFullYear();\n"
1160 + "m = d.getMonth();\n"
1161 + "d = d.getDate();\n"
1162 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
1163 + "if (results && results.length > 0) {";
1166 var special = false;
1168 for (var i = 0; i < format.length; ++i) {
1169 ch = format.charAt(i);
1170 if (!special && ch == "\\") {
1175 regex += String.escape(ch);
1178 var obj = Date.formatCodeToRegex(ch, currentGroup);
1179 currentGroup += obj.g;
1181 if (obj.g && obj.c) {
1187 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
1188 + "{v = new Date(y, m, d, h, i, s);}\n"
1189 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
1190 + "{v = new Date(y, m, d, h, i);}\n"
1191 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
1192 + "{v = new Date(y, m, d, h);}\n"
1193 + "else if (y >= 0 && m >= 0 && d > 0)\n"
1194 + "{v = new Date(y, m, d);}\n"
1195 + "else if (y >= 0 && m >= 0)\n"
1196 + "{v = new Date(y, m);}\n"
1197 + "else if (y >= 0)\n"
1198 + "{v = new Date(y);}\n"
1199 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
1200 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
1201 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
1204 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
1205 /** eval:var:zzzzzzzzzzzzz */
1210 Date.formatCodeToRegex = function(character, currentGroup) {
1211 switch (character) {
1215 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
1218 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1219 s:"(\\d{1,2})"}; // day of month without leading zeroes
1222 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1223 s:"(\\d{2})"}; // day of month with leading zeroes
1227 s:"(?:" + Date.dayNames.join("|") + ")"};
1231 s:"(?:st|nd|rd|th)"};
1246 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
1247 s:"(" + Date.monthNames.join("|") + ")"};
1250 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
1251 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
1254 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1255 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
1258 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1259 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
1270 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
1274 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
1275 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
1279 c:"if (results[" + currentGroup + "] == 'am') {\n"
1280 + "if (h == 12) { h = 0; }\n"
1281 + "} else { if (h < 12) { h += 12; }}",
1285 c:"if (results[" + currentGroup + "] == 'AM') {\n"
1286 + "if (h == 12) { h = 0; }\n"
1287 + "} else { if (h < 12) { h += 12; }}",
1292 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1293 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
1297 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1298 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
1301 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
1305 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
1310 "o = results[", currentGroup, "];\n",
1311 "var sn = o.substring(0,1);\n", // get + / - sign
1312 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
1313 "var mn = o.substring(3,5) % 60;\n", // get minutes
1314 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
1315 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1321 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
1324 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
1325 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
1326 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
1330 s:String.escape(character)};
1335 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
1336 * @return {String} The abbreviated timezone name (e.g. 'CST')
1338 Date.prototype.getTimezone = function() {
1339 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
1343 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
1344 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
1346 Date.prototype.getGMTOffset = function() {
1347 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1348 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1349 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
1353 * Get the numeric day number of the year, adjusted for leap year.
1354 * @return {Number} 0 through 364 (365 in leap years)
1356 Date.prototype.getDayOfYear = function() {
1358 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1359 for (var i = 0; i < this.getMonth(); ++i) {
1360 num += Date.daysInMonth[i];
1362 return num + this.getDate() - 1;
1366 * Get the string representation of the numeric week number of the year
1367 * (equivalent to the format specifier 'W').
1368 * @return {String} '00' through '52'
1370 Date.prototype.getWeekOfYear = function() {
1371 // Skip to Thursday of this week
1372 var now = this.getDayOfYear() + (4 - this.getDay());
1373 // Find the first Thursday of the year
1374 var jan1 = new Date(this.getFullYear(), 0, 1);
1375 var then = (7 - jan1.getDay() + 4);
1376 return String.leftPad(((now - then) / 7) + 1, 2, "0");
1380 * Whether or not the current date is in a leap year.
1381 * @return {Boolean} True if the current date is in a leap year, else false
1383 Date.prototype.isLeapYear = function() {
1384 var year = this.getFullYear();
1385 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
1389 * Get the first day of the current month, adjusted for leap year. The returned value
1390 * is the numeric day index within the week (0-6) which can be used in conjunction with
1391 * the {@link #monthNames} array to retrieve the textual day name.
1394 var dt = new Date('1/10/2007');
1395 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
1397 * @return {Number} The day number (0-6)
1399 Date.prototype.getFirstDayOfMonth = function() {
1400 var day = (this.getDay() - (this.getDate() - 1)) % 7;
1401 return (day < 0) ? (day + 7) : day;
1405 * Get the last day of the current month, adjusted for leap year. The returned value
1406 * is the numeric day index within the week (0-6) which can be used in conjunction with
1407 * the {@link #monthNames} array to retrieve the textual day name.
1410 var dt = new Date('1/10/2007');
1411 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
1413 * @return {Number} The day number (0-6)
1415 Date.prototype.getLastDayOfMonth = function() {
1416 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
1417 return (day < 0) ? (day + 7) : day;
1422 * Get the first date of this date's month
1425 Date.prototype.getFirstDateOfMonth = function() {
1426 return new Date(this.getFullYear(), this.getMonth(), 1);
1430 * Get the last date of this date's month
1433 Date.prototype.getLastDateOfMonth = function() {
1434 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
1437 * Get the number of days in the current month, adjusted for leap year.
1438 * @return {Number} The number of days in the month
1440 Date.prototype.getDaysInMonth = function() {
1441 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1442 return Date.daysInMonth[this.getMonth()];
1446 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
1447 * @return {String} 'st, 'nd', 'rd' or 'th'
1449 Date.prototype.getSuffix = function() {
1450 switch (this.getDate()) {
1467 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
1470 * An array of textual month names.
1471 * Override these values for international dates, for example...
1472 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
1491 * An array of textual day names.
1492 * Override these values for international dates, for example...
1493 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
1509 Date.monthNumbers = {
1524 * Creates and returns a new Date instance with the exact same date value as the called instance.
1525 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
1526 * variable will also be changed. When the intention is to create a new variable that will not
1527 * modify the original instance, you should create a clone.
1529 * Example of correctly cloning a date:
1532 var orig = new Date('10/1/2006');
1535 document.write(orig); //returns 'Thu Oct 05 2006'!
1538 var orig = new Date('10/1/2006');
1539 var copy = orig.clone();
1541 document.write(orig); //returns 'Thu Oct 01 2006'
1543 * @return {Date} The new Date instance
1545 Date.prototype.clone = function() {
1546 return new Date(this.getTime());
1550 * Clears any time information from this date
1551 @param {Boolean} clone true to create a clone of this date, clear the time and return it
1552 @return {Date} this or the clone
1554 Date.prototype.clearTime = function(clone){
1556 return this.clone().clearTime();
1561 this.setMilliseconds(0);
1566 // safari setMonth is broken
1568 Date.brokenSetMonth = Date.prototype.setMonth;
1569 Date.prototype.setMonth = function(num){
1571 var n = Math.ceil(-num);
1572 var back_year = Math.ceil(n/12);
1573 var month = (n % 12) ? 12 - n % 12 : 0 ;
1574 this.setFullYear(this.getFullYear() - back_year);
1575 return Date.brokenSetMonth.call(this, month);
1577 return Date.brokenSetMonth.apply(this, arguments);
1582 /** Date interval constant
1586 /** Date interval constant
1590 /** Date interval constant
1594 /** Date interval constant
1598 /** Date interval constant
1602 /** Date interval constant
1606 /** Date interval constant
1612 * Provides a convenient method of performing basic date arithmetic. This method
1613 * does not modify the Date instance being called - it creates and returns
1614 * a new Date instance containing the resulting date value.
1619 var dt = new Date('10/29/2006').add(Date.DAY, 5);
1620 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
1622 //Negative values will subtract correctly:
1623 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
1624 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
1626 //You can even chain several calls together in one line!
1627 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
1628 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
1631 * @param {String} interval A valid date interval enum value
1632 * @param {Number} value The amount to add to the current date
1633 * @return {Date} The new Date instance
1635 Date.prototype.add = function(interval, value){
1636 var d = this.clone();
1637 if (!interval || value === 0) return d;
1638 switch(interval.toLowerCase()){
1640 d.setMilliseconds(this.getMilliseconds() + value);
1643 d.setSeconds(this.getSeconds() + value);
1646 d.setMinutes(this.getMinutes() + value);
1649 d.setHours(this.getHours() + value);
1652 d.setDate(this.getDate() + value);
1655 var day = this.getDate();
1657 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
1660 d.setMonth(this.getMonth() + value);
1663 d.setFullYear(this.getFullYear() + value);
1669 * Ext JS Library 1.1.1
1670 * Copyright(c) 2006-2007, Ext JS, LLC.
1672 * Originally Released Under LGPL - original licence link has changed is not relivant.
1675 * <script type="text/javascript">
1679 getViewWidth : function(full) {
1680 return full ? this.getDocumentWidth() : this.getViewportWidth();
1683 getViewHeight : function(full) {
1684 return full ? this.getDocumentHeight() : this.getViewportHeight();
1687 getDocumentHeight: function() {
1688 var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
1689 return Math.max(scrollHeight, this.getViewportHeight());
1692 getDocumentWidth: function() {
1693 var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
1694 return Math.max(scrollWidth, this.getViewportWidth());
1697 getViewportHeight: function() {
1698 var height = self.innerHeight;
1699 var mode = document.compatMode;
1701 if ((mode || Roo.isIE) && !Roo.isOpera) {
1702 height = (mode == "CSS1Compat") ?
1703 document.documentElement.clientHeight :
1704 document.body.clientHeight;
1710 getViewportWidth: function() {
1711 var width = self.innerWidth;
1712 var mode = document.compatMode;
1714 if (mode || Roo.isIE) {
1715 width = (mode == "CSS1Compat") ?
1716 document.documentElement.clientWidth :
1717 document.body.clientWidth;
1722 isAncestor : function(p, c) {
1729 if (p.contains && !Roo.isSafari) {
1730 return p.contains(c);
1731 } else if (p.compareDocumentPosition) {
1732 return !!(p.compareDocumentPosition(c) & 16);
1734 var parent = c.parentNode;
1739 else if (!parent.tagName || parent.tagName.toUpperCase() == "HTML") {
1742 parent = parent.parentNode;
1748 getRegion : function(el) {
1749 return Roo.lib.Region.getRegion(el);
1752 getY : function(el) {
1753 return this.getXY(el)[1];
1756 getX : function(el) {
1757 return this.getXY(el)[0];
1760 getXY : function(el) {
1761 var p, pe, b, scroll, bd = document.body;
1762 el = Roo.getDom(el);
1763 var fly = Roo.lib.AnimBase.fly;
1764 if (el.getBoundingClientRect) {
1765 b = el.getBoundingClientRect();
1766 scroll = fly(document).getScroll();
1767 return [b.left + scroll.left, b.top + scroll.top];
1773 var hasAbsolute = fly(el).getStyle("position") == "absolute";
1780 if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
1787 var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
1788 var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
1795 if (p != el && pe.getStyle('overflow') != 'visible') {
1803 if (Roo.isSafari && hasAbsolute) {
1808 if (Roo.isGecko && !hasAbsolute) {
1810 x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
1811 y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
1815 while (p && p != bd) {
1816 if (!Roo.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
1828 setXY : function(el, xy) {
1829 el = Roo.fly(el, '_setXY');
1831 var pts = el.translatePoints(xy);
1832 if (xy[0] !== false) {
1833 el.dom.style.left = pts.left + "px";
1835 if (xy[1] !== false) {
1836 el.dom.style.top = pts.top + "px";
1840 setX : function(el, x) {
1841 this.setXY(el, [x, false]);
1844 setY : function(el, y) {
1845 this.setXY(el, [false, y]);
1849 * Portions of this file are based on pieces of Yahoo User Interface Library
1850 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
1851 * YUI licensed under the BSD License:
1852 * http://developer.yahoo.net/yui/license.txt
1853 * <script type="text/javascript">
1857 Roo.lib.Event = function() {
1858 var loadComplete = false;
1860 var unloadListeners = [];
1862 var onAvailStack = [];
1864 var lastError = null;
1877 startInterval: function() {
1878 if (!this._interval) {
1880 var callback = function() {
1881 self._tryPreloadAttach();
1883 this._interval = setInterval(callback, this.POLL_INTERVAL);
1888 onAvailable: function(p_id, p_fn, p_obj, p_override) {
1889 onAvailStack.push({ id: p_id,
1892 override: p_override,
1893 checkReady: false });
1895 retryCount = this.POLL_RETRYS;
1896 this.startInterval();
1900 addListener: function(el, eventName, fn) {
1901 el = Roo.getDom(el);
1906 if ("unload" == eventName) {
1907 unloadListeners[unloadListeners.length] =
1908 [el, eventName, fn];
1912 var wrappedFn = function(e) {
1913 return fn(Roo.lib.Event.getEvent(e));
1916 var li = [el, eventName, fn, wrappedFn];
1918 var index = listeners.length;
1919 listeners[index] = li;
1921 this.doAdd(el, eventName, wrappedFn, false);
1927 removeListener: function(el, eventName, fn) {
1930 el = Roo.getDom(el);
1933 return this.purgeElement(el, false, eventName);
1937 if ("unload" == eventName) {
1939 for (i = 0,len = unloadListeners.length; i < len; i++) {
1940 var li = unloadListeners[i];
1943 li[1] == eventName &&
1945 unloadListeners.splice(i, 1);
1953 var cacheItem = null;
1956 var index = arguments[3];
1958 if ("undefined" == typeof index) {
1959 index = this._getCacheIndex(el, eventName, fn);
1963 cacheItem = listeners[index];
1966 if (!el || !cacheItem) {
1970 this.doRemove(el, eventName, cacheItem[this.WFN], false);
1972 delete listeners[index][this.WFN];
1973 delete listeners[index][this.FN];
1974 listeners.splice(index, 1);
1981 getTarget: function(ev, resolveTextNode) {
1982 ev = ev.browserEvent || ev;
1983 var t = ev.target || ev.srcElement;
1984 return this.resolveTextNode(t);
1988 resolveTextNode: function(node) {
1989 if (Roo.isSafari && node && 3 == node.nodeType) {
1990 return node.parentNode;
1997 getPageX: function(ev) {
1998 ev = ev.browserEvent || ev;
2000 if (!x && 0 !== x) {
2001 x = ev.clientX || 0;
2004 x += this.getScroll()[1];
2012 getPageY: function(ev) {
2013 ev = ev.browserEvent || ev;
2015 if (!y && 0 !== y) {
2016 y = ev.clientY || 0;
2019 y += this.getScroll()[0];
2028 getXY: function(ev) {
2029 ev = ev.browserEvent || ev;
2030 return [this.getPageX(ev), this.getPageY(ev)];
2034 getRelatedTarget: function(ev) {
2035 ev = ev.browserEvent || ev;
2036 var t = ev.relatedTarget;
2038 if (ev.type == "mouseout") {
2040 } else if (ev.type == "mouseover") {
2045 return this.resolveTextNode(t);
2049 getTime: function(ev) {
2050 ev = ev.browserEvent || ev;
2052 var t = new Date().getTime();
2056 this.lastError = ex;
2065 stopEvent: function(ev) {
2066 this.stopPropagation(ev);
2067 this.preventDefault(ev);
2071 stopPropagation: function(ev) {
2072 ev = ev.browserEvent || ev;
2073 if (ev.stopPropagation) {
2074 ev.stopPropagation();
2076 ev.cancelBubble = true;
2081 preventDefault: function(ev) {
2082 ev = ev.browserEvent || ev;
2083 if(ev.preventDefault) {
2084 ev.preventDefault();
2086 ev.returnValue = false;
2091 getEvent: function(e) {
2092 var ev = e || window.event;
2094 var c = this.getEvent.caller;
2096 ev = c.arguments[0];
2097 if (ev && Event == ev.constructor) {
2107 getCharCode: function(ev) {
2108 ev = ev.browserEvent || ev;
2109 return ev.charCode || ev.keyCode || 0;
2113 _getCacheIndex: function(el, eventName, fn) {
2114 for (var i = 0,len = listeners.length; i < len; ++i) {
2115 var li = listeners[i];
2117 li[this.FN] == fn &&
2118 li[this.EL] == el &&
2119 li[this.TYPE] == eventName) {
2131 getEl: function(id) {
2132 return document.getElementById(id);
2136 clearCache: function() {
2140 _load: function(e) {
2141 loadComplete = true;
2142 var EU = Roo.lib.Event;
2146 EU.doRemove(window, "load", EU._load);
2151 _tryPreloadAttach: function() {
2160 var tryAgain = !loadComplete;
2162 tryAgain = (retryCount > 0);
2167 for (var i = 0,len = onAvailStack.length; i < len; ++i) {
2168 var item = onAvailStack[i];
2170 var el = this.getEl(item.id);
2173 if (!item.checkReady ||
2176 (document && document.body)) {
2179 if (item.override) {
2180 if (item.override === true) {
2183 scope = item.override;
2186 item.fn.call(scope, item.obj);
2187 onAvailStack[i] = null;
2190 notAvail.push(item);
2195 retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;
2199 this.startInterval();
2201 clearInterval(this._interval);
2202 this._interval = null;
2205 this.locked = false;
2212 purgeElement: function(el, recurse, eventName) {
2213 var elListeners = this.getListeners(el, eventName);
2215 for (var i = 0,len = elListeners.length; i < len; ++i) {
2216 var l = elListeners[i];
2217 this.removeListener(el, l.type, l.fn);
2221 if (recurse && el && el.childNodes) {
2222 for (i = 0,len = el.childNodes.length; i < len; ++i) {
2223 this.purgeElement(el.childNodes[i], recurse, eventName);
2229 getListeners: function(el, eventName) {
2230 var results = [], searchLists;
2232 searchLists = [listeners, unloadListeners];
2233 } else if (eventName == "unload") {
2234 searchLists = [unloadListeners];
2236 searchLists = [listeners];
2239 for (var j = 0; j < searchLists.length; ++j) {
2240 var searchList = searchLists[j];
2241 if (searchList && searchList.length > 0) {
2242 for (var i = 0,len = searchList.length; i < len; ++i) {
2243 var l = searchList[i];
2244 if (l && l[this.EL] === el &&
2245 (!eventName || eventName === l[this.TYPE])) {
2250 adjust: l[this.ADJ_SCOPE],
2258 return (results.length) ? results : null;
2262 _unload: function(e) {
2264 var EU = Roo.lib.Event, i, j, l, len, index;
2266 for (i = 0,len = unloadListeners.length; i < len; ++i) {
2267 l = unloadListeners[i];
2270 if (l[EU.ADJ_SCOPE]) {
2271 if (l[EU.ADJ_SCOPE] === true) {
2274 scope = l[EU.ADJ_SCOPE];
2277 l[EU.FN].call(scope, EU.getEvent(e), l[EU.OBJ]);
2278 unloadListeners[i] = null;
2284 unloadListeners = null;
2286 if (listeners && listeners.length > 0) {
2287 j = listeners.length;
2290 l = listeners[index];
2292 EU.removeListener(l[EU.EL], l[EU.TYPE],
2302 EU.doRemove(window, "unload", EU._unload);
2307 getScroll: function() {
2308 var dd = document.documentElement, db = document.body;
2309 if (dd && (dd.scrollTop || dd.scrollLeft)) {
2310 return [dd.scrollTop, dd.scrollLeft];
2312 return [db.scrollTop, db.scrollLeft];
2319 doAdd: function () {
2320 if (window.addEventListener) {
2321 return function(el, eventName, fn, capture) {
2322 el.addEventListener(eventName, fn, (capture));
2324 } else if (window.attachEvent) {
2325 return function(el, eventName, fn, capture) {
2326 el.attachEvent("on" + eventName, fn);
2335 doRemove: function() {
2336 if (window.removeEventListener) {
2337 return function (el, eventName, fn, capture) {
2338 el.removeEventListener(eventName, fn, (capture));
2340 } else if (window.detachEvent) {
2341 return function (el, eventName, fn) {
2342 el.detachEvent("on" + eventName, fn);
2354 var E = Roo.lib.Event;
2355 E.on = E.addListener;
2356 E.un = E.removeListener;
2358 if (document && document.body) {
2361 E.doAdd(window, "load", E._load);
2363 E.doAdd(window, "unload", E._unload);
2364 E._tryPreloadAttach();
2368 * Portions of this file are based on pieces of Yahoo User Interface Library
2369 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2370 * YUI licensed under the BSD License:
2371 * http://developer.yahoo.net/yui/license.txt
2372 * <script type="text/javascript">
2379 request : function(method, uri, cb, data, options) {
2381 var hs = options.headers;
2384 if(hs.hasOwnProperty(h)){
2385 this.initHeader(h, hs[h], false);
2389 if(options.xmlData){
2390 this.initHeader('Content-Type', 'text/xml', false);
2392 data = options.xmlData;
2396 return this.asyncRequest(method, uri, cb, data);
2399 serializeForm : function(form) {
2400 if(typeof form == 'string') {
2401 form = (document.getElementById(form) || document.forms[form]);
2404 var el, name, val, disabled, data = '', hasSubmit = false;
2405 for (var i = 0; i < form.elements.length; i++) {
2406 el = form.elements[i];
2407 disabled = form.elements[i].disabled;
2408 name = form.elements[i].name;
2409 val = form.elements[i].value;
2411 if (!disabled && name){
2415 case 'select-multiple':
2416 for (var j = 0; j < el.options.length; j++) {
2417 if (el.options[j].selected) {
2419 data += encodeURIComponent(name) + '=' + encodeURIComponent(el.options[j].attributes['value'].specified ? el.options[j].value : el.options[j].text) + '&';
2422 data += encodeURIComponent(name) + '=' + encodeURIComponent(el.options[j].hasAttribute('value') ? el.options[j].value : el.options[j].text) + '&';
2430 data += encodeURIComponent(name) + '=' + encodeURIComponent(val) + '&';
2443 if(hasSubmit == false) {
2444 data += encodeURIComponent(name) + '=' + encodeURIComponent(val) + '&';
2449 data += encodeURIComponent(name) + '=' + encodeURIComponent(val) + '&';
2454 data = data.substr(0, data.length - 1);
2462 useDefaultHeader:true,
2464 defaultPostHeader:'application/x-www-form-urlencoded',
2466 useDefaultXhrHeader:true,
2468 defaultXhrHeader:'XMLHttpRequest',
2470 hasDefaultHeaders:true,
2482 setProgId:function(id)
2484 this.activeX.unshift(id);
2487 setDefaultPostHeader:function(b)
2489 this.useDefaultHeader = b;
2492 setDefaultXhrHeader:function(b)
2494 this.useDefaultXhrHeader = b;
2497 setPollingInterval:function(i)
2499 if (typeof i == 'number' && isFinite(i)) {
2500 this.pollInterval = i;
2504 createXhrObject:function(transactionId)
2510 http = new XMLHttpRequest();
2512 obj = { conn:http, tId:transactionId };
2516 for (var i = 0; i < this.activeX.length; ++i) {
2520 http = new ActiveXObject(this.activeX[i]);
2522 obj = { conn:http, tId:transactionId };
2535 getConnectionObject:function()
2538 var tId = this.transactionId;
2542 o = this.createXhrObject(tId);
2544 this.transactionId++;
2555 asyncRequest:function(method, uri, callback, postData)
2557 var o = this.getConnectionObject();
2563 o.conn.open(method, uri, true);
2565 if (this.useDefaultXhrHeader) {
2566 if (!this.defaultHeaders['X-Requested-With']) {
2567 this.initHeader('X-Requested-With', this.defaultXhrHeader, true);
2571 if(postData && this.useDefaultHeader){
2572 this.initHeader('Content-Type', this.defaultPostHeader);
2575 if (this.hasDefaultHeaders || this.hasHeaders) {
2579 this.handleReadyState(o, callback);
2580 o.conn.send(postData || null);
2586 handleReadyState:function(o, callback)
2590 if (callback && callback.timeout) {
2591 this.timeout[o.tId] = window.setTimeout(function() {
2592 oConn.abort(o, callback, true);
2593 }, callback.timeout);
2596 this.poll[o.tId] = window.setInterval(
2598 if (o.conn && o.conn.readyState == 4) {
2599 window.clearInterval(oConn.poll[o.tId]);
2600 delete oConn.poll[o.tId];
2602 if(callback && callback.timeout) {
2603 window.clearTimeout(oConn.timeout[o.tId]);
2604 delete oConn.timeout[o.tId];
2607 oConn.handleTransactionResponse(o, callback);
2610 , this.pollInterval);
2613 handleTransactionResponse:function(o, callback, isAbort)
2617 this.releaseObject(o);
2621 var httpStatus, responseObject;
2625 if (o.conn.status !== undefined && o.conn.status != 0) {
2626 httpStatus = o.conn.status;
2638 if (httpStatus >= 200 && httpStatus < 300) {
2639 responseObject = this.createResponseObject(o, callback.argument);
2640 if (callback.success) {
2641 if (!callback.scope) {
2642 callback.success(responseObject);
2647 callback.success.apply(callback.scope, [responseObject]);
2652 switch (httpStatus) {
2660 responseObject = this.createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false));
2661 if (callback.failure) {
2662 if (!callback.scope) {
2663 callback.failure(responseObject);
2666 callback.failure.apply(callback.scope, [responseObject]);
2671 responseObject = this.createResponseObject(o, callback.argument);
2672 if (callback.failure) {
2673 if (!callback.scope) {
2674 callback.failure(responseObject);
2677 callback.failure.apply(callback.scope, [responseObject]);
2683 this.releaseObject(o);
2684 responseObject = null;
2687 createResponseObject:function(o, callbackArg)
2694 var headerStr = o.conn.getAllResponseHeaders();
2695 var header = headerStr.split('\n');
2696 for (var i = 0; i < header.length; i++) {
2697 var delimitPos = header[i].indexOf(':');
2698 if (delimitPos != -1) {
2699 headerObj[header[i].substring(0, delimitPos)] = header[i].substring(delimitPos + 2);
2707 obj.status = o.conn.status;
2708 obj.statusText = o.conn.statusText;
2709 obj.getResponseHeader = headerObj;
2710 obj.getAllResponseHeaders = headerStr;
2711 obj.responseText = o.conn.responseText;
2712 obj.responseXML = o.conn.responseXML;
2714 if (typeof callbackArg !== undefined) {
2715 obj.argument = callbackArg;
2721 createExceptionObject:function(tId, callbackArg, isAbort)
2724 var COMM_ERROR = 'communication failure';
2725 var ABORT_CODE = -1;
2726 var ABORT_ERROR = 'transaction aborted';
2732 obj.status = ABORT_CODE;
2733 obj.statusText = ABORT_ERROR;
2736 obj.status = COMM_CODE;
2737 obj.statusText = COMM_ERROR;
2741 obj.argument = callbackArg;
2747 initHeader:function(label, value, isDefault)
2749 var headerObj = (isDefault) ? this.defaultHeaders : this.headers;
2751 if (headerObj[label] === undefined) {
2752 headerObj[label] = value;
2757 headerObj[label] = value + "," + headerObj[label];
2761 this.hasDefaultHeaders = true;
2764 this.hasHeaders = true;
2769 setHeader:function(o)
2771 if (this.hasDefaultHeaders) {
2772 for (var prop in this.defaultHeaders) {
2773 if (this.defaultHeaders.hasOwnProperty(prop)) {
2774 o.conn.setRequestHeader(prop, this.defaultHeaders[prop]);
2779 if (this.hasHeaders) {
2780 for (var prop in this.headers) {
2781 if (this.headers.hasOwnProperty(prop)) {
2782 o.conn.setRequestHeader(prop, this.headers[prop]);
2786 this.hasHeaders = false;
2790 resetDefaultHeaders:function() {
2791 delete this.defaultHeaders;
2792 this.defaultHeaders = {};
2793 this.hasDefaultHeaders = false;
2796 abort:function(o, callback, isTimeout)
2798 if(this.isCallInProgress(o)) {
2800 window.clearInterval(this.poll[o.tId]);
2801 delete this.poll[o.tId];
2803 delete this.timeout[o.tId];
2806 this.handleTransactionResponse(o, callback, true);
2816 isCallInProgress:function(o)
2819 return o.conn.readyState != 4 && o.conn.readyState != 0;
2828 releaseObject:function(o)
2837 'MSXML2.XMLHTTP.3.0',
2845 * Portions of this file are based on pieces of Yahoo User Interface Library
2846 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2847 * YUI licensed under the BSD License:
2848 * http://developer.yahoo.net/yui/license.txt
2849 * <script type="text/javascript">
2853 Roo.lib.Region = function(t, r, b, l) {
2863 Roo.lib.Region.prototype = {
2864 contains : function(region) {
2865 return ( region.left >= this.left &&
2866 region.right <= this.right &&
2867 region.top >= this.top &&
2868 region.bottom <= this.bottom );
2872 getArea : function() {
2873 return ( (this.bottom - this.top) * (this.right - this.left) );
2876 intersect : function(region) {
2877 var t = Math.max(this.top, region.top);
2878 var r = Math.min(this.right, region.right);
2879 var b = Math.min(this.bottom, region.bottom);
2880 var l = Math.max(this.left, region.left);
2882 if (b >= t && r >= l) {
2883 return new Roo.lib.Region(t, r, b, l);
2888 union : function(region) {
2889 var t = Math.min(this.top, region.top);
2890 var r = Math.max(this.right, region.right);
2891 var b = Math.max(this.bottom, region.bottom);
2892 var l = Math.min(this.left, region.left);
2894 return new Roo.lib.Region(t, r, b, l);
2897 adjust : function(t, l, b, r) {
2906 Roo.lib.Region.getRegion = function(el) {
2907 var p = Roo.lib.Dom.getXY(el);
2910 var r = p[0] + el.offsetWidth;
2911 var b = p[1] + el.offsetHeight;
2914 return new Roo.lib.Region(t, r, b, l);
2917 * Portions of this file are based on pieces of Yahoo User Interface Library
2918 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2919 * YUI licensed under the BSD License:
2920 * http://developer.yahoo.net/yui/license.txt
2921 * <script type="text/javascript">
2924 //@@dep Roo.lib.Region
2927 Roo.lib.Point = function(x, y) {
2928 if (x instanceof Array) {
2932 this.x = this.right = this.left = this[0] = x;
2933 this.y = this.top = this.bottom = this[1] = y;
2936 Roo.lib.Point.prototype = new Roo.lib.Region();
2938 * Portions of this file are based on pieces of Yahoo User Interface Library
2939 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2940 * YUI licensed under the BSD License:
2941 * http://developer.yahoo.net/yui/license.txt
2942 * <script type="text/javascript">
2949 scroll : function(el, args, duration, easing, cb, scope) {
2950 this.run(el, args, duration, easing, cb, scope, Roo.lib.Scroll);
2953 motion : function(el, args, duration, easing, cb, scope) {
2954 this.run(el, args, duration, easing, cb, scope, Roo.lib.Motion);
2957 color : function(el, args, duration, easing, cb, scope) {
2958 this.run(el, args, duration, easing, cb, scope, Roo.lib.ColorAnim);
2961 run : function(el, args, duration, easing, cb, scope, type) {
2962 type = type || Roo.lib.AnimBase;
2963 if (typeof easing == "string") {
2964 easing = Roo.lib.Easing[easing];
2966 var anim = new type(el, args, duration, easing);
2967 anim.animateX(function() {
2968 Roo.callback(cb, scope);
2974 * Portions of this file are based on pieces of Yahoo User Interface Library
2975 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2976 * YUI licensed under the BSD License:
2977 * http://developer.yahoo.net/yui/license.txt
2978 * <script type="text/javascript">
2986 if (!libFlyweight) {
2987 libFlyweight = new Roo.Element.Flyweight();
2989 libFlyweight.dom = el;
2990 return libFlyweight;
2993 // since this uses fly! - it cant be in DOM (which does not have fly yet..)
2997 Roo.lib.AnimBase = function(el, attributes, duration, method) {
2999 this.init(el, attributes, duration, method);
3003 Roo.lib.AnimBase.fly = fly;
3007 Roo.lib.AnimBase.prototype = {
3009 toString: function() {
3010 var el = this.getEl();
3011 var id = el.id || el.tagName;
3012 return ("Anim " + id);
3016 noNegatives: /width|height|opacity|padding/i,
3017 offsetAttribute: /^((width|height)|(top|left))$/,
3018 defaultUnit: /width|height|top$|bottom$|left$|right$/i,
3019 offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i
3023 doMethod: function(attr, start, end) {
3024 return this.method(this.currentFrame, start, end - start, this.totalFrames);
3028 setAttribute: function(attr, val, unit) {
3029 if (this.patterns.noNegatives.test(attr)) {
3030 val = (val > 0) ? val : 0;
3033 Roo.fly(this.getEl(), '_anim').setStyle(attr, val + unit);
3037 getAttribute: function(attr) {
3038 var el = this.getEl();
3039 var val = fly(el).getStyle(attr);
3041 if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) {
3042 return parseFloat(val);
3045 var a = this.patterns.offsetAttribute.exec(attr) || [];
3046 var pos = !!( a[3] );
3047 var box = !!( a[2] );
3050 if (box || (fly(el).getStyle('position') == 'absolute' && pos)) {
3051 val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)];
3060 getDefaultUnit: function(attr) {
3061 if (this.patterns.defaultUnit.test(attr)) {
3068 animateX : function(callback, scope) {
3069 var f = function() {
3070 this.onComplete.removeListener(f);
3071 if (typeof callback == "function") {
3072 callback.call(scope || this, this);
3075 this.onComplete.addListener(f, this);
3080 setRuntimeAttribute: function(attr) {
3083 var attributes = this.attributes;
3085 this.runtimeAttributes[attr] = {};
3087 var isset = function(prop) {
3088 return (typeof prop !== 'undefined');
3091 if (!isset(attributes[attr]['to']) && !isset(attributes[attr]['by'])) {
3095 start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr);
3098 if (isset(attributes[attr]['to'])) {
3099 end = attributes[attr]['to'];
3100 } else if (isset(attributes[attr]['by'])) {
3101 if (start.constructor == Array) {
3103 for (var i = 0, len = start.length; i < len; ++i) {
3104 end[i] = start[i] + attributes[attr]['by'][i];
3107 end = start + attributes[attr]['by'];
3111 this.runtimeAttributes[attr].start = start;
3112 this.runtimeAttributes[attr].end = end;
3115 this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr);
3119 init: function(el, attributes, duration, method) {
3121 var isAnimated = false;
3124 var startTime = null;
3127 var actualFrames = 0;
3130 el = Roo.getDom(el);
3133 this.attributes = attributes || {};
3136 this.duration = duration || 1;
3139 this.method = method || Roo.lib.Easing.easeNone;
3142 this.useSeconds = true;
3145 this.currentFrame = 0;
3148 this.totalFrames = Roo.lib.AnimMgr.fps;
3151 this.getEl = function() {
3156 this.isAnimated = function() {
3161 this.getStartTime = function() {
3165 this.runtimeAttributes = {};
3168 this.animate = function() {
3169 if (this.isAnimated()) {
3173 this.currentFrame = 0;
3175 this.totalFrames = ( this.useSeconds ) ? Math.ceil(Roo.lib.AnimMgr.fps * this.duration) : this.duration;
3177 Roo.lib.AnimMgr.registerElement(this);
3181 this.stop = function(finish) {
3183 this.currentFrame = this.totalFrames;
3184 this._onTween.fire();
3186 Roo.lib.AnimMgr.stop(this);
3189 var onStart = function() {
3190 this.onStart.fire();
3192 this.runtimeAttributes = {};
3193 for (var attr in this.attributes) {
3194 this.setRuntimeAttribute(attr);
3199 startTime = new Date();
3203 var onTween = function() {
3205 duration: new Date() - this.getStartTime(),
3206 currentFrame: this.currentFrame
3209 data.toString = function() {
3211 'duration: ' + data.duration +
3212 ', currentFrame: ' + data.currentFrame
3216 this.onTween.fire(data);
3218 var runtimeAttributes = this.runtimeAttributes;
3220 for (var attr in runtimeAttributes) {
3221 this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit);
3227 var onComplete = function() {
3228 var actual_duration = (new Date() - startTime) / 1000 ;
3231 duration: actual_duration,
3232 frames: actualFrames,
3233 fps: actualFrames / actual_duration
3236 data.toString = function() {
3238 'duration: ' + data.duration +
3239 ', frames: ' + data.frames +
3240 ', fps: ' + data.fps
3246 this.onComplete.fire(data);
3250 this._onStart = new Roo.util.Event(this);
3251 this.onStart = new Roo.util.Event(this);
3252 this.onTween = new Roo.util.Event(this);
3253 this._onTween = new Roo.util.Event(this);
3254 this.onComplete = new Roo.util.Event(this);
3255 this._onComplete = new Roo.util.Event(this);
3256 this._onStart.addListener(onStart);
3257 this._onTween.addListener(onTween);
3258 this._onComplete.addListener(onComplete);
3263 * Portions of this file are based on pieces of Yahoo User Interface Library
3264 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3265 * YUI licensed under the BSD License:
3266 * http://developer.yahoo.net/yui/license.txt
3267 * <script type="text/javascript">
3271 Roo.lib.AnimMgr = new function() {
3288 this.registerElement = function(tween) {
3289 queue[queue.length] = tween;
3291 tween._onStart.fire();
3296 this.unRegister = function(tween, index) {
3297 tween._onComplete.fire();
3298 index = index || getIndex(tween);
3300 queue.splice(index, 1);
3304 if (tweenCount <= 0) {
3310 this.start = function() {
3311 if (thread === null) {
3312 thread = setInterval(this.run, this.delay);
3317 this.stop = function(tween) {
3319 clearInterval(thread);
3321 for (var i = 0, len = queue.length; i < len; ++i) {
3322 if (queue[0].isAnimated()) {
3323 this.unRegister(queue[0], 0);
3332 this.unRegister(tween);
3337 this.run = function() {
3338 for (var i = 0, len = queue.length; i < len; ++i) {
3339 var tween = queue[i];
3340 if (!tween || !tween.isAnimated()) {
3344 if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null)
3346 tween.currentFrame += 1;
3348 if (tween.useSeconds) {
3349 correctFrame(tween);
3351 tween._onTween.fire();
3354 Roo.lib.AnimMgr.stop(tween, i);
3359 var getIndex = function(anim) {
3360 for (var i = 0, len = queue.length; i < len; ++i) {
3361 if (queue[i] == anim) {
3369 var correctFrame = function(tween) {
3370 var frames = tween.totalFrames;
3371 var frame = tween.currentFrame;
3372 var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames);
3373 var elapsed = (new Date() - tween.getStartTime());
3376 if (elapsed < tween.duration * 1000) {
3377 tweak = Math.round((elapsed / expected - 1) * tween.currentFrame);
3379 tweak = frames - (frame + 1);
3381 if (tweak > 0 && isFinite(tweak)) {
3382 if (tween.currentFrame + tweak >= frames) {
3383 tweak = frames - (frame + 1);
3386 tween.currentFrame += tweak;
3390 * Portions of this file are based on pieces of Yahoo User Interface Library
3391 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3392 * YUI licensed under the BSD License:
3393 * http://developer.yahoo.net/yui/license.txt
3394 * <script type="text/javascript">
3397 Roo.lib.Bezier = new function() {
3399 this.getPosition = function(points, t) {
3400 var n = points.length;
3403 for (var i = 0; i < n; ++i) {
3404 tmp[i] = [points[i][0], points[i][1]];
3407 for (var j = 1; j < n; ++j) {
3408 for (i = 0; i < n - j; ++i) {
3409 tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
3410 tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
3414 return [ tmp[0][0], tmp[0][1] ];
3418 * Portions of this file are based on pieces of Yahoo User Interface Library
3419 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3420 * YUI licensed under the BSD License:
3421 * http://developer.yahoo.net/yui/license.txt
3422 * <script type="text/javascript">
3427 Roo.lib.ColorAnim = function(el, attributes, duration, method) {
3428 Roo.lib.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method);
3431 Roo.extend(Roo.lib.ColorAnim, Roo.lib.AnimBase);
3433 var fly = Roo.lib.AnimBase.fly;
3435 var superclass = Y.ColorAnim.superclass;
3436 var proto = Y.ColorAnim.prototype;
3438 proto.toString = function() {
3439 var el = this.getEl();
3440 var id = el.id || el.tagName;
3441 return ("ColorAnim " + id);
3444 proto.patterns.color = /color$/i;
3445 proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;
3446 proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;
3447 proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;
3448 proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/;
3451 proto.parseColor = function(s) {
3452 if (s.length == 3) {
3456 var c = this.patterns.hex.exec(s);
3457 if (c && c.length == 4) {
3458 return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ];
3461 c = this.patterns.rgb.exec(s);
3462 if (c && c.length == 4) {
3463 return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ];
3466 c = this.patterns.hex3.exec(s);
3467 if (c && c.length == 4) {
3468 return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ];
3473 // since this uses fly! - it cant be in ColorAnim (which does not have fly yet..)
3474 proto.getAttribute = function(attr) {
3475 var el = this.getEl();
3476 if (this.patterns.color.test(attr)) {
3477 var val = fly(el).getStyle(attr);
3479 if (this.patterns.transparent.test(val)) {
3480 var parent = el.parentNode;
3481 val = fly(parent).getStyle(attr);
3483 while (parent && this.patterns.transparent.test(val)) {
3484 parent = parent.parentNode;
3485 val = fly(parent).getStyle(attr);
3486 if (parent.tagName.toUpperCase() == 'HTML') {
3492 val = superclass.getAttribute.call(this, attr);
3497 proto.getAttribute = function(attr) {
3498 var el = this.getEl();
3499 if (this.patterns.color.test(attr)) {
3500 var val = fly(el).getStyle(attr);
3502 if (this.patterns.transparent.test(val)) {
3503 var parent = el.parentNode;
3504 val = fly(parent).getStyle(attr);
3506 while (parent && this.patterns.transparent.test(val)) {
3507 parent = parent.parentNode;
3508 val = fly(parent).getStyle(attr);
3509 if (parent.tagName.toUpperCase() == 'HTML') {
3515 val = superclass.getAttribute.call(this, attr);
3521 proto.doMethod = function(attr, start, end) {
3524 if (this.patterns.color.test(attr)) {
3526 for (var i = 0, len = start.length; i < len; ++i) {
3527 val[i] = superclass.doMethod.call(this, attr, start[i], end[i]);
3530 val = 'rgb(' + Math.floor(val[0]) + ',' + Math.floor(val[1]) + ',' + Math.floor(val[2]) + ')';
3533 val = superclass.doMethod.call(this, attr, start, end);
3539 proto.setRuntimeAttribute = function(attr) {
3540 superclass.setRuntimeAttribute.call(this, attr);
3542 if (this.patterns.color.test(attr)) {
3543 var attributes = this.attributes;
3544 var start = this.parseColor(this.runtimeAttributes[attr].start);
3545 var end = this.parseColor(this.runtimeAttributes[attr].end);
3547 if (typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined') {
3548 end = this.parseColor(attributes[attr].by);
3550 for (var i = 0, len = start.length; i < len; ++i) {
3551 end[i] = start[i] + end[i];
3555 this.runtimeAttributes[attr].start = start;
3556 this.runtimeAttributes[attr].end = end;
3562 * Portions of this file are based on pieces of Yahoo User Interface Library
3563 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3564 * YUI licensed under the BSD License:
3565 * http://developer.yahoo.net/yui/license.txt
3566 * <script type="text/javascript">
3572 easeNone: function (t, b, c, d) {
3573 return c * t / d + b;
3577 easeIn: function (t, b, c, d) {
3578 return c * (t /= d) * t + b;
3582 easeOut: function (t, b, c, d) {
3583 return -c * (t /= d) * (t - 2) + b;
3587 easeBoth: function (t, b, c, d) {
3588 if ((t /= d / 2) < 1) {
3589 return c / 2 * t * t + b;
3592 return -c / 2 * ((--t) * (t - 2) - 1) + b;
3596 easeInStrong: function (t, b, c, d) {
3597 return c * (t /= d) * t * t * t + b;
3601 easeOutStrong: function (t, b, c, d) {
3602 return -c * ((t = t / d - 1) * t * t * t - 1) + b;
3606 easeBothStrong: function (t, b, c, d) {
3607 if ((t /= d / 2) < 1) {
3608 return c / 2 * t * t * t * t + b;
3611 return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
3616 elasticIn: function (t, b, c, d, a, p) {
3620 if ((t /= d) == 1) {
3627 if (!a || a < Math.abs(c)) {
3632 var s = p / (2 * Math.PI) * Math.asin(c / a);
3635 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
3639 elasticOut: function (t, b, c, d, a, p) {
3643 if ((t /= d) == 1) {
3650 if (!a || a < Math.abs(c)) {
3655 var s = p / (2 * Math.PI) * Math.asin(c / a);
3658 return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
3662 elasticBoth: function (t, b, c, d, a, p) {
3667 if ((t /= d / 2) == 2) {
3675 if (!a || a < Math.abs(c)) {
3680 var s = p / (2 * Math.PI) * Math.asin(c / a);
3684 return -.5 * (a * Math.pow(2, 10 * (t -= 1)) *
3685 Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
3687 return a * Math.pow(2, -10 * (t -= 1)) *
3688 Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
3693 backIn: function (t, b, c, d, s) {
3694 if (typeof s == 'undefined') {
3697 return c * (t /= d) * t * ((s + 1) * t - s) + b;
3701 backOut: function (t, b, c, d, s) {
3702 if (typeof s == 'undefined') {
3705 return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
3709 backBoth: function (t, b, c, d, s) {
3710 if (typeof s == 'undefined') {
3714 if ((t /= d / 2 ) < 1) {
3715 return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
3717 return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
3721 bounceIn: function (t, b, c, d) {
3722 return c - Roo.lib.Easing.bounceOut(d - t, 0, c, d) + b;
3726 bounceOut: function (t, b, c, d) {
3727 if ((t /= d) < (1 / 2.75)) {
3728 return c * (7.5625 * t * t) + b;
3729 } else if (t < (2 / 2.75)) {
3730 return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
3731 } else if (t < (2.5 / 2.75)) {
3732 return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
3734 return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
3738 bounceBoth: function (t, b, c, d) {
3740 return Roo.lib.Easing.bounceIn(t * 2, 0, c, d) * .5 + b;
3742 return Roo.lib.Easing.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
3745 * Portions of this file are based on pieces of Yahoo User Interface Library
3746 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3747 * YUI licensed under the BSD License:
3748 * http://developer.yahoo.net/yui/license.txt
3749 * <script type="text/javascript">
3753 Roo.lib.Motion = function(el, attributes, duration, method) {
3755 Roo.lib.Motion.superclass.constructor.call(this, el, attributes, duration, method);
3759 Roo.extend(Roo.lib.Motion, Roo.lib.ColorAnim);
3763 var superclass = Y.Motion.superclass;
3764 var proto = Y.Motion.prototype;
3766 proto.toString = function() {
3767 var el = this.getEl();
3768 var id = el.id || el.tagName;
3769 return ("Motion " + id);
3772 proto.patterns.points = /^points$/i;
3774 proto.setAttribute = function(attr, val, unit) {
3775 if (this.patterns.points.test(attr)) {
3776 unit = unit || 'px';
3777 superclass.setAttribute.call(this, 'left', val[0], unit);
3778 superclass.setAttribute.call(this, 'top', val[1], unit);
3780 superclass.setAttribute.call(this, attr, val, unit);
3784 proto.getAttribute = function(attr) {
3785 if (this.patterns.points.test(attr)) {
3787 superclass.getAttribute.call(this, 'left'),
3788 superclass.getAttribute.call(this, 'top')
3791 val = superclass.getAttribute.call(this, attr);
3797 proto.doMethod = function(attr, start, end) {
3800 if (this.patterns.points.test(attr)) {
3801 var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100;
3802 val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t);
3804 val = superclass.doMethod.call(this, attr, start, end);
3809 proto.setRuntimeAttribute = function(attr) {
3810 if (this.patterns.points.test(attr)) {
3811 var el = this.getEl();
3812 var attributes = this.attributes;
3814 var control = attributes['points']['control'] || [];
3818 if (control.length > 0 && !(control[0] instanceof Array)) {
3819 control = [control];
3822 for (i = 0,len = control.length; i < len; ++i) {
3823 tmp[i] = control[i];
3828 Roo.fly(el).position();
3830 if (isset(attributes['points']['from'])) {
3831 Roo.lib.Dom.setXY(el, attributes['points']['from']);
3834 Roo.lib.Dom.setXY(el, Roo.lib.Dom.getXY(el));
3837 start = this.getAttribute('points');
3840 if (isset(attributes['points']['to'])) {
3841 end = translateValues.call(this, attributes['points']['to'], start);
3843 var pageXY = Roo.lib.Dom.getXY(this.getEl());
3844 for (i = 0,len = control.length; i < len; ++i) {
3845 control[i] = translateValues.call(this, control[i], start);
3849 } else if (isset(attributes['points']['by'])) {
3850 end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ];
3852 for (i = 0,len = control.length; i < len; ++i) {
3853 control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ];
3857 this.runtimeAttributes[attr] = [start];
3859 if (control.length > 0) {
3860 this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control);
3863 this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end;
3866 superclass.setRuntimeAttribute.call(this, attr);
3870 var translateValues = function(val, start) {
3871 var pageXY = Roo.lib.Dom.getXY(this.getEl());
3872 val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ];
3877 var isset = function(prop) {
3878 return (typeof prop !== 'undefined');
3882 * Portions of this file are based on pieces of Yahoo User Interface Library
3883 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3884 * YUI licensed under the BSD License:
3885 * http://developer.yahoo.net/yui/license.txt
3886 * <script type="text/javascript">
3890 Roo.lib.Scroll = function(el, attributes, duration, method) {
3892 Roo.lib.Scroll.superclass.constructor.call(this, el, attributes, duration, method);
3896 Roo.extend(Roo.lib.Scroll, Roo.lib.ColorAnim);
3900 var superclass = Y.Scroll.superclass;
3901 var proto = Y.Scroll.prototype;
3903 proto.toString = function() {
3904 var el = this.getEl();
3905 var id = el.id || el.tagName;
3906 return ("Scroll " + id);
3909 proto.doMethod = function(attr, start, end) {
3912 if (attr == 'scroll') {
3914 this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames),
3915 this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames)
3919 val = superclass.doMethod.call(this, attr, start, end);
3924 proto.getAttribute = function(attr) {
3926 var el = this.getEl();
3928 if (attr == 'scroll') {
3929 val = [ el.scrollLeft, el.scrollTop ];
3931 val = superclass.getAttribute.call(this, attr);
3937 proto.setAttribute = function(attr, val, unit) {
3938 var el = this.getEl();
3940 if (attr == 'scroll') {
3941 el.scrollLeft = val[0];
3942 el.scrollTop = val[1];
3944 superclass.setAttribute.call(this, attr, val, unit);
3950 * Ext JS Library 1.1.1
3951 * Copyright(c) 2006-2007, Ext JS, LLC.
3953 * Originally Released Under LGPL - original licence link has changed is not relivant.
3956 * <script type="text/javascript">
3961 * @class Roo.DomHelper
3962 * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.
3963 * For more information see <a href="http://www.jackslocum.com/yui/2006/10/06/domhelper-create-elements-using-dom-html-fragments-or-templates/">this blog post with examples</a>.
3966 Roo.DomHelper = function(){
3967 var tempTableEl = null;
3968 var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
3969 var tableRe = /^table|tbody|tr|td$/i;
3971 // build as innerHTML where available
3973 var createHtml = function(o){
3974 if(typeof o == 'string'){
3983 if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") continue;
3984 if(attr == "style"){
3986 if(typeof s == "function"){
3989 if(typeof s == "string"){
3990 b += ' style="' + s + '"';
3991 }else if(typeof s == "object"){
3994 if(typeof s[key] != "function"){
3995 b += key + ":" + s[key] + ";";
4002 b += ' class="' + o["cls"] + '"';
4003 }else if(attr == "htmlFor"){
4004 b += ' for="' + o["htmlFor"] + '"';
4006 b += " " + attr + '="' + o[attr] + '"';
4010 if(emptyTags.test(o.tag)){
4014 var cn = o.children || o.cn;
4016 //http://bugs.kde.org/show_bug.cgi?id=71506
4017 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4018 for(var i = 0, len = cn.length; i < len; i++) {
4019 b += createHtml(cn[i], b);
4022 b += createHtml(cn, b);
4028 b += "</" + o.tag + ">";
4035 var createDom = function(o, parentNode){
4037 // defininition craeted..
4039 if (o.ns && o.ns != 'html') {
4041 if (o.xmlns && typeof(xmlns[o.ns]) == 'undefined') {
4042 xmlns[o.ns] = o.xmlns;
4045 if (typeof(xmlns[o.ns]) == 'undefined') {
4046 console.log("Trying to create namespace element " + o.ns + ", however no xmlns was sent to builder previously");
4052 if (typeof(o) == 'string') {
4053 return parentNode.appendChild(document.createTextNode(o));
4055 o.tag = o.tag || div;
4056 if (o.ns && Roo.isIE) {
4058 o.tag = o.ns + ':' + o.tag;
4061 var el = ns ? document.createElementNS( ns, o.tag||'div') : document.createElement(o.tag||'div');
4062 var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
4065 if(attr == "tag" || attr == "ns" ||attr == "xmlns" ||attr == "children" || attr == "cn" || attr == "html" ||
4066 attr == "style" || typeof o[attr] == "function") continue;
4068 if(attr=="cls" && Roo.isIE){
4069 el.className = o["cls"];
4071 if(useSet) el.setAttribute(attr=="cls" ? 'class' : attr, o[attr]);
4072 else el[attr] = o[attr];
4075 Roo.DomHelper.applyStyles(el, o.style);
4076 var cn = o.children || o.cn;
4078 //http://bugs.kde.org/show_bug.cgi?id=71506
4079 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4080 for(var i = 0, len = cn.length; i < len; i++) {
4081 createDom(cn[i], el);
4088 el.innerHTML = o.html;
4091 parentNode.appendChild(el);
4096 var ieTable = function(depth, s, h, e){
4097 tempTableEl.innerHTML = [s, h, e].join('');
4098 var i = -1, el = tempTableEl;
4105 // kill repeat to save bytes
4109 tbe = '</tbody>'+te,
4115 * Nasty code for IE's broken table implementation
4117 var insertIntoTable = function(tag, where, el, html){
4119 tempTableEl = document.createElement('div');
4124 if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
4127 if(where == 'beforebegin'){
4131 before = el.nextSibling;
4134 node = ieTable(4, trs, html, tre);
4136 else if(tag == 'tr'){
4137 if(where == 'beforebegin'){
4140 node = ieTable(3, tbs, html, tbe);
4141 } else if(where == 'afterend'){
4142 before = el.nextSibling;
4144 node = ieTable(3, tbs, html, tbe);
4145 } else{ // INTO a TR
4146 if(where == 'afterbegin'){
4147 before = el.firstChild;
4149 node = ieTable(4, trs, html, tre);
4151 } else if(tag == 'tbody'){
4152 if(where == 'beforebegin'){
4155 node = ieTable(2, ts, html, te);
4156 } else if(where == 'afterend'){
4157 before = el.nextSibling;
4159 node = ieTable(2, ts, html, te);
4161 if(where == 'afterbegin'){
4162 before = el.firstChild;
4164 node = ieTable(3, tbs, html, tbe);
4167 if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
4170 if(where == 'afterbegin'){
4171 before = el.firstChild;
4173 node = ieTable(2, ts, html, te);
4175 el.insertBefore(node, before);
4180 /** True to force the use of DOM instead of html fragments @type Boolean */
4184 * Returns the markup for the passed Element(s) config
4185 * @param {Object} o The Dom object spec (and children)
4188 markup : function(o){
4189 return createHtml(o);
4193 * Applies a style specification to an element
4194 * @param {String/HTMLElement} el The element to apply styles to
4195 * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
4196 * a function which returns such a specification.
4198 applyStyles : function(el, styles){
4201 if(typeof styles == "string"){
4202 var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
4204 while ((matches = re.exec(styles)) != null){
4205 el.setStyle(matches[1], matches[2]);
4207 }else if (typeof styles == "object"){
4208 for (var style in styles){
4209 el.setStyle(style, styles[style]);
4211 }else if (typeof styles == "function"){
4212 Roo.DomHelper.applyStyles(el, styles.call());
4218 * Inserts an HTML fragment into the Dom
4219 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
4220 * @param {HTMLElement} el The context element
4221 * @param {String} html The HTML fragmenet
4222 * @return {HTMLElement} The new node
4224 insertHtml : function(where, el, html){
4225 where = where.toLowerCase();
4226 if(el.insertAdjacentHTML){
4227 if(tableRe.test(el.tagName)){
4229 if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
4235 el.insertAdjacentHTML('BeforeBegin', html);
4236 return el.previousSibling;
4238 el.insertAdjacentHTML('AfterBegin', html);
4239 return el.firstChild;
4241 el.insertAdjacentHTML('BeforeEnd', html);
4242 return el.lastChild;
4244 el.insertAdjacentHTML('AfterEnd', html);
4245 return el.nextSibling;
4247 throw 'Illegal insertion point -> "' + where + '"';
4249 var range = el.ownerDocument.createRange();
4253 range.setStartBefore(el);
4254 frag = range.createContextualFragment(html);
4255 el.parentNode.insertBefore(frag, el);
4256 return el.previousSibling;
4259 range.setStartBefore(el.firstChild);
4260 frag = range.createContextualFragment(html);
4261 el.insertBefore(frag, el.firstChild);
4262 return el.firstChild;
4264 el.innerHTML = html;
4265 return el.firstChild;
4269 range.setStartAfter(el.lastChild);
4270 frag = range.createContextualFragment(html);
4271 el.appendChild(frag);
4272 return el.lastChild;
4274 el.innerHTML = html;
4275 return el.lastChild;
4278 range.setStartAfter(el);
4279 frag = range.createContextualFragment(html);
4280 el.parentNode.insertBefore(frag, el.nextSibling);
4281 return el.nextSibling;
4283 throw 'Illegal insertion point -> "' + where + '"';
4287 * Creates new Dom element(s) and inserts them before el
4288 * @param {String/HTMLElement/Element} el The context element
4289 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4290 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4291 * @return {HTMLElement/Roo.Element} The new node
4293 insertBefore : function(el, o, returnElement){
4294 return this.doInsert(el, o, returnElement, "beforeBegin");
4298 * Creates new Dom element(s) and inserts them after el
4299 * @param {String/HTMLElement/Element} el The context element
4300 * @param {Object} o The Dom object spec (and children)
4301 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4302 * @return {HTMLElement/Roo.Element} The new node
4304 insertAfter : function(el, o, returnElement){
4305 return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
4309 * Creates new Dom element(s) and inserts them as the first child of el
4310 * @param {String/HTMLElement/Element} el The context element
4311 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4312 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4313 * @return {HTMLElement/Roo.Element} The new node
4315 insertFirst : function(el, o, returnElement){
4316 return this.doInsert(el, o, returnElement, "afterBegin");
4320 doInsert : function(el, o, returnElement, pos, sibling){
4321 el = Roo.getDom(el);
4323 if(this.useDom || o.ns){
4324 newNode = createDom(o, null);
4325 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
4327 var html = createHtml(o);
4328 newNode = this.insertHtml(pos, el, html);
4330 return returnElement ? Roo.get(newNode, true) : newNode;
4334 * Creates new Dom element(s) and appends them to el
4335 * @param {String/HTMLElement/Element} el The context element
4336 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4337 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4338 * @return {HTMLElement/Roo.Element} The new node
4340 append : function(el, o, returnElement){
4341 el = Roo.getDom(el);
4343 if(this.useDom || o.ns){
4344 newNode = createDom(o, null);
4345 el.appendChild(newNode);
4347 var html = createHtml(o);
4348 newNode = this.insertHtml("beforeEnd", el, html);
4350 return returnElement ? Roo.get(newNode, true) : newNode;
4354 * Creates new Dom element(s) and overwrites the contents of el with them
4355 * @param {String/HTMLElement/Element} el The context element
4356 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4357 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4358 * @return {HTMLElement/Roo.Element} The new node
4360 overwrite : function(el, o, returnElement){
4361 el = Roo.getDom(el);
4364 while (el.childNodes.length) {
4365 el.removeChild(el.firstChild);
4369 el.innerHTML = createHtml(o);
4372 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
4376 * Creates a new Roo.DomHelper.Template from the Dom object spec
4377 * @param {Object} o The Dom object spec (and children)
4378 * @return {Roo.DomHelper.Template} The new template
4380 createTemplate : function(o){
4381 var html = createHtml(o);
4382 return new Roo.Template(html);
4388 * Ext JS Library 1.1.1
4389 * Copyright(c) 2006-2007, Ext JS, LLC.
4391 * Originally Released Under LGPL - original licence link has changed is not relivant.
4394 * <script type="text/javascript">
4398 * @class Roo.Template
4399 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
4400 * For a list of available format functions, see {@link Roo.util.Format}.<br />
4403 var t = new Roo.Template({
4404 html : '<div name="{id}">' +
4405 '<span class="{cls}">{name:trim} {someval:this.myformat}{value:ellipsis(10)}</span>' +
4407 myformat: function (value, allValues) {
4408 return 'XX' + value;
4411 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
4413 * For more information see this blog post with examples: <a href="http://www.jackslocum.com/yui/2006/10/06/domhelper-create-elements-using-dom-html-fragments-or-templates/">DomHelper - Create Elements using DOM, HTML fragments and Templates</a>.
4415 * @param {Object} cfg - Configuration object.
4417 Roo.Template = function(cfg){
4419 if(cfg instanceof Array){
4421 }else if(arguments.length > 1){
4422 cfg = Array.prototype.join.call(arguments, "");
4426 if (typeof(cfg) == 'object') {
4435 Roo.Template.prototype = {
4438 * @cfg {String} html The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
4442 * Returns an HTML fragment of this template with the specified values applied.
4443 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
4444 * @return {String} The HTML fragment
4446 applyTemplate : function(values){
4450 return this.compiled(values);
4452 var useF = this.disableFormats !== true;
4453 var fm = Roo.util.Format, tpl = this;
4454 var fn = function(m, name, format, args){
4456 if(format.substr(0, 5) == "this."){
4457 return tpl.call(format.substr(5), values[name], values);
4460 // quoted values are required for strings in compiled templates,
4461 // but for non compiled we need to strip them
4462 // quoted reversed for jsmin
4463 var re = /^\s*['"](.*)["']\s*$/;
4464 args = args.split(',');
4465 for(var i = 0, len = args.length; i < len; i++){
4466 args[i] = args[i].replace(re, "$1");
4468 args = [values[name]].concat(args);
4470 args = [values[name]];
4472 return fm[format].apply(fm, args);
4475 return values[name] !== undefined ? values[name] : "";
4478 return this.html.replace(this.re, fn);
4487 * Sets the HTML used as the template and optionally compiles it.
4488 * @param {String} html
4489 * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
4490 * @return {Roo.Template} this
4492 set : function(html, compile){
4494 this.compiled = null;
4502 * True to disable format functions (defaults to false)
4505 disableFormats : false,
4508 * The regular expression used to match template variables
4512 re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
4515 * Compiles the template into an internal function, eliminating the RegEx overhead.
4516 * @return {Roo.Template} this
4518 compile : function(){
4519 var fm = Roo.util.Format;
4520 var useF = this.disableFormats !== true;
4521 var sep = Roo.isGecko ? "+" : ",";
4522 var fn = function(m, name, format, args){
4524 args = args ? ',' + args : "";
4525 if(format.substr(0, 5) != "this."){
4526 format = "fm." + format + '(';
4528 format = 'this.call("'+ format.substr(5) + '", ';
4532 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
4534 return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
4537 // branched to use + in gecko and [].join() in others
4539 body = "this.compiled = function(values){ return '" +
4540 this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
4543 body = ["this.compiled = function(values){ return ['"];
4544 body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
4545 body.push("'].join('');};");
4546 body = body.join('');
4556 // private function used to call members
4557 call : function(fnName, value, allValues){
4558 return this[fnName](value, allValues);
4562 * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
4563 * @param {String/HTMLElement/Roo.Element} el The context element
4564 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
4565 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4566 * @return {HTMLElement/Roo.Element} The new node or Element
4568 insertFirst: function(el, values, returnElement){
4569 return this.doInsert('afterBegin', el, values, returnElement);
4573 * Applies the supplied values to the template and inserts the new node(s) before el.
4574 * @param {String/HTMLElement/Roo.Element} el The context element
4575 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
4576 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4577 * @return {HTMLElement/Roo.Element} The new node or Element
4579 insertBefore: function(el, values, returnElement){
4580 return this.doInsert('beforeBegin', el, values, returnElement);
4584 * Applies the supplied values to the template and inserts the new node(s) after el.
4585 * @param {String/HTMLElement/Roo.Element} el The context element
4586 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
4587 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4588 * @return {HTMLElement/Roo.Element} The new node or Element
4590 insertAfter : function(el, values, returnElement){
4591 return this.doInsert('afterEnd', el, values, returnElement);
4595 * Applies the supplied values to the template and appends the new node(s) to el.
4596 * @param {String/HTMLElement/Roo.Element} el The context element
4597 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
4598 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4599 * @return {HTMLElement/Roo.Element} The new node or Element
4601 append : function(el, values, returnElement){
4602 return this.doInsert('beforeEnd', el, values, returnElement);
4605 doInsert : function(where, el, values, returnEl){
4606 el = Roo.getDom(el);
4607 var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
4608 return returnEl ? Roo.get(newNode, true) : newNode;
4612 * Applies the supplied values to the template and overwrites the content of el with the new node(s).
4613 * @param {String/HTMLElement/Roo.Element} el The context element
4614 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
4615 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4616 * @return {HTMLElement/Roo.Element} The new node or Element
4618 overwrite : function(el, values, returnElement){
4619 el = Roo.getDom(el);
4620 el.innerHTML = this.applyTemplate(values);
4621 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
4625 * Alias for {@link #applyTemplate}
4628 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
4631 Roo.DomHelper.Template = Roo.Template;
4634 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
4635 * @param {String/HTMLElement} el A DOM element or its id
4636 * @returns {Roo.Template} The created template
4639 Roo.Template.from = function(el){
4640 el = Roo.getDom(el);
4641 return new Roo.Template(el.value || el.innerHTML);
4644 * Ext JS Library 1.1.1
4645 * Copyright(c) 2006-2007, Ext JS, LLC.
4647 * Originally Released Under LGPL - original licence link has changed is not relivant.
4650 * <script type="text/javascript">
4655 * This is code is also distributed under MIT license for use
4656 * with jQuery and prototype JavaScript libraries.
4659 * @class Roo.DomQuery
4660 Provides high performance selector/xpath processing by compiling queries into reusable functions. New pseudo classes and matchers can be plugged. It works on HTML and XML documents (if a content node is passed in).
4662 DomQuery supports most of the <a href="http://www.w3.org/TR/2005/WD-css3-selectors-20051215/">CSS3 selectors spec</a>, along with some custom selectors and basic XPath.</p>
4665 All selectors, attribute filters and pseudos below can be combined infinitely in any order. For example "div.foo:nth-child(odd)[@foo=bar].bar:first" would be a perfectly valid selector. Node filters are processed in the order in which they appear, which allows you to optimize your queries for your document structure.
4667 <h4>Element Selectors:</h4>
4669 <li> <b>*</b> any element</li>
4670 <li> <b>E</b> an element with the tag E</li>
4671 <li> <b>E F</b> All descendent elements of E that have the tag F</li>
4672 <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
4673 <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
4674 <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
4676 <h4>Attribute Selectors:</h4>
4677 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
4679 <li> <b>E[foo]</b> has an attribute "foo"</li>
4680 <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
4681 <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
4682 <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
4683 <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
4684 <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
4685 <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
4687 <h4>Pseudo Classes:</h4>
4689 <li> <b>E:first-child</b> E is the first child of its parent</li>
4690 <li> <b>E:last-child</b> E is the last child of its parent</li>
4691 <li> <b>E:nth-child(<i>n</i>)</b> E is the <i>n</i>th child of its parent (1 based as per the spec)</li>
4692 <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
4693 <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
4694 <li> <b>E:only-child</b> E is the only child of its parent</li>
4695 <li> <b>E:checked</b> E is an element that is has a checked attribute that is true (e.g. a radio or checkbox) </li>
4696 <li> <b>E:first</b> the first E in the resultset</li>
4697 <li> <b>E:last</b> the last E in the resultset</li>
4698 <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
4699 <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
4700 <li> <b>E:even</b> shortcut for :nth-child(even)</li>
4701 <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
4702 <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
4703 <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
4704 <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
4705 <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
4706 <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
4708 <h4>CSS Value Selectors:</h4>
4710 <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
4711 <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
4712 <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
4713 <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
4714 <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
4715 <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
4719 Roo.DomQuery = function(){
4720 var cache = {}, simpleCache = {}, valueCache = {};
4721 var nonSpace = /\S/;
4722 var trimRe = /^\s+|\s+$/g;
4723 var tplRe = /\{(\d+)\}/g;
4724 var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
4725 var tagTokenRe = /^(#)?([\w-\*]+)/;
4726 var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
4728 function child(p, index){
4730 var n = p.firstChild;
4732 if(n.nodeType == 1){
4743 while((n = n.nextSibling) && n.nodeType != 1);
4748 while((n = n.previousSibling) && n.nodeType != 1);
4752 function children(d){
4753 var n = d.firstChild, ni = -1;
4755 var nx = n.nextSibling;
4756 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
4766 function byClassName(c, a, v){
4770 var r = [], ri = -1, cn;
4771 for(var i = 0, ci; ci = c[i]; i++){
4772 if((' '+ci.className+' ').indexOf(v) != -1){
4779 function attrValue(n, attr){
4780 if(!n.tagName && typeof n.length != "undefined"){
4789 if(attr == "class" || attr == "className"){
4792 return n.getAttribute(attr) || n[attr];
4796 function getNodes(ns, mode, tagName){
4797 var result = [], ri = -1, cs;
4801 tagName = tagName || "*";
4802 if(typeof ns.getElementsByTagName != "undefined"){
4806 for(var i = 0, ni; ni = ns[i]; i++){
4807 cs = ni.getElementsByTagName(tagName);
4808 for(var j = 0, ci; ci = cs[j]; j++){
4812 }else if(mode == "/" || mode == ">"){
4813 var utag = tagName.toUpperCase();
4814 for(var i = 0, ni, cn; ni = ns[i]; i++){
4815 cn = ni.children || ni.childNodes;
4816 for(var j = 0, cj; cj = cn[j]; j++){
4817 if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
4822 }else if(mode == "+"){
4823 var utag = tagName.toUpperCase();
4824 for(var i = 0, n; n = ns[i]; i++){
4825 while((n = n.nextSibling) && n.nodeType != 1);
4826 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
4830 }else if(mode == "~"){
4831 for(var i = 0, n; n = ns[i]; i++){
4832 while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
4841 function concat(a, b){
4845 for(var i = 0, l = b.length; i < l; i++){
4851 function byTag(cs, tagName){
4852 if(cs.tagName || cs == document){
4858 var r = [], ri = -1;
4859 tagName = tagName.toLowerCase();
4860 for(var i = 0, ci; ci = cs[i]; i++){
4861 if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
4868 function byId(cs, attr, id){
4869 if(cs.tagName || cs == document){
4875 var r = [], ri = -1;
4876 for(var i = 0,ci; ci = cs[i]; i++){
4877 if(ci && ci.id == id){
4885 function byAttribute(cs, attr, value, op, custom){
4886 var r = [], ri = -1, st = custom=="{";
4887 var f = Roo.DomQuery.operators[op];
4888 for(var i = 0, ci; ci = cs[i]; i++){
4891 a = Roo.DomQuery.getStyle(ci, attr);
4893 else if(attr == "class" || attr == "className"){
4895 }else if(attr == "for"){
4897 }else if(attr == "href"){
4898 a = ci.getAttribute("href", 2);
4900 a = ci.getAttribute(attr);
4902 if((f && f(a, value)) || (!f && a)){
4909 function byPseudo(cs, name, value){
4910 return Roo.DomQuery.pseudos[name](cs, value);
4913 // This is for IE MSXML which does not support expandos.
4914 // IE runs the same speed using setAttribute, however FF slows way down
4915 // and Safari completely fails so they need to continue to use expandos.
4916 var isIE = window.ActiveXObject ? true : false;
4918 // this eval is stop the compressor from
4919 // renaming the variable to something shorter
4921 /** eval:var:batch */
4926 function nodupIEXml(cs){
4928 cs[0].setAttribute("_nodup", d);
4930 for(var i = 1, len = cs.length; i < len; i++){
4932 if(!c.getAttribute("_nodup") != d){
4933 c.setAttribute("_nodup", d);
4937 for(var i = 0, len = cs.length; i < len; i++){
4938 cs[i].removeAttribute("_nodup");
4947 var len = cs.length, c, i, r = cs, cj, ri = -1;
4948 if(!len || typeof cs.nodeType != "undefined" || len == 1){
4951 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
4952 return nodupIEXml(cs);
4956 for(i = 1; c = cs[i]; i++){
4961 for(var j = 0; j < i; j++){
4964 for(j = i+1; cj = cs[j]; j++){
4976 function quickDiffIEXml(c1, c2){
4978 for(var i = 0, len = c1.length; i < len; i++){
4979 c1[i].setAttribute("_qdiff", d);
4982 for(var i = 0, len = c2.length; i < len; i++){
4983 if(c2[i].getAttribute("_qdiff") != d){
4984 r[r.length] = c2[i];
4987 for(var i = 0, len = c1.length; i < len; i++){
4988 c1[i].removeAttribute("_qdiff");
4993 function quickDiff(c1, c2){
4994 var len1 = c1.length;
4998 if(isIE && c1[0].selectSingleNode){
4999 return quickDiffIEXml(c1, c2);
5002 for(var i = 0; i < len1; i++){
5006 for(var i = 0, len = c2.length; i < len; i++){
5007 if(c2[i]._qdiff != d){
5008 r[r.length] = c2[i];
5014 function quickId(ns, mode, root, id){
5016 var d = root.ownerDocument || root;
5017 return d.getElementById(id);
5019 ns = getNodes(ns, mode, "*");
5020 return byId(ns, null, id);
5024 getStyle : function(el, name){
5025 return Roo.fly(el).getStyle(name);
5028 * Compiles a selector/xpath query into a reusable function. The returned function
5029 * takes one parameter "root" (optional), which is the context node from where the query should start.
5030 * @param {String} selector The selector/xpath query
5031 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
5032 * @return {Function}
5034 compile : function(path, type){
5035 type = type || "select";
5037 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
5038 var q = path, mode, lq;
5039 var tk = Roo.DomQuery.matchers;
5040 var tklen = tk.length;
5043 // accept leading mode switch
5044 var lmode = q.match(modeRe);
5045 if(lmode && lmode[1]){
5046 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
5047 q = q.replace(lmode[1], "");
5049 // strip leading slashes
5050 while(path.substr(0, 1)=="/"){
5051 path = path.substr(1);
5054 while(q && lq != q){
5056 var tm = q.match(tagTokenRe);
5057 if(type == "select"){
5060 fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
5062 fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
5064 q = q.replace(tm[0], "");
5065 }else if(q.substr(0, 1) != '@'){
5066 fn[fn.length] = 'n = getNodes(n, mode, "*");';
5071 fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
5073 fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
5075 q = q.replace(tm[0], "");
5078 while(!(mm = q.match(modeRe))){
5079 var matched = false;
5080 for(var j = 0; j < tklen; j++){
5082 var m = q.match(t.re);
5084 fn[fn.length] = t.select.replace(tplRe, function(x, i){
5087 q = q.replace(m[0], "");
5092 // prevent infinite loop on bad selector
5094 throw 'Error parsing selector, parsing failed at "' + q + '"';
5098 fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
5099 q = q.replace(mm[1], "");
5102 fn[fn.length] = "return nodup(n);\n}";
5105 * list of variables that need from compression as they are used by eval.
5115 * eval:var:byClassName
5117 * eval:var:byAttribute
5118 * eval:var:attrValue
5126 * Selects a group of elements.
5127 * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
5128 * @param {Node} root (optional) The start of the query (defaults to document).
5131 select : function(path, root, type){
5132 if(!root || root == document){
5135 if(typeof root == "string"){
5136 root = document.getElementById(root);
5138 var paths = path.split(",");
5140 for(var i = 0, len = paths.length; i < len; i++){
5141 var p = paths[i].replace(trimRe, "");
5143 cache[p] = Roo.DomQuery.compile(p);
5145 throw p + " is not a valid selector";
5148 var result = cache[p](root);
5149 if(result && result != document){
5150 results = results.concat(result);
5153 if(paths.length > 1){
5154 return nodup(results);
5160 * Selects a single element.
5161 * @param {String} selector The selector/xpath query
5162 * @param {Node} root (optional) The start of the query (defaults to document).
5165 selectNode : function(path, root){
5166 return Roo.DomQuery.select(path, root)[0];
5170 * Selects the value of a node, optionally replacing null with the defaultValue.
5171 * @param {String} selector The selector/xpath query
5172 * @param {Node} root (optional) The start of the query (defaults to document).
5173 * @param {String} defaultValue
5175 selectValue : function(path, root, defaultValue){
5176 path = path.replace(trimRe, "");
5177 if(!valueCache[path]){
5178 valueCache[path] = Roo.DomQuery.compile(path, "select");
5180 var n = valueCache[path](root);
5181 n = n[0] ? n[0] : n;
5182 var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
5183 return ((v === null||v === undefined||v==='') ? defaultValue : v);
5187 * Selects the value of a node, parsing integers and floats.
5188 * @param {String} selector The selector/xpath query
5189 * @param {Node} root (optional) The start of the query (defaults to document).
5190 * @param {Number} defaultValue
5193 selectNumber : function(path, root, defaultValue){
5194 var v = Roo.DomQuery.selectValue(path, root, defaultValue || 0);
5195 return parseFloat(v);
5199 * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
5200 * @param {String/HTMLElement/Array} el An element id, element or array of elements
5201 * @param {String} selector The simple selector to test
5204 is : function(el, ss){
5205 if(typeof el == "string"){
5206 el = document.getElementById(el);
5208 var isArray = (el instanceof Array);
5209 var result = Roo.DomQuery.filter(isArray ? el : [el], ss);
5210 return isArray ? (result.length == el.length) : (result.length > 0);
5214 * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
5215 * @param {Array} el An array of elements to filter
5216 * @param {String} selector The simple selector to test
5217 * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
5218 * the selector instead of the ones that match
5221 filter : function(els, ss, nonMatches){
5222 ss = ss.replace(trimRe, "");
5223 if(!simpleCache[ss]){
5224 simpleCache[ss] = Roo.DomQuery.compile(ss, "simple");
5226 var result = simpleCache[ss](els);
5227 return nonMatches ? quickDiff(result, els) : result;
5231 * Collection of matching regular expressions and code snippets.
5235 select: 'n = byClassName(n, null, " {1} ");'
5237 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
5238 select: 'n = byPseudo(n, "{1}", "{2}");'
5240 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
5241 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
5244 select: 'n = byId(n, null, "{1}");'
5247 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
5252 * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
5253 * New operators can be added as long as the match the format <i>c</i>= where <i>c</i> is any character other than space, > <.
5256 "=" : function(a, v){
5259 "!=" : function(a, v){
5262 "^=" : function(a, v){
5263 return a && a.substr(0, v.length) == v;
5265 "$=" : function(a, v){
5266 return a && a.substr(a.length-v.length) == v;
5268 "*=" : function(a, v){
5269 return a && a.indexOf(v) !== -1;
5271 "%=" : function(a, v){
5272 return (a % v) == 0;
5274 "|=" : function(a, v){
5275 return a && (a == v || a.substr(0, v.length+1) == v+'-');
5277 "~=" : function(a, v){
5278 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
5283 * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
5284 * and the argument (if any) supplied in the selector.
5287 "first-child" : function(c){
5288 var r = [], ri = -1, n;
5289 for(var i = 0, ci; ci = n = c[i]; i++){
5290 while((n = n.previousSibling) && n.nodeType != 1);
5298 "last-child" : function(c){
5299 var r = [], ri = -1, n;
5300 for(var i = 0, ci; ci = n = c[i]; i++){
5301 while((n = n.nextSibling) && n.nodeType != 1);
5309 "nth-child" : function(c, a) {
5310 var r = [], ri = -1;
5311 var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
5312 var f = (m[1] || 1) - 0, l = m[2] - 0;
5313 for(var i = 0, n; n = c[i]; i++){
5314 var pn = n.parentNode;
5315 if (batch != pn._batch) {
5317 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
5318 if(cn.nodeType == 1){
5325 if (l == 0 || n.nodeIndex == l){
5328 } else if ((n.nodeIndex + l) % f == 0){
5336 "only-child" : function(c){
5337 var r = [], ri = -1;;
5338 for(var i = 0, ci; ci = c[i]; i++){
5339 if(!prev(ci) && !next(ci)){
5346 "empty" : function(c){
5347 var r = [], ri = -1;
5348 for(var i = 0, ci; ci = c[i]; i++){
5349 var cns = ci.childNodes, j = 0, cn, empty = true;
5352 if(cn.nodeType == 1 || cn.nodeType == 3){
5364 "contains" : function(c, v){
5365 var r = [], ri = -1;
5366 for(var i = 0, ci; ci = c[i]; i++){
5367 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
5374 "nodeValue" : function(c, v){
5375 var r = [], ri = -1;
5376 for(var i = 0, ci; ci = c[i]; i++){
5377 if(ci.firstChild && ci.firstChild.nodeValue == v){
5384 "checked" : function(c){
5385 var r = [], ri = -1;
5386 for(var i = 0, ci; ci = c[i]; i++){
5387 if(ci.checked == true){
5394 "not" : function(c, ss){
5395 return Roo.DomQuery.filter(c, ss, true);
5398 "odd" : function(c){
5399 return this["nth-child"](c, "odd");
5402 "even" : function(c){
5403 return this["nth-child"](c, "even");
5406 "nth" : function(c, a){
5407 return c[a-1] || [];
5410 "first" : function(c){
5414 "last" : function(c){
5415 return c[c.length-1] || [];
5418 "has" : function(c, ss){
5419 var s = Roo.DomQuery.select;
5420 var r = [], ri = -1;
5421 for(var i = 0, ci; ci = c[i]; i++){
5422 if(s(ss, ci).length > 0){
5429 "next" : function(c, ss){
5430 var is = Roo.DomQuery.is;
5431 var r = [], ri = -1;
5432 for(var i = 0, ci; ci = c[i]; i++){
5441 "prev" : function(c, ss){
5442 var is = Roo.DomQuery.is;
5443 var r = [], ri = -1;
5444 for(var i = 0, ci; ci = c[i]; i++){
5457 * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Roo.DomQuery#select}
5458 * @param {String} path The selector/xpath query
5459 * @param {Node} root (optional) The start of the query (defaults to document).
5464 Roo.query = Roo.DomQuery.select;
5467 * Ext JS Library 1.1.1
5468 * Copyright(c) 2006-2007, Ext JS, LLC.
5470 * Originally Released Under LGPL - original licence link has changed is not relivant.
5473 * <script type="text/javascript">
5477 * @class Roo.util.Observable
5478 * Base class that provides a common interface for publishing events. Subclasses are expected to
5479 * to have a property "events" with all the events defined.<br>
5482 Employee = function(name){
5489 Roo.extend(Employee, Roo.util.Observable);
5491 * @param {Object} config properties to use (incuding events / listeners)
5494 Roo.util.Observable = function(cfg){
5497 this.addEvents(cfg.events || {});
5499 delete cfg.events; // make sure
5502 Roo.apply(this, cfg);
5505 this.on(this.listeners);
5506 delete this.listeners;
5509 Roo.util.Observable.prototype = {
5511 * @cfg {Object} listeners list of events and functions to call for this object,
5515 'click' : function(e) {
5525 * Fires the specified event with the passed parameters (minus the event name).
5526 * @param {String} eventName
5527 * @param {Object...} args Variable number of parameters are passed to handlers
5528 * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
5530 fireEvent : function(){
5531 var ce = this.events[arguments[0].toLowerCase()];
5532 if(typeof ce == "object"){
5533 return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
5540 filterOptRe : /^(?:scope|delay|buffer|single)$/,
5543 * Appends an event handler to this component
5544 * @param {String} eventName The type of event to listen for
5545 * @param {Function} handler The method the event invokes
5546 * @param {Object} scope (optional) The scope in which to execute the handler
5547 * function. The handler function's "this" context.
5548 * @param {Object} options (optional) An object containing handler configuration
5549 * properties. This may contain any of the following properties:<ul>
5550 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
5551 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
5552 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
5553 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
5554 * by the specified number of milliseconds. If the event fires again within that time, the original
5555 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
5558 * <b>Combining Options</b><br>
5559 * Using the options argument, it is possible to combine different types of listeners:<br>
5561 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
5563 el.on('click', this.onClick, this, {
5570 * <b>Attaching multiple handlers in 1 call</b><br>
5571 * The method also allows for a single argument to be passed which is a config object containing properties
5572 * which specify multiple handlers.
5581 fn: this.onMouseOver,
5585 fn: this.onMouseOut,
5591 * Or a shorthand syntax which passes the same scope object to all handlers:
5594 'click': this.onClick,
5595 'mouseover': this.onMouseOver,
5596 'mouseout': this.onMouseOut,
5601 addListener : function(eventName, fn, scope, o){
5602 if(typeof eventName == "object"){
5605 if(this.filterOptRe.test(e)){
5608 if(typeof o[e] == "function"){
5610 this.addListener(e, o[e], o.scope, o);
5612 // individual options
5613 this.addListener(e, o[e].fn, o[e].scope, o[e]);
5618 o = (!o || typeof o == "boolean") ? {} : o;
5619 eventName = eventName.toLowerCase();
5620 var ce = this.events[eventName] || true;
5621 if(typeof ce == "boolean"){
5622 ce = new Roo.util.Event(this, eventName);
5623 this.events[eventName] = ce;
5625 ce.addListener(fn, scope, o);
5629 * Removes a listener
5630 * @param {String} eventName The type of event to listen for
5631 * @param {Function} handler The handler to remove
5632 * @param {Object} scope (optional) The scope (this object) for the handler
5634 removeListener : function(eventName, fn, scope){
5635 var ce = this.events[eventName.toLowerCase()];
5636 if(typeof ce == "object"){
5637 ce.removeListener(fn, scope);
5642 * Removes all listeners for this object
5644 purgeListeners : function(){
5645 for(var evt in this.events){
5646 if(typeof this.events[evt] == "object"){
5647 this.events[evt].clearListeners();
5652 relayEvents : function(o, events){
5653 var createHandler = function(ename){
5655 return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
5658 for(var i = 0, len = events.length; i < len; i++){
5659 var ename = events[i];
5660 if(!this.events[ename]){ this.events[ename] = true; };
5661 o.on(ename, createHandler(ename), this);
5666 * Used to define events on this Observable
5667 * @param {Object} object The object with the events defined
5669 addEvents : function(o){
5673 Roo.applyIf(this.events, o);
5677 * Checks to see if this object has any listeners for a specified event
5678 * @param {String} eventName The name of the event to check for
5679 * @return {Boolean} True if the event is being listened for, else false
5681 hasListener : function(eventName){
5682 var e = this.events[eventName];
5683 return typeof e == "object" && e.listeners.length > 0;
5687 * Appends an event handler to this element (shorthand for addListener)
5688 * @param {String} eventName The type of event to listen for
5689 * @param {Function} handler The method the event invokes
5690 * @param {Object} scope (optional) The scope in which to execute the handler
5691 * function. The handler function's "this" context.
5692 * @param {Object} options (optional)
5695 Roo.util.Observable.prototype.on = Roo.util.Observable.prototype.addListener;
5697 * Removes a listener (shorthand for removeListener)
5698 * @param {String} eventName The type of event to listen for
5699 * @param {Function} handler The handler to remove
5700 * @param {Object} scope (optional) The scope (this object) for the handler
5703 Roo.util.Observable.prototype.un = Roo.util.Observable.prototype.removeListener;
5706 * Starts capture on the specified Observable. All events will be passed
5707 * to the supplied function with the event name + standard signature of the event
5708 * <b>before</b> the event is fired. If the supplied function returns false,
5709 * the event will not fire.
5710 * @param {Observable} o The Observable to capture
5711 * @param {Function} fn The function to call
5712 * @param {Object} scope (optional) The scope (this object) for the fn
5715 Roo.util.Observable.capture = function(o, fn, scope){
5716 o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
5720 * Removes <b>all</b> added captures from the Observable.
5721 * @param {Observable} o The Observable to release
5724 Roo.util.Observable.releaseCapture = function(o){
5725 o.fireEvent = Roo.util.Observable.prototype.fireEvent;
5730 var createBuffered = function(h, o, scope){
5731 var task = new Roo.util.DelayedTask();
5733 task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
5737 var createSingle = function(h, e, fn, scope){
5739 e.removeListener(fn, scope);
5740 return h.apply(scope, arguments);
5744 var createDelayed = function(h, o, scope){
5746 var args = Array.prototype.slice.call(arguments, 0);
5747 setTimeout(function(){
5748 h.apply(scope, args);
5753 Roo.util.Event = function(obj, name){
5756 this.listeners = [];
5759 Roo.util.Event.prototype = {
5760 addListener : function(fn, scope, options){
5761 var o = options || {};
5762 scope = scope || this.obj;
5763 if(!this.isListening(fn, scope)){
5764 var l = {fn: fn, scope: scope, options: o};
5767 h = createDelayed(h, o, scope);
5770 h = createSingle(h, this, fn, scope);
5773 h = createBuffered(h, o, scope);
5776 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
5777 this.listeners.push(l);
5779 this.listeners = this.listeners.slice(0);
5780 this.listeners.push(l);
5785 findListener : function(fn, scope){
5786 scope = scope || this.obj;
5787 var ls = this.listeners;
5788 for(var i = 0, len = ls.length; i < len; i++){
5790 if(l.fn == fn && l.scope == scope){
5797 isListening : function(fn, scope){
5798 return this.findListener(fn, scope) != -1;
5801 removeListener : function(fn, scope){
5803 if((index = this.findListener(fn, scope)) != -1){
5805 this.listeners.splice(index, 1);
5807 this.listeners = this.listeners.slice(0);
5808 this.listeners.splice(index, 1);
5815 clearListeners : function(){
5816 this.listeners = [];
5820 var ls = this.listeners, scope, len = ls.length;
5823 var args = Array.prototype.slice.call(arguments, 0);
5824 for(var i = 0; i < len; i++){
5826 if(l.fireFn.apply(l.scope||this.obj||window, arguments) === false){
5827 this.firing = false;
5831 this.firing = false;
5838 * Ext JS Library 1.1.1
5839 * Copyright(c) 2006-2007, Ext JS, LLC.
5841 * Originally Released Under LGPL - original licence link has changed is not relivant.
5844 * <script type="text/javascript">
5848 * @class Roo.EventManager
5849 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
5850 * several useful events directly.
5851 * See {@link Roo.EventObject} for more details on normalized event objects.
5854 Roo.EventManager = function(){
5855 var docReadyEvent, docReadyProcId, docReadyState = false;
5856 var resizeEvent, resizeTask, textEvent, textSize;
5857 var E = Roo.lib.Event;
5858 var D = Roo.lib.Dom;
5861 var fireDocReady = function(){
5863 docReadyState = true;
5866 clearInterval(docReadyProcId);
5868 if(Roo.isGecko || Roo.isOpera) {
5869 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
5872 var defer = document.getElementById("ie-deferred-loader");
5874 defer.onreadystatechange = null;
5875 defer.parentNode.removeChild(defer);
5879 docReadyEvent.fire();
5880 docReadyEvent.clearListeners();
5885 var initDocReady = function(){
5886 docReadyEvent = new Roo.util.Event();
5887 if(Roo.isGecko || Roo.isOpera) {
5888 document.addEventListener("DOMContentLoaded", fireDocReady, false);
5890 document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
5891 var defer = document.getElementById("ie-deferred-loader");
5892 defer.onreadystatechange = function(){
5893 if(this.readyState == "complete"){
5897 }else if(Roo.isSafari){
5898 docReadyProcId = setInterval(function(){
5899 var rs = document.readyState;
5900 if(rs == "complete") {
5905 // no matter what, make sure it fires on load
5906 E.on(window, "load", fireDocReady);
5909 var createBuffered = function(h, o){
5910 var task = new Roo.util.DelayedTask(h);
5912 // create new event object impl so new events don't wipe out properties
5913 e = new Roo.EventObjectImpl(e);
5914 task.delay(o.buffer, h, null, [e]);
5918 var createSingle = function(h, el, ename, fn){
5920 Roo.EventManager.removeListener(el, ename, fn);
5925 var createDelayed = function(h, o){
5927 // create new event object impl so new events don't wipe out properties
5928 e = new Roo.EventObjectImpl(e);
5929 setTimeout(function(){
5935 var listen = function(element, ename, opt, fn, scope){
5936 var o = (!opt || typeof opt == "boolean") ? {} : opt;
5937 fn = fn || o.fn; scope = scope || o.scope;
5938 var el = Roo.getDom(element);
5940 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
5942 var h = function(e){
5943 e = Roo.EventObject.setEvent(e);
5946 t = e.getTarget(o.delegate, el);
5953 if(o.stopEvent === true){
5956 if(o.preventDefault === true){
5959 if(o.stopPropagation === true){
5960 e.stopPropagation();
5963 if(o.normalized === false){
5967 fn.call(scope || el, e, t, o);
5970 h = createDelayed(h, o);
5973 h = createSingle(h, el, ename, fn);
5976 h = createBuffered(h, o);
5978 fn._handlers = fn._handlers || [];
5979 fn._handlers.push([Roo.id(el), ename, h]);
5982 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
5983 el.addEventListener("DOMMouseScroll", h, false);
5984 E.on(window, 'unload', function(){
5985 el.removeEventListener("DOMMouseScroll", h, false);
5988 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
5989 Roo.EventManager.stoppedMouseDownEvent.addListener(h);
5994 var stopListening = function(el, ename, fn){
5995 var id = Roo.id(el), hds = fn._handlers, hd = fn;
5997 for(var i = 0, len = hds.length; i < len; i++){
5999 if(h[0] == id && h[1] == ename){
6006 E.un(el, ename, hd);
6007 el = Roo.getDom(el);
6008 if(ename == "mousewheel" && el.addEventListener){
6009 el.removeEventListener("DOMMouseScroll", hd, false);
6011 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
6012 Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
6016 var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
6023 * @scope Roo.EventManager
6028 * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
6029 * object with a Roo.EventObject
6030 * @param {Function} fn The method the event invokes
6031 * @param {Object} scope An object that becomes the scope of the handler
6032 * @param {boolean} override If true, the obj passed in becomes
6033 * the execution scope of the listener
6034 * @return {Function} The wrapped function
6037 wrap : function(fn, scope, override){
6039 Roo.EventObject.setEvent(e);
6040 fn.call(override ? scope || window : window, Roo.EventObject, scope);
6045 * Appends an event handler to an element (shorthand for addListener)
6046 * @param {String/HTMLElement} element The html element or id to assign the
6047 * @param {String} eventName The type of event to listen for
6048 * @param {Function} handler The method the event invokes
6049 * @param {Object} scope (optional) The scope in which to execute the handler
6050 * function. The handler function's "this" context.
6051 * @param {Object} options (optional) An object containing handler configuration
6052 * properties. This may contain any of the following properties:<ul>
6053 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6054 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
6055 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
6056 * <li>preventDefault {Boolean} True to prevent the default action</li>
6057 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
6058 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
6059 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6060 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6061 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6062 * by the specified number of milliseconds. If the event fires again within that time, the original
6063 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6066 * <b>Combining Options</b><br>
6067 * Using the options argument, it is possible to combine different types of listeners:<br>
6069 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
6071 el.on('click', this.onClick, this, {
6078 * <b>Attaching multiple handlers in 1 call</b><br>
6079 * The method also allows for a single argument to be passed which is a config object containing properties
6080 * which specify multiple handlers.
6090 fn: this.onMouseOver
6099 * Or a shorthand syntax:<br>
6102 'click' : this.onClick,
6103 'mouseover' : this.onMouseOver,
6104 'mouseout' : this.onMouseOut
6108 addListener : function(element, eventName, fn, scope, options){
6109 if(typeof eventName == "object"){
6115 if(typeof o[e] == "function"){
6117 listen(element, e, o, o[e], o.scope);
6119 // individual options
6120 listen(element, e, o[e]);
6125 return listen(element, eventName, options, fn, scope);
6129 * Removes an event handler
6131 * @param {String/HTMLElement} element The id or html element to remove the
6133 * @param {String} eventName The type of event
6134 * @param {Function} fn
6135 * @return {Boolean} True if a listener was actually removed
6137 removeListener : function(element, eventName, fn){
6138 return stopListening(element, eventName, fn);
6142 * Fires when the document is ready (before onload and before images are loaded). Can be
6143 * accessed shorthanded Roo.onReady().
6144 * @param {Function} fn The method the event invokes
6145 * @param {Object} scope An object that becomes the scope of the handler
6146 * @param {boolean} options
6148 onDocumentReady : function(fn, scope, options){
6149 if(docReadyState){ // if it already fired
6150 docReadyEvent.addListener(fn, scope, options);
6151 docReadyEvent.fire();
6152 docReadyEvent.clearListeners();
6158 docReadyEvent.addListener(fn, scope, options);
6162 * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
6163 * @param {Function} fn The method the event invokes
6164 * @param {Object} scope An object that becomes the scope of the handler
6165 * @param {boolean} options
6167 onWindowResize : function(fn, scope, options){
6169 resizeEvent = new Roo.util.Event();
6170 resizeTask = new Roo.util.DelayedTask(function(){
6171 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6173 E.on(window, "resize", function(){
6175 resizeTask.delay(50);
6177 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6181 resizeEvent.addListener(fn, scope, options);
6185 * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
6186 * @param {Function} fn The method the event invokes
6187 * @param {Object} scope An object that becomes the scope of the handler
6188 * @param {boolean} options
6190 onTextResize : function(fn, scope, options){
6192 textEvent = new Roo.util.Event();
6193 var textEl = new Roo.Element(document.createElement('div'));
6194 textEl.dom.className = 'x-text-resize';
6195 textEl.dom.innerHTML = 'X';
6196 textEl.appendTo(document.body);
6197 textSize = textEl.dom.offsetHeight;
6198 setInterval(function(){
6199 if(textEl.dom.offsetHeight != textSize){
6200 textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
6202 }, this.textResizeInterval);
6204 textEvent.addListener(fn, scope, options);
6208 * Removes the passed window resize listener.
6209 * @param {Function} fn The method the event invokes
6210 * @param {Object} scope The scope of handler
6212 removeResizeListener : function(fn, scope){
6214 resizeEvent.removeListener(fn, scope);
6219 fireResize : function(){
6221 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6225 * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
6229 * The frequency, in milliseconds, to check for text resize events (defaults to 50)
6231 textResizeInterval : 50
6236 * @scopeAlias pub=Roo.EventManager
6240 * Appends an event handler to an element (shorthand for addListener)
6241 * @param {String/HTMLElement} element The html element or id to assign the
6242 * @param {String} eventName The type of event to listen for
6243 * @param {Function} handler The method the event invokes
6244 * @param {Object} scope (optional) The scope in which to execute the handler
6245 * function. The handler function's "this" context.
6246 * @param {Object} options (optional) An object containing handler configuration
6247 * properties. This may contain any of the following properties:<ul>
6248 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6249 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
6250 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
6251 * <li>preventDefault {Boolean} True to prevent the default action</li>
6252 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
6253 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
6254 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6255 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6256 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6257 * by the specified number of milliseconds. If the event fires again within that time, the original
6258 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6261 * <b>Combining Options</b><br>
6262 * Using the options argument, it is possible to combine different types of listeners:<br>
6264 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
6266 el.on('click', this.onClick, this, {
6273 * <b>Attaching multiple handlers in 1 call</b><br>
6274 * The method also allows for a single argument to be passed which is a config object containing properties
6275 * which specify multiple handlers.
6285 fn: this.onMouseOver
6294 * Or a shorthand syntax:<br>
6297 'click' : this.onClick,
6298 'mouseover' : this.onMouseOver,
6299 'mouseout' : this.onMouseOut
6303 pub.on = pub.addListener;
6304 pub.un = pub.removeListener;
6306 pub.stoppedMouseDownEvent = new Roo.util.Event();
6310 * Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Roo.EventManager#onDocumentReady}.
6311 * @param {Function} fn The method the event invokes
6312 * @param {Object} scope An object that becomes the scope of the handler
6313 * @param {boolean} override If true, the obj passed in becomes
6314 * the execution scope of the listener
6318 Roo.onReady = Roo.EventManager.onDocumentReady;
6320 Roo.onReady(function(){
6321 var bd = Roo.get(document.body);
6326 : Roo.isGecko ? "roo-gecko"
6327 : Roo.isOpera ? "roo-opera"
6328 : Roo.isSafari ? "roo-safari" : ""];
6331 cls.push("roo-mac");
6334 cls.push("roo-linux");
6336 if(Roo.isBorderBox){
6337 cls.push('roo-border-box');
6339 if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
6340 var p = bd.dom.parentNode;
6342 p.className += ' roo-strict';
6345 bd.addClass(cls.join(' '));
6349 * @class Roo.EventObject
6350 * EventObject exposes the Yahoo! UI Event functionality directly on the object
6351 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
6354 function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
6356 var target = e.getTarget();
6359 var myDiv = Roo.get("myDiv");
6360 myDiv.on("click", handleClick);
6362 Roo.EventManager.on("myDiv", 'click', handleClick);
6363 Roo.EventManager.addListener("myDiv", 'click', handleClick);
6367 Roo.EventObject = function(){
6369 var E = Roo.lib.Event;
6371 // safari keypress events for special keys return bad keycodes
6374 63235 : 39, // right
6377 63276 : 33, // page up
6378 63277 : 34, // page down
6379 63272 : 46, // delete
6384 // normalize button clicks
6385 var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
6386 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
6388 Roo.EventObjectImpl = function(e){
6390 this.setEvent(e.browserEvent || e);
6393 Roo.EventObjectImpl.prototype = {
6395 * Used to fix doc tools.
6396 * @scope Roo.EventObject.prototype
6402 /** The normal browser event */
6403 browserEvent : null,
6404 /** The button pressed in a mouse event */
6406 /** True if the shift key was down during the event */
6408 /** True if the control key was down during the event */
6410 /** True if the alt key was down during the event */
6469 setEvent : function(e){
6470 if(e == this || (e && e.browserEvent)){ // already wrapped
6473 this.browserEvent = e;
6475 // normalize buttons
6476 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
6477 if(e.type == 'click' && this.button == -1){
6481 this.shiftKey = e.shiftKey;
6482 // mac metaKey behaves like ctrlKey
6483 this.ctrlKey = e.ctrlKey || e.metaKey;
6484 this.altKey = e.altKey;
6485 // in getKey these will be normalized for the mac
6486 this.keyCode = e.keyCode;
6487 // keyup warnings on firefox.
6488 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
6489 // cache the target for the delayed and or buffered events
6490 this.target = E.getTarget(e);
6492 this.xy = E.getXY(e);
6495 this.shiftKey = false;
6496 this.ctrlKey = false;
6497 this.altKey = false;
6507 * Stop the event (preventDefault and stopPropagation)
6509 stopEvent : function(){
6510 if(this.browserEvent){
6511 if(this.browserEvent.type == 'mousedown'){
6512 Roo.EventManager.stoppedMouseDownEvent.fire(this);
6514 E.stopEvent(this.browserEvent);
6519 * Prevents the browsers default handling of the event.
6521 preventDefault : function(){
6522 if(this.browserEvent){
6523 E.preventDefault(this.browserEvent);
6528 isNavKeyPress : function(){
6529 var k = this.keyCode;
6530 k = Roo.isSafari ? (safariKeys[k] || k) : k;
6531 return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
6534 isSpecialKey : function(){
6535 var k = this.keyCode;
6536 return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
6537 (k == 16) || (k == 17) ||
6538 (k >= 18 && k <= 20) ||
6539 (k >= 33 && k <= 35) ||
6540 (k >= 36 && k <= 39) ||
6541 (k >= 44 && k <= 45);
6544 * Cancels bubbling of the event.
6546 stopPropagation : function(){
6547 if(this.browserEvent){
6548 if(this.type == 'mousedown'){
6549 Roo.EventManager.stoppedMouseDownEvent.fire(this);
6551 E.stopPropagation(this.browserEvent);
6556 * Gets the key code for the event.
6559 getCharCode : function(){
6560 return this.charCode || this.keyCode;
6564 * Returns a normalized keyCode for the event.
6565 * @return {Number} The key code
6567 getKey : function(){
6568 var k = this.keyCode || this.charCode;
6569 return Roo.isSafari ? (safariKeys[k] || k) : k;
6573 * Gets the x coordinate of the event.
6576 getPageX : function(){
6581 * Gets the y coordinate of the event.
6584 getPageY : function(){
6589 * Gets the time of the event.
6592 getTime : function(){
6593 if(this.browserEvent){
6594 return E.getTime(this.browserEvent);
6600 * Gets the page coordinates of the event.
6601 * @return {Array} The xy values like [x, y]
6608 * Gets the target for the event.
6609 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
6610 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
6611 search as a number or element (defaults to 10 || document.body)
6612 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
6613 * @return {HTMLelement}
6615 getTarget : function(selector, maxDepth, returnEl){
6616 return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
6619 * Gets the related target.
6620 * @return {HTMLElement}
6622 getRelatedTarget : function(){
6623 if(this.browserEvent){
6624 return E.getRelatedTarget(this.browserEvent);
6630 * Normalizes mouse wheel delta across browsers
6631 * @return {Number} The delta
6633 getWheelDelta : function(){
6634 var e = this.browserEvent;
6636 if(e.wheelDelta){ /* IE/Opera. */
6637 delta = e.wheelDelta/120;
6638 }else if(e.detail){ /* Mozilla case. */
6639 delta = -e.detail/3;
6645 * Returns true if the control, meta, shift or alt key was pressed during this event.
6648 hasModifier : function(){
6649 return !!((this.ctrlKey || this.altKey) || this.shiftKey);
6653 * Returns true if the target of this event equals el or is a child of el
6654 * @param {String/HTMLElement/Element} el
6655 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
6658 within : function(el, related){
6659 var t = this[related ? "getRelatedTarget" : "getTarget"]();
6660 return t && Roo.fly(el).contains(t);
6663 getPoint : function(){
6664 return new Roo.lib.Point(this.xy[0], this.xy[1]);
6668 return new Roo.EventObjectImpl();
6673 * Ext JS Library 1.1.1
6674 * Copyright(c) 2006-2007, Ext JS, LLC.
6676 * Originally Released Under LGPL - original licence link has changed is not relivant.
6679 * <script type="text/javascript">
6683 // was in Composite Element!??!?!
6686 var D = Roo.lib.Dom;
6687 var E = Roo.lib.Event;
6688 var A = Roo.lib.Anim;
6690 // local style camelizing for speed
6692 var camelRe = /(-[a-z])/gi;
6693 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
6694 var view = document.defaultView;
6697 * @class Roo.Element
6698 * Represents an Element in the DOM.<br><br>
6701 var el = Roo.get("my-div");
6704 var el = getEl("my-div");
6706 // or with a DOM element
6707 var el = Roo.get(myDivElement);
6709 * Using Roo.get() or getEl() instead of calling the constructor directly ensures you get the same object
6710 * each call instead of constructing a new one.<br><br>
6711 * <b>Animations</b><br />
6712 * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
6713 * should either be a boolean (true) or an object literal with animation options. The animation options are:
6715 Option Default Description
6716 --------- -------- ---------------------------------------------
6717 duration .35 The duration of the animation in seconds
6718 easing easeOut The YUI easing method
6719 callback none A function to execute when the anim completes
6720 scope this The scope (this) of the callback function
6722 * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
6723 * manipulate the animation. Here's an example:
6725 var el = Roo.get("my-div");
6730 // default animation
6731 el.setWidth(100, true);
6733 // animation with some options set
6740 // using the "anim" property to get the Anim object
6746 el.setWidth(100, opt);
6748 if(opt.anim.isAnimated()){
6752 * <b> Composite (Collections of) Elements</b><br />
6753 * For working with collections of Elements, see <a href="Roo.CompositeElement.html">Roo.CompositeElement</a>
6754 * @constructor Create a new Element directly.
6755 * @param {String/HTMLElement} element
6756 * @param {Boolean} forceNew (optional) By default the constructor checks to see if there is already an instance of this element in the cache and if there is it returns the same instance. This will skip that check (useful for extending this class).
6758 Roo.Element = function(element, forceNew){
6759 var dom = typeof element == "string" ?
6760 document.getElementById(element) : element;
6761 if(!dom){ // invalid id/element
6765 if(forceNew !== true && id && Roo.Element.cache[id]){ // element object already exists
6766 return Roo.Element.cache[id];
6776 * The DOM element ID
6779 this.id = id || Roo.id(dom);
6782 var El = Roo.Element;
6786 * The element's default display mode (defaults to "")
6789 originalDisplay : "",
6793 * The default unit to append to CSS values where a unit isn't provided (defaults to px).
6798 * Sets the element's visibility mode. When setVisible() is called it
6799 * will use this to determine whether to set the visibility or the display property.
6800 * @param visMode Element.VISIBILITY or Element.DISPLAY
6801 * @return {Roo.Element} this
6803 setVisibilityMode : function(visMode){
6804 this.visibilityMode = visMode;
6808 * Convenience method for setVisibilityMode(Element.DISPLAY)
6809 * @param {String} display (optional) What to set display to when visible
6810 * @return {Roo.Element} this
6812 enableDisplayMode : function(display){
6813 this.setVisibilityMode(El.DISPLAY);
6814 if(typeof display != "undefined") this.originalDisplay = display;
6819 * Looks at this node and then at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
6820 * @param {String} selector The simple selector to test
6821 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
6822 search as a number or element (defaults to 10 || document.body)
6823 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
6824 * @return {HTMLElement} The matching DOM node (or null if no match was found)
6826 findParent : function(simpleSelector, maxDepth, returnEl){
6827 var p = this.dom, b = document.body, depth = 0, dq = Roo.DomQuery, stopEl;
6828 maxDepth = maxDepth || 50;
6829 if(typeof maxDepth != "number"){
6830 stopEl = Roo.getDom(maxDepth);
6833 while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
6834 if(dq.is(p, simpleSelector)){
6835 return returnEl ? Roo.get(p) : p;
6845 * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
6846 * @param {String} selector The simple selector to test
6847 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
6848 search as a number or element (defaults to 10 || document.body)
6849 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
6850 * @return {HTMLElement} The matching DOM node (or null if no match was found)
6852 findParentNode : function(simpleSelector, maxDepth, returnEl){
6853 var p = Roo.fly(this.dom.parentNode, '_internal');
6854 return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
6858 * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
6859 * This is a shortcut for findParentNode() that always returns an Roo.Element.
6860 * @param {String} selector The simple selector to test
6861 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
6862 search as a number or element (defaults to 10 || document.body)
6863 * @return {Roo.Element} The matching DOM node (or null if no match was found)
6865 up : function(simpleSelector, maxDepth){
6866 return this.findParentNode(simpleSelector, maxDepth, true);
6872 * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
6873 * @param {String} selector The simple selector to test
6874 * @return {Boolean} True if this element matches the selector, else false
6876 is : function(simpleSelector){
6877 return Roo.DomQuery.is(this.dom, simpleSelector);
6881 * Perform animation on this element.
6882 * @param {Object} args The YUI animation control args
6883 * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35)
6884 * @param {Function} onComplete (optional) Function to call when animation completes
6885 * @param {String} easing (optional) Easing method to use (defaults to 'easeOut')
6886 * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
6887 * @return {Roo.Element} this
6889 animate : function(args, duration, onComplete, easing, animType){
6890 this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
6895 * @private Internal animation call
6897 anim : function(args, opt, animType, defaultDur, defaultEase, cb){
6898 animType = animType || 'run';
6900 var anim = Roo.lib.Anim[animType](
6902 (opt.duration || defaultDur) || .35,
6903 (opt.easing || defaultEase) || 'easeOut',
6905 Roo.callback(cb, this);
6906 Roo.callback(opt.callback, opt.scope || this, [this, opt]);
6914 // private legacy anim prep
6915 preanim : function(a, i){
6916 return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
6920 * Removes worthless text nodes
6921 * @param {Boolean} forceReclean (optional) By default the element
6922 * keeps track if it has been cleaned already so
6923 * you can call this over and over. However, if you update the element and
6924 * need to force a reclean, you can pass true.
6926 clean : function(forceReclean){
6927 if(this.isCleaned && forceReclean !== true){
6931 var d = this.dom, n = d.firstChild, ni = -1;
6933 var nx = n.nextSibling;
6934 if(n.nodeType == 3 && !ns.test(n.nodeValue)){
6941 this.isCleaned = true;
6946 calcOffsetsTo : function(el){
6949 var restorePos = false;
6950 if(el.getStyle('position') == 'static'){
6951 el.position('relative');
6956 while(op && op != d && op.tagName != 'HTML'){
6959 op = op.offsetParent;
6962 el.position('static');
6968 * Scrolls this element into view within the passed container.
6969 * @param {String/HTMLElement/Element} container (optional) The container element to scroll (defaults to document.body)
6970 * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
6971 * @return {Roo.Element} this
6973 scrollIntoView : function(container, hscroll){
6974 var c = Roo.getDom(container) || document.body;
6977 var o = this.calcOffsetsTo(c),
6980 b = t+el.offsetHeight,
6981 r = l+el.offsetWidth;
6983 var ch = c.clientHeight;
6984 var ct = parseInt(c.scrollTop, 10);
6985 var cl = parseInt(c.scrollLeft, 10);
6987 var cr = cl + c.clientWidth;
6995 if(hscroll !== false){
6999 c.scrollLeft = r-c.clientWidth;
7006 scrollChildIntoView : function(child, hscroll){
7007 Roo.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
7011 * Measures the element's content height and updates height to match. Note: this function uses setTimeout so
7012 * the new height may not be available immediately.
7013 * @param {Boolean} animate (optional) Animate the transition (defaults to false)
7014 * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
7015 * @param {Function} onComplete (optional) Function to call when animation completes
7016 * @param {String} easing (optional) Easing method to use (defaults to easeOut)
7017 * @return {Roo.Element} this
7019 autoHeight : function(animate, duration, onComplete, easing){
7020 var oldHeight = this.getHeight();
7022 this.setHeight(1); // force clipping
7023 setTimeout(function(){
7024 var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
7026 this.setHeight(height);
7028 if(typeof onComplete == "function"){
7032 this.setHeight(oldHeight); // restore original height
7033 this.setHeight(height, animate, duration, function(){
7035 if(typeof onComplete == "function") onComplete();
7036 }.createDelegate(this), easing);
7038 }.createDelegate(this), 0);
7043 * Returns true if this element is an ancestor of the passed element
7044 * @param {HTMLElement/String} el The element to check
7045 * @return {Boolean} True if this element is an ancestor of el, else false
7047 contains : function(el){
7048 if(!el){return false;}
7049 return D.isAncestor(this.dom, el.dom ? el.dom : el);
7053 * Checks whether the element is currently visible using both visibility and display properties.
7054 * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
7055 * @return {Boolean} True if the element is currently visible, else false
7057 isVisible : function(deep) {
7058 var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
7059 if(deep !== true || !vis){
7062 var p = this.dom.parentNode;
7063 while(p && p.tagName.toLowerCase() != "body"){
7064 if(!Roo.fly(p, '_isVisible').isVisible()){
7073 * Creates a {@link Roo.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
7074 * @param {String} selector The CSS selector
7075 * @param {Boolean} unique (optional) True to create a unique Roo.Element for each child (defaults to false, which creates a single shared flyweight object)
7076 * @return {CompositeElement/CompositeElementLite} The composite element
7078 select : function(selector, unique){
7079 return El.select(selector, unique, this.dom);
7083 * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
7084 * @param {String} selector The CSS selector
7085 * @return {Array} An array of the matched nodes
7087 query : function(selector, unique){
7088 return Roo.DomQuery.select(selector, this.dom);
7092 * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
7093 * @param {String} selector The CSS selector
7094 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
7095 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
7097 child : function(selector, returnDom){
7098 var n = Roo.DomQuery.selectNode(selector, this.dom);
7099 return returnDom ? n : Roo.get(n);
7103 * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
7104 * @param {String} selector The CSS selector
7105 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
7106 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
7108 down : function(selector, returnDom){
7109 var n = Roo.DomQuery.selectNode(" > " + selector, this.dom);
7110 return returnDom ? n : Roo.get(n);
7114 * Initializes a {@link Roo.dd.DD} drag drop object for this element.
7115 * @param {String} group The group the DD object is member of
7116 * @param {Object} config The DD config object
7117 * @param {Object} overrides An object containing methods to override/implement on the DD object
7118 * @return {Roo.dd.DD} The DD object
7120 initDD : function(group, config, overrides){
7121 var dd = new Roo.dd.DD(Roo.id(this.dom), group, config);
7122 return Roo.apply(dd, overrides);
7126 * Initializes a {@link Roo.dd.DDProxy} object for this element.
7127 * @param {String} group The group the DDProxy object is member of
7128 * @param {Object} config The DDProxy config object
7129 * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
7130 * @return {Roo.dd.DDProxy} The DDProxy object
7132 initDDProxy : function(group, config, overrides){
7133 var dd = new Roo.dd.DDProxy(Roo.id(this.dom), group, config);
7134 return Roo.apply(dd, overrides);
7138 * Initializes a {@link Roo.dd.DDTarget} object for this element.
7139 * @param {String} group The group the DDTarget object is member of
7140 * @param {Object} config The DDTarget config object
7141 * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
7142 * @return {Roo.dd.DDTarget} The DDTarget object
7144 initDDTarget : function(group, config, overrides){
7145 var dd = new Roo.dd.DDTarget(Roo.id(this.dom), group, config);
7146 return Roo.apply(dd, overrides);
7150 * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
7151 * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
7152 * @param {Boolean} visible Whether the element is visible
7153 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7154 * @return {Roo.Element} this
7156 setVisible : function(visible, animate){
7158 if(this.visibilityMode == El.DISPLAY){
7159 this.setDisplayed(visible);
7162 this.dom.style.visibility = visible ? "visible" : "hidden";
7165 // closure for composites
7167 var visMode = this.visibilityMode;
7169 this.setOpacity(.01);
7170 this.setVisible(true);
7172 this.anim({opacity: { to: (visible?1:0) }},
7173 this.preanim(arguments, 1),
7174 null, .35, 'easeIn', function(){
7176 if(visMode == El.DISPLAY){
7177 dom.style.display = "none";
7179 dom.style.visibility = "hidden";
7181 Roo.get(dom).setOpacity(1);
7189 * Returns true if display is not "none"
7192 isDisplayed : function() {
7193 return this.getStyle("display") != "none";
7197 * Toggles the element's visibility or display, depending on visibility mode.
7198 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7199 * @return {Roo.Element} this
7201 toggle : function(animate){
7202 this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
7207 * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
7208 * @param {Boolean} value Boolean value to display the element using its default display, or a string to set the display directly
7209 * @return {Roo.Element} this
7211 setDisplayed : function(value) {
7212 if(typeof value == "boolean"){
7213 value = value ? this.originalDisplay : "none";
7215 this.setStyle("display", value);
7220 * Tries to focus the element. Any exceptions are caught and ignored.
7221 * @return {Roo.Element} this
7223 focus : function() {
7231 * Tries to blur the element. Any exceptions are caught and ignored.
7232 * @return {Roo.Element} this
7242 * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
7243 * @param {String/Array} className The CSS class to add, or an array of classes
7244 * @return {Roo.Element} this
7246 addClass : function(className){
7247 if(className instanceof Array){
7248 for(var i = 0, len = className.length; i < len; i++) {
7249 this.addClass(className[i]);
7252 if(className && !this.hasClass(className)){
7253 this.dom.className = this.dom.className + " " + className;
7260 * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
7261 * @param {String/Array} className The CSS class to add, or an array of classes
7262 * @return {Roo.Element} this
7264 radioClass : function(className){
7265 var siblings = this.dom.parentNode.childNodes;
7266 for(var i = 0; i < siblings.length; i++) {
7267 var s = siblings[i];
7268 if(s.nodeType == 1){
7269 Roo.get(s).removeClass(className);
7272 this.addClass(className);
7277 * Removes one or more CSS classes from the element.
7278 * @param {String/Array} className The CSS class to remove, or an array of classes
7279 * @return {Roo.Element} this
7281 removeClass : function(className){
7282 if(!className || !this.dom.className){
7285 if(className instanceof Array){
7286 for(var i = 0, len = className.length; i < len; i++) {
7287 this.removeClass(className[i]);
7290 if(this.hasClass(className)){
7291 var re = this.classReCache[className];
7293 re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
7294 this.classReCache[className] = re;
7296 this.dom.className =
7297 this.dom.className.replace(re, " ");
7307 * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
7308 * @param {String} className The CSS class to toggle
7309 * @return {Roo.Element} this
7311 toggleClass : function(className){
7312 if(this.hasClass(className)){
7313 this.removeClass(className);
7315 this.addClass(className);
7321 * Checks if the specified CSS class exists on this element's DOM node.
7322 * @param {String} className The CSS class to check for
7323 * @return {Boolean} True if the class exists, else false
7325 hasClass : function(className){
7326 return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
7330 * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
7331 * @param {String} oldClassName The CSS class to replace
7332 * @param {String} newClassName The replacement CSS class
7333 * @return {Roo.Element} this
7335 replaceClass : function(oldClassName, newClassName){
7336 this.removeClass(oldClassName);
7337 this.addClass(newClassName);
7342 * Returns an object with properties matching the styles requested.
7343 * For example, el.getStyles('color', 'font-size', 'width') might return
7344 * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
7345 * @param {String} style1 A style name
7346 * @param {String} style2 A style name
7347 * @param {String} etc.
7348 * @return {Object} The style object
7350 getStyles : function(){
7351 var a = arguments, len = a.length, r = {};
7352 for(var i = 0; i < len; i++){
7353 r[a[i]] = this.getStyle(a[i]);
7359 * Normalizes currentStyle and computedStyle. This is not YUI getStyle, it is an optimised version.
7360 * @param {String} property The style property whose value is returned.
7361 * @return {String} The current value of the style property for this element.
7363 getStyle : function(){
7364 return view && view.getComputedStyle ?
7366 var el = this.dom, v, cs, camel;
7367 if(prop == 'float'){
7370 if(el.style && (v = el.style[prop])){
7373 if(cs = view.getComputedStyle(el, "")){
7374 if(!(camel = propCache[prop])){
7375 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7382 var el = this.dom, v, cs, camel;
7383 if(prop == 'opacity'){
7384 if(typeof el.style.filter == 'string'){
7385 var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
7387 var fv = parseFloat(m[1]);
7389 return fv ? fv / 100 : 0;
7394 }else if(prop == 'float'){
7395 prop = "styleFloat";
7397 if(!(camel = propCache[prop])){
7398 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7400 if(v = el.style[camel]){
7403 if(cs = el.currentStyle){
7411 * Wrapper for setting style properties, also takes single object parameter of multiple styles.
7412 * @param {String/Object} property The style property to be set, or an object of multiple styles.
7413 * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
7414 * @return {Roo.Element} this
7416 setStyle : function(prop, value){
7417 if(typeof prop == "string"){
7419 if (prop == 'float') {
7420 this.setStyle(Roo.isIE ? 'styleFloat' : 'cssFloat', value);
7425 if(!(camel = propCache[prop])){
7426 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7429 if(camel == 'opacity') {
7430 this.setOpacity(value);
7432 this.dom.style[camel] = value;
7435 for(var style in prop){
7436 if(typeof prop[style] != "function"){
7437 this.setStyle(style, prop[style]);
7445 * More flexible version of {@link #setStyle} for setting style properties.
7446 * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
7447 * a function which returns such a specification.
7448 * @return {Roo.Element} this
7450 applyStyles : function(style){
7451 Roo.DomHelper.applyStyles(this.dom, style);
7456 * Gets the current X position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7457 * @return {Number} The X position of the element
7460 return D.getX(this.dom);
7464 * Gets the current Y position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7465 * @return {Number} The Y position of the element
7468 return D.getY(this.dom);
7472 * Gets the current position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7473 * @return {Array} The XY position of the element
7476 return D.getXY(this.dom);
7480 * Sets the X position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7481 * @param {Number} The X position of the element
7482 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7483 * @return {Roo.Element} this
7485 setX : function(x, animate){
7487 D.setX(this.dom, x);
7489 this.setXY([x, this.getY()], this.preanim(arguments, 1));
7495 * Sets the Y position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7496 * @param {Number} The Y position of the element
7497 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7498 * @return {Roo.Element} this
7500 setY : function(y, animate){
7502 D.setY(this.dom, y);
7504 this.setXY([this.getX(), y], this.preanim(arguments, 1));
7510 * Sets the element's left position directly using CSS style (instead of {@link #setX}).
7511 * @param {String} left The left CSS property value
7512 * @return {Roo.Element} this
7514 setLeft : function(left){
7515 this.setStyle("left", this.addUnits(left));
7520 * Sets the element's top position directly using CSS style (instead of {@link #setY}).
7521 * @param {String} top The top CSS property value
7522 * @return {Roo.Element} this
7524 setTop : function(top){
7525 this.setStyle("top", this.addUnits(top));
7530 * Sets the element's CSS right style.
7531 * @param {String} right The right CSS property value
7532 * @return {Roo.Element} this
7534 setRight : function(right){
7535 this.setStyle("right", this.addUnits(right));
7540 * Sets the element's CSS bottom style.
7541 * @param {String} bottom The bottom CSS property value
7542 * @return {Roo.Element} this
7544 setBottom : function(bottom){
7545 this.setStyle("bottom", this.addUnits(bottom));
7550 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7551 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7552 * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
7553 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7554 * @return {Roo.Element} this
7556 setXY : function(pos, animate){
7558 D.setXY(this.dom, pos);
7560 this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
7566 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7567 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7568 * @param {Number} x X value for new position (coordinates are page-based)
7569 * @param {Number} y Y value for new position (coordinates are page-based)
7570 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7571 * @return {Roo.Element} this
7573 setLocation : function(x, y, animate){
7574 this.setXY([x, y], this.preanim(arguments, 2));
7579 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7580 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7581 * @param {Number} x X value for new position (coordinates are page-based)
7582 * @param {Number} y Y value for new position (coordinates are page-based)
7583 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7584 * @return {Roo.Element} this
7586 moveTo : function(x, y, animate){
7587 this.setXY([x, y], this.preanim(arguments, 2));
7592 * Returns the region of the given element.
7593 * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
7594 * @return {Region} A Roo.lib.Region containing "top, left, bottom, right" member data.
7596 getRegion : function(){
7597 return D.getRegion(this.dom);
7601 * Returns the offset height of the element
7602 * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
7603 * @return {Number} The element's height
7605 getHeight : function(contentHeight){
7606 var h = this.dom.offsetHeight || 0;
7607 return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
7611 * Returns the offset width of the element
7612 * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
7613 * @return {Number} The element's width
7615 getWidth : function(contentWidth){
7616 var w = this.dom.offsetWidth || 0;
7617 return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
7621 * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
7622 * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
7623 * if a height has not been set using CSS.
7626 getComputedHeight : function(){
7627 var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
7629 h = parseInt(this.getStyle('height'), 10) || 0;
7630 if(!this.isBorderBox()){
7631 h += this.getFrameWidth('tb');
7638 * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
7639 * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
7640 * if a width has not been set using CSS.
7643 getComputedWidth : function(){
7644 var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
7646 w = parseInt(this.getStyle('width'), 10) || 0;
7647 if(!this.isBorderBox()){
7648 w += this.getFrameWidth('lr');
7655 * Returns the size of the element.
7656 * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
7657 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
7659 getSize : function(contentSize){
7660 return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
7664 * Returns the width and height of the viewport.
7665 * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)}
7667 getViewSize : function(){
7668 var d = this.dom, doc = document, aw = 0, ah = 0;
7669 if(d == doc || d == doc.body){
7670 return {width : D.getViewWidth(), height: D.getViewHeight()};
7673 width : d.clientWidth,
7674 height: d.clientHeight
7680 * Returns the value of the "value" attribute
7681 * @param {Boolean} asNumber true to parse the value as a number
7682 * @return {String/Number}
7684 getValue : function(asNumber){
7685 return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
7689 adjustWidth : function(width){
7690 if(typeof width == "number"){
7691 if(this.autoBoxAdjust && !this.isBorderBox()){
7692 width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
7702 adjustHeight : function(height){
7703 if(typeof height == "number"){
7704 if(this.autoBoxAdjust && !this.isBorderBox()){
7705 height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
7715 * Set the width of the element
7716 * @param {Number} width The new width
7717 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7718 * @return {Roo.Element} this
7720 setWidth : function(width, animate){
7721 width = this.adjustWidth(width);
7723 this.dom.style.width = this.addUnits(width);
7725 this.anim({width: {to: width}}, this.preanim(arguments, 1));
7731 * Set the height of the element
7732 * @param {Number} height The new height
7733 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7734 * @return {Roo.Element} this
7736 setHeight : function(height, animate){
7737 height = this.adjustHeight(height);
7739 this.dom.style.height = this.addUnits(height);
7741 this.anim({height: {to: height}}, this.preanim(arguments, 1));
7747 * Set the size of the element. If animation is true, both width an height will be animated concurrently.
7748 * @param {Number} width The new width
7749 * @param {Number} height The new height
7750 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7751 * @return {Roo.Element} this
7753 setSize : function(width, height, animate){
7754 if(typeof width == "object"){ // in case of object from getSize()
7755 height = width.height; width = width.width;
7757 width = this.adjustWidth(width); height = this.adjustHeight(height);
7759 this.dom.style.width = this.addUnits(width);
7760 this.dom.style.height = this.addUnits(height);
7762 this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
7768 * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
7769 * @param {Number} x X value for new position (coordinates are page-based)
7770 * @param {Number} y Y value for new position (coordinates are page-based)
7771 * @param {Number} width The new width
7772 * @param {Number} height The new height
7773 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7774 * @return {Roo.Element} this
7776 setBounds : function(x, y, width, height, animate){
7778 this.setSize(width, height);
7779 this.setLocation(x, y);
7781 width = this.adjustWidth(width); height = this.adjustHeight(height);
7782 this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
7783 this.preanim(arguments, 4), 'motion');
7789 * Sets the element's position and size the the specified region. If animation is true then width, height, x and y will be animated concurrently.
7790 * @param {Roo.lib.Region} region The region to fill
7791 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7792 * @return {Roo.Element} this
7794 setRegion : function(region, animate){
7795 this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
7800 * Appends an event handler
7802 * @param {String} eventName The type of event to append
7803 * @param {Function} fn The method the event invokes
7804 * @param {Object} scope (optional) The scope (this object) of the fn
7805 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
7807 addListener : function(eventName, fn, scope, options){
7808 Roo.EventManager.on(this.dom, eventName, fn, scope || this, options);
7812 * Removes an event handler from this element
7813 * @param {String} eventName the type of event to remove
7814 * @param {Function} fn the method the event invokes
7815 * @return {Roo.Element} this
7817 removeListener : function(eventName, fn){
7818 Roo.EventManager.removeListener(this.dom, eventName, fn);
7823 * Removes all previous added listeners from this element
7824 * @return {Roo.Element} this
7826 removeAllListeners : function(){
7827 E.purgeElement(this.dom);
7831 relayEvent : function(eventName, observable){
7832 this.on(eventName, function(e){
7833 observable.fireEvent(eventName, e);
7838 * Set the opacity of the element
7839 * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
7840 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7841 * @return {Roo.Element} this
7843 setOpacity : function(opacity, animate){
7845 var s = this.dom.style;
7848 s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
7849 (opacity == 1 ? "" : "alpha(opacity=" + opacity * 100 + ")");
7851 s.opacity = opacity;
7854 this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
7860 * Gets the left X coordinate
7861 * @param {Boolean} local True to get the local css position instead of page coordinate
7864 getLeft : function(local){
7868 return parseInt(this.getStyle("left"), 10) || 0;
7873 * Gets the right X coordinate of the element (element X position + element width)
7874 * @param {Boolean} local True to get the local css position instead of page coordinate
7877 getRight : function(local){
7879 return this.getX() + this.getWidth();
7881 return (this.getLeft(true) + this.getWidth()) || 0;
7886 * Gets the top Y coordinate
7887 * @param {Boolean} local True to get the local css position instead of page coordinate
7890 getTop : function(local) {
7894 return parseInt(this.getStyle("top"), 10) || 0;
7899 * Gets the bottom Y coordinate of the element (element Y position + element height)
7900 * @param {Boolean} local True to get the local css position instead of page coordinate
7903 getBottom : function(local){
7905 return this.getY() + this.getHeight();
7907 return (this.getTop(true) + this.getHeight()) || 0;
7912 * Initializes positioning on this element. If a desired position is not passed, it will make the
7913 * the element positioned relative IF it is not already positioned.
7914 * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
7915 * @param {Number} zIndex (optional) The zIndex to apply
7916 * @param {Number} x (optional) Set the page X position
7917 * @param {Number} y (optional) Set the page Y position
7919 position : function(pos, zIndex, x, y){
7921 if(this.getStyle('position') == 'static'){
7922 this.setStyle('position', 'relative');
7925 this.setStyle("position", pos);
7928 this.setStyle("z-index", zIndex);
7930 if(x !== undefined && y !== undefined){
7932 }else if(x !== undefined){
7934 }else if(y !== undefined){
7940 * Clear positioning back to the default when the document was loaded
7941 * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
7942 * @return {Roo.Element} this
7944 clearPositioning : function(value){
7952 "position" : "static"
7958 * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
7959 * snapshot before performing an update and then restoring the element.
7962 getPositioning : function(){
7963 var l = this.getStyle("left");
7964 var t = this.getStyle("top");
7966 "position" : this.getStyle("position"),
7968 "right" : l ? "" : this.getStyle("right"),
7970 "bottom" : t ? "" : this.getStyle("bottom"),
7971 "z-index" : this.getStyle("z-index")
7976 * Gets the width of the border(s) for the specified side(s)
7977 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
7978 * passing lr would get the border (l)eft width + the border (r)ight width.
7979 * @return {Number} The width of the sides passed added together
7981 getBorderWidth : function(side){
7982 return this.addStyles(side, El.borders);
7986 * Gets the width of the padding(s) for the specified side(s)
7987 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
7988 * passing lr would get the padding (l)eft + the padding (r)ight.
7989 * @return {Number} The padding of the sides passed added together
7991 getPadding : function(side){
7992 return this.addStyles(side, El.paddings);
7996 * Set positioning with an object returned by getPositioning().
7997 * @param {Object} posCfg
7998 * @return {Roo.Element} this
8000 setPositioning : function(pc){
8001 this.applyStyles(pc);
8002 if(pc.right == "auto"){
8003 this.dom.style.right = "";
8005 if(pc.bottom == "auto"){
8006 this.dom.style.bottom = "";
8012 fixDisplay : function(){
8013 if(this.getStyle("display") == "none"){
8014 this.setStyle("visibility", "hidden");
8015 this.setStyle("display", this.originalDisplay); // first try reverting to default
8016 if(this.getStyle("display") == "none"){ // if that fails, default to block
8017 this.setStyle("display", "block");
8023 * Quick set left and top adding default units
8024 * @param {String} left The left CSS property value
8025 * @param {String} top The top CSS property value
8026 * @return {Roo.Element} this
8028 setLeftTop : function(left, top){
8029 this.dom.style.left = this.addUnits(left);
8030 this.dom.style.top = this.addUnits(top);
8035 * Move this element relative to its current position.
8036 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
8037 * @param {Number} distance How far to move the element in pixels
8038 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8039 * @return {Roo.Element} this
8041 move : function(direction, distance, animate){
8042 var xy = this.getXY();
8043 direction = direction.toLowerCase();
8047 this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
8051 this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
8056 this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
8061 this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
8068 * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
8069 * @return {Roo.Element} this
8072 if(!this.isClipped){
8073 this.isClipped = true;
8074 this.originalClip = {
8075 "o": this.getStyle("overflow"),
8076 "x": this.getStyle("overflow-x"),
8077 "y": this.getStyle("overflow-y")
8079 this.setStyle("overflow", "hidden");
8080 this.setStyle("overflow-x", "hidden");
8081 this.setStyle("overflow-y", "hidden");
8087 * Return clipping (overflow) to original clipping before clip() was called
8088 * @return {Roo.Element} this
8090 unclip : function(){
8092 this.isClipped = false;
8093 var o = this.originalClip;
8094 if(o.o){this.setStyle("overflow", o.o);}
8095 if(o.x){this.setStyle("overflow-x", o.x);}
8096 if(o.y){this.setStyle("overflow-y", o.y);}
8103 * Gets the x,y coordinates specified by the anchor position on the element.
8104 * @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo} for details on supported anchor positions.
8105 * @param {Object} size (optional) An object containing the size to use for calculating anchor position
8106 * {width: (target width), height: (target height)} (defaults to the element's current size)
8107 * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead of page coordinates
8108 * @return {Array} [x, y] An array containing the element's x and y coordinates
8110 getAnchorXY : function(anchor, local, s){
8111 //Passing a different size is useful for pre-calculating anchors,
8112 //especially for anchored animations that change the el size.
8114 var w, h, vp = false;
8117 if(d == document.body || d == document){
8119 w = D.getViewWidth(); h = D.getViewHeight();
8121 w = this.getWidth(); h = this.getHeight();
8124 w = s.width; h = s.height;
8126 var x = 0, y = 0, r = Math.round;
8127 switch((anchor || "tl").toLowerCase()){
8169 var sc = this.getScroll();
8170 return [x + sc.left, y + sc.top];
8172 //Add the element's offset xy
8173 var o = this.getXY();
8174 return [x+o[0], y+o[1]];
8178 * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
8179 * supported position values.
8180 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8181 * @param {String} position The position to align to.
8182 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8183 * @return {Array} [x, y]
8185 getAlignToXY : function(el, p, o){
8189 throw "Element.alignTo with an element that doesn't exist";
8191 var c = false; //constrain to viewport
8192 var p1 = "", p2 = "";
8199 }else if(p.indexOf("-") == -1){
8202 p = p.toLowerCase();
8203 var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
8205 throw "Element.alignTo with an invalid alignment " + p;
8207 p1 = m[1]; p2 = m[2]; c = !!m[3];
8209 //Subtract the aligned el's internal xy from the target's offset xy
8210 //plus custom offset to get the aligned el's new offset xy
8211 var a1 = this.getAnchorXY(p1, true);
8212 var a2 = el.getAnchorXY(p2, false);
8213 var x = a2[0] - a1[0] + o[0];
8214 var y = a2[1] - a1[1] + o[1];
8216 //constrain the aligned el to viewport if necessary
8217 var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
8218 // 5px of margin for ie
8219 var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5;
8221 //If we are at a viewport boundary and the aligned el is anchored on a target border that is
8222 //perpendicular to the vp border, allow the aligned el to slide on that border,
8223 //otherwise swap the aligned el to the opposite border of the target.
8224 var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
8225 var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
8226 var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t"));
8227 var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
8230 var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
8231 var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
8233 if((x+w) > dw + scrollX){
8234 x = swapX ? r.left-w : dw+scrollX-w;
8237 x = swapX ? r.right : scrollX;
8239 if((y+h) > dh + scrollY){
8240 y = swapY ? r.top-h : dh+scrollY-h;
8243 y = swapY ? r.bottom : scrollY;
8250 getConstrainToXY : function(){
8251 var os = {top:0, left:0, bottom:0, right: 0};
8253 return function(el, local, offsets, proposedXY){
8255 offsets = offsets ? Roo.applyIf(offsets, os) : os;
8257 var vw, vh, vx = 0, vy = 0;
8258 if(el.dom == document.body || el.dom == document){
8259 vw = Roo.lib.Dom.getViewWidth();
8260 vh = Roo.lib.Dom.getViewHeight();
8262 vw = el.dom.clientWidth;
8263 vh = el.dom.clientHeight;
8265 var vxy = el.getXY();
8271 var s = el.getScroll();
8273 vx += offsets.left + s.left;
8274 vy += offsets.top + s.top;
8276 vw -= offsets.right;
8277 vh -= offsets.bottom;
8282 var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
8283 var x = xy[0], y = xy[1];
8284 var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
8286 // only move it if it needs it
8289 // first validate right/bottom
8298 // then make sure top/left isn't negative
8307 return moved ? [x, y] : false;
8312 adjustForConstraints : function(xy, parent, offsets){
8313 return this.getConstrainToXY(parent || document, false, offsets, xy) || xy;
8317 * Aligns this element with another element relative to the specified anchor points. If the other element is the
8318 * document it aligns it to the viewport.
8319 * The position parameter is optional, and can be specified in any one of the following formats:
8321 * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
8322 * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
8323 * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been
8324 * deprecated in favor of the newer two anchor syntax below</i>.</li>
8325 * <li><b>Two anchors</b>: If two values from the table below are passed separated by a dash, the first value is used as the
8326 * element's anchor point, and the second value is used as the target's anchor point.</li>
8328 * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
8329 * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
8330 * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than
8331 * that specified in order to enforce the viewport constraints.
8332 * Following are all of the supported anchor positions:
8335 ----- -----------------------------
8336 tl The top left corner (default)
8337 t The center of the top edge
8338 tr The top right corner
8339 l The center of the left edge
8340 c In the center of the element
8341 r The center of the right edge
8342 bl The bottom left corner
8343 b The center of the bottom edge
8344 br The bottom right corner
8348 // align el to other-el using the default positioning ("tl-bl", non-constrained)
8349 el.alignTo("other-el");
8351 // align the top left corner of el with the top right corner of other-el (constrained to viewport)
8352 el.alignTo("other-el", "tr?");
8354 // align the bottom right corner of el with the center left edge of other-el
8355 el.alignTo("other-el", "br-l?");
8357 // align the center of el with the bottom left corner of other-el and
8358 // adjust the x position by -6 pixels (and the y position by 0)
8359 el.alignTo("other-el", "c-bl", [-6, 0]);
8361 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8362 * @param {String} position The position to align to.
8363 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8364 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8365 * @return {Roo.Element} this
8367 alignTo : function(element, position, offsets, animate){
8368 var xy = this.getAlignToXY(element, position, offsets);
8369 this.setXY(xy, this.preanim(arguments, 3));
8374 * Anchors an element to another element and realigns it when the window is resized.
8375 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8376 * @param {String} position The position to align to.
8377 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8378 * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
8379 * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
8380 * is a number, it is used as the buffer delay (defaults to 50ms).
8381 * @param {Function} callback The function to call after the animation finishes
8382 * @return {Roo.Element} this
8384 anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
8385 var action = function(){
8386 this.alignTo(el, alignment, offsets, animate);
8387 Roo.callback(callback, this);
8389 Roo.EventManager.onWindowResize(action, this);
8390 var tm = typeof monitorScroll;
8391 if(tm != 'undefined'){
8392 Roo.EventManager.on(window, 'scroll', action, this,
8393 {buffer: tm == 'number' ? monitorScroll : 50});
8395 action.call(this); // align immediately
8399 * Clears any opacity settings from this element. Required in some cases for IE.
8400 * @return {Roo.Element} this
8402 clearOpacity : function(){
8403 if (window.ActiveXObject) {
8404 if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
8405 this.dom.style.filter = "";
8408 this.dom.style.opacity = "";
8409 this.dom.style["-moz-opacity"] = "";
8410 this.dom.style["-khtml-opacity"] = "";
8416 * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
8417 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8418 * @return {Roo.Element} this
8420 hide : function(animate){
8421 this.setVisible(false, this.preanim(arguments, 0));
8426 * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
8427 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8428 * @return {Roo.Element} this
8430 show : function(animate){
8431 this.setVisible(true, this.preanim(arguments, 0));
8436 * @private Test if size has a unit, otherwise appends the default
8438 addUnits : function(size){
8439 return Roo.Element.addUnits(size, this.defaultUnit);
8443 * Temporarily enables offsets (width,height,x,y) for an element with display:none, use endMeasure() when done.
8444 * @return {Roo.Element} this
8446 beginMeasure : function(){
8448 if(el.offsetWidth || el.offsetHeight){
8449 return this; // offsets work already
8452 var p = this.dom, b = document.body; // start with this element
8453 while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){
8454 var pe = Roo.get(p);
8455 if(pe.getStyle('display') == 'none'){
8456 changed.push({el: p, visibility: pe.getStyle("visibility")});
8457 p.style.visibility = "hidden";
8458 p.style.display = "block";
8462 this._measureChanged = changed;
8468 * Restores displays to before beginMeasure was called
8469 * @return {Roo.Element} this
8471 endMeasure : function(){
8472 var changed = this._measureChanged;
8474 for(var i = 0, len = changed.length; i < len; i++) {
8476 r.el.style.visibility = r.visibility;
8477 r.el.style.display = "none";
8479 this._measureChanged = null;
8485 * Update the innerHTML of this element, optionally searching for and processing scripts
8486 * @param {String} html The new HTML
8487 * @param {Boolean} loadScripts (optional) true to look for and process scripts
8488 * @param {Function} callback For async script loading you can be noticed when the update completes
8489 * @return {Roo.Element} this
8491 update : function(html, loadScripts, callback){
8492 if(typeof html == "undefined"){
8495 if(loadScripts !== true){
8496 this.dom.innerHTML = html;
8497 if(typeof callback == "function"){
8505 html += '<span id="' + id + '"></span>';
8507 E.onAvailable(id, function(){
8508 var hd = document.getElementsByTagName("head")[0];
8509 var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
8510 var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
8511 var typeRe = /\stype=([\'\"])(.*?)\1/i;
8514 while(match = re.exec(html)){
8515 var attrs = match[1];
8516 var srcMatch = attrs ? attrs.match(srcRe) : false;
8517 if(srcMatch && srcMatch[2]){
8518 var s = document.createElement("script");
8519 s.src = srcMatch[2];
8520 var typeMatch = attrs.match(typeRe);
8521 if(typeMatch && typeMatch[2]){
8522 s.type = typeMatch[2];
8525 }else if(match[2] && match[2].length > 0){
8526 if(window.execScript) {
8527 window.execScript(match[2]);
8535 window.eval(match[2]);
8539 var el = document.getElementById(id);
8540 if(el){el.parentNode.removeChild(el);}
8541 if(typeof callback == "function"){
8545 dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
8550 * Direct access to the UpdateManager update() method (takes the same parameters).
8551 * @param {String/Function} url The url for this request or a function to call to get the url
8552 * @param {String/Object} params (optional) The parameters to pass as either a url encoded string "param1=1&param2=2" or an object {param1: 1, param2: 2}
8553 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
8554 * @param {Boolean} discardUrl (optional) By default when you execute an update the defaultUrl is changed to the last used url. If true, it will not store the url.
8555 * @return {Roo.Element} this
8558 var um = this.getUpdateManager();
8559 um.update.apply(um, arguments);
8564 * Gets this element's UpdateManager
8565 * @return {Roo.UpdateManager} The UpdateManager
8567 getUpdateManager : function(){
8568 if(!this.updateManager){
8569 this.updateManager = new Roo.UpdateManager(this);
8571 return this.updateManager;
8575 * Disables text selection for this element (normalized across browsers)
8576 * @return {Roo.Element} this
8578 unselectable : function(){
8579 this.dom.unselectable = "on";
8580 this.swallowEvent("selectstart", true);
8581 this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
8582 this.addClass("x-unselectable");
8587 * Calculates the x, y to center this element on the screen
8588 * @return {Array} The x, y values [x, y]
8590 getCenterXY : function(){
8591 return this.getAlignToXY(document, 'c-c');
8595 * Centers the Element in either the viewport, or another Element.
8596 * @param {String/HTMLElement/Roo.Element} centerIn (optional) The element in which to center the element.
8598 center : function(centerIn){
8599 this.alignTo(centerIn || document, 'c-c');
8604 * Tests various css rules/browsers to determine if this element uses a border box
8607 isBorderBox : function(){
8608 return noBoxAdjust[this.dom.tagName.toLowerCase()] || Roo.isBorderBox;
8612 * Return a box {x, y, width, height} that can be used to set another elements
8613 * size/location to match this element.
8614 * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
8615 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
8616 * @return {Object} box An object in the format {x, y, width, height}
8618 getBox : function(contentBox, local){
8623 var left = parseInt(this.getStyle("left"), 10) || 0;
8624 var top = parseInt(this.getStyle("top"), 10) || 0;
8627 var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
8629 bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
8631 var l = this.getBorderWidth("l")+this.getPadding("l");
8632 var r = this.getBorderWidth("r")+this.getPadding("r");
8633 var t = this.getBorderWidth("t")+this.getPadding("t");
8634 var b = this.getBorderWidth("b")+this.getPadding("b");
8635 bx = {x: xy[0]+l, y: xy[1]+t, 0: xy[0]+l, 1: xy[1]+t, width: w-(l+r), height: h-(t+b)};
8637 bx.right = bx.x + bx.width;
8638 bx.bottom = bx.y + bx.height;
8643 * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
8644 for more information about the sides.
8645 * @param {String} sides
8648 getFrameWidth : function(sides, onlyContentBox){
8649 return onlyContentBox && Roo.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
8653 * Sets the element's box. Use getBox() on another element to get a box obj. If animate is true then width, height, x and y will be animated concurrently.
8654 * @param {Object} box The box to fill {x, y, width, height}
8655 * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
8656 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8657 * @return {Roo.Element} this
8659 setBox : function(box, adjust, animate){
8660 var w = box.width, h = box.height;
8661 if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
8662 w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
8663 h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
8665 this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
8670 * Forces the browser to repaint this element
8671 * @return {Roo.Element} this
8673 repaint : function(){
8675 this.addClass("x-repaint");
8676 setTimeout(function(){
8677 Roo.get(dom).removeClass("x-repaint");
8683 * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
8684 * then it returns the calculated width of the sides (see getPadding)
8685 * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
8686 * @return {Object/Number}
8688 getMargins : function(side){
8691 top: parseInt(this.getStyle("margin-top"), 10) || 0,
8692 left: parseInt(this.getStyle("margin-left"), 10) || 0,
8693 bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
8694 right: parseInt(this.getStyle("margin-right"), 10) || 0
8697 return this.addStyles(side, El.margins);
8702 addStyles : function(sides, styles){
8704 for(var i = 0, len = sides.length; i < len; i++){
8705 v = this.getStyle(styles[sides.charAt(i)]);
8707 w = parseInt(v, 10);
8715 * Creates a proxy element of this element
8716 * @param {String/Object} config The class name of the proxy element or a DomHelper config object
8717 * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
8718 * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
8719 * @return {Roo.Element} The new proxy element
8721 createProxy : function(config, renderTo, matchBox){
8723 renderTo = Roo.getDom(renderTo);
8725 renderTo = document.body;
8727 config = typeof config == "object" ?
8728 config : {tag : "div", cls: config};
8729 var proxy = Roo.DomHelper.append(renderTo, config, true);
8731 proxy.setBox(this.getBox());
8737 * Puts a mask over this element to disable user interaction. Requires core.css.
8738 * This method can only be applied to elements which accept child nodes.
8739 * @param {String} msg (optional) A message to display in the mask
8740 * @param {String} msgCls (optional) A css class to apply to the msg element
8741 * @return {Element} The mask element
8743 mask : function(msg, msgCls){
8744 if(this.getStyle("position") == "static"){
8745 this.setStyle("position", "relative");
8748 this._mask = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask"}, true);
8750 this.addClass("x-masked");
8751 this._mask.setDisplayed(true);
8752 if(typeof msg == 'string'){
8754 this._maskMsg = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask-msg", cn:{tag:'div'}}, true);
8756 var mm = this._maskMsg;
8757 mm.dom.className = msgCls ? "roo-el-mask-msg " + msgCls : "roo-el-mask-msg";
8758 mm.dom.firstChild.innerHTML = msg;
8759 mm.setDisplayed(true);
8762 if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
8763 this._mask.setHeight(this.getHeight());
8769 * Removes a previously applied mask. If removeEl is true the mask overlay is destroyed, otherwise
8770 * it is cached for reuse.
8772 unmask : function(removeEl){
8774 if(removeEl === true){
8775 this._mask.remove();
8778 this._maskMsg.remove();
8779 delete this._maskMsg;
8782 this._mask.setDisplayed(false);
8784 this._maskMsg.setDisplayed(false);
8788 this.removeClass("x-masked");
8792 * Returns true if this element is masked
8795 isMasked : function(){
8796 return this._mask && this._mask.isVisible();
8800 * Creates an iframe shim for this element to keep selects and other windowed objects from
8802 * @return {Roo.Element} The new shim element
8804 createShim : function(){
8805 var el = document.createElement('iframe');
8806 el.frameBorder = 'no';
8807 el.className = 'roo-shim';
8808 if(Roo.isIE && Roo.isSecure){
8809 el.src = Roo.SSL_SECURE_URL;
8811 var shim = Roo.get(this.dom.parentNode.insertBefore(el, this.dom));
8812 shim.autoBoxAdjust = false;
8817 * Removes this element from the DOM and deletes it from the cache
8819 remove : function(){
8820 if(this.dom.parentNode){
8821 this.dom.parentNode.removeChild(this.dom);
8823 delete El.cache[this.dom.id];
8827 * Sets up event handlers to add and remove a css class when the mouse is over this element
8828 * @param {String} className
8829 * @param {Boolean} preventFlicker (optional) If set to true, it prevents flickering by filtering
8830 * mouseout events for children elements
8831 * @return {Roo.Element} this
8833 addClassOnOver : function(className, preventFlicker){
8834 this.on("mouseover", function(){
8835 Roo.fly(this, '_internal').addClass(className);
8837 var removeFn = function(e){
8838 if(preventFlicker !== true || !e.within(this, true)){
8839 Roo.fly(this, '_internal').removeClass(className);
8842 this.on("mouseout", removeFn, this.dom);
8847 * Sets up event handlers to add and remove a css class when this element has the focus
8848 * @param {String} className
8849 * @return {Roo.Element} this
8851 addClassOnFocus : function(className){
8852 this.on("focus", function(){
8853 Roo.fly(this, '_internal').addClass(className);
8855 this.on("blur", function(){
8856 Roo.fly(this, '_internal').removeClass(className);
8861 * Sets up event handlers to add and remove a css class when the mouse is down and then up on this element (a click effect)
8862 * @param {String} className
8863 * @return {Roo.Element} this
8865 addClassOnClick : function(className){
8867 this.on("mousedown", function(){
8868 Roo.fly(dom, '_internal').addClass(className);
8869 var d = Roo.get(document);
8870 var fn = function(){
8871 Roo.fly(dom, '_internal').removeClass(className);
8872 d.removeListener("mouseup", fn);
8874 d.on("mouseup", fn);
8880 * Stops the specified event from bubbling and optionally prevents the default action
8881 * @param {String} eventName
8882 * @param {Boolean} preventDefault (optional) true to prevent the default action too
8883 * @return {Roo.Element} this
8885 swallowEvent : function(eventName, preventDefault){
8886 var fn = function(e){
8887 e.stopPropagation();
8892 if(eventName instanceof Array){
8893 for(var i = 0, len = eventName.length; i < len; i++){
8894 this.on(eventName[i], fn);
8898 this.on(eventName, fn);
8905 fitToParentDelegate : Roo.emptyFn, // keep a reference to the fitToParent delegate
8908 * Sizes this element to its parent element's dimensions performing
8909 * neccessary box adjustments.
8910 * @param {Boolean} monitorResize (optional) If true maintains the fit when the browser window is resized.
8911 * @param {String/HTMLElment/Element} targetParent (optional) The target parent, default to the parentNode.
8912 * @return {Roo.Element} this
8914 fitToParent : function(monitorResize, targetParent) {
8915 Roo.EventManager.removeResizeListener(this.fitToParentDelegate); // always remove previous fitToParent delegate from onWindowResize
8916 this.fitToParentDelegate = Roo.emptyFn; // remove reference to previous delegate
8917 if (monitorResize === true && !this.dom.parentNode) { // check if this Element still exists
8920 var p = Roo.get(targetParent || this.dom.parentNode);
8921 this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb'));
8922 if (monitorResize === true) {
8923 this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]);
8924 Roo.EventManager.onWindowResize(this.fitToParentDelegate);
8930 * Gets the next sibling, skipping text nodes
8931 * @return {HTMLElement} The next sibling or null
8933 getNextSibling : function(){
8934 var n = this.dom.nextSibling;
8935 while(n && n.nodeType != 1){
8942 * Gets the previous sibling, skipping text nodes
8943 * @return {HTMLElement} The previous sibling or null
8945 getPrevSibling : function(){
8946 var n = this.dom.previousSibling;
8947 while(n && n.nodeType != 1){
8948 n = n.previousSibling;
8955 * Appends the passed element(s) to this element
8956 * @param {String/HTMLElement/Array/Element/CompositeElement} el
8957 * @return {Roo.Element} this
8959 appendChild: function(el){
8966 * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
8967 * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
8968 * automatically generated with the specified attributes.
8969 * @param {HTMLElement} insertBefore (optional) a child element of this element
8970 * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
8971 * @return {Roo.Element} The new child element
8973 createChild: function(config, insertBefore, returnDom){
8974 config = config || {tag:'div'};
8976 return Roo.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
8978 return Roo.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true);
8982 * Appends this element to the passed element
8983 * @param {String/HTMLElement/Element} el The new parent element
8984 * @return {Roo.Element} this
8986 appendTo: function(el){
8987 el = Roo.getDom(el);
8988 el.appendChild(this.dom);
8993 * Inserts this element before the passed element in the DOM
8994 * @param {String/HTMLElement/Element} el The element to insert before
8995 * @return {Roo.Element} this
8997 insertBefore: function(el){
8998 el = Roo.getDom(el);
8999 el.parentNode.insertBefore(this.dom, el);
9004 * Inserts this element after the passed element in the DOM
9005 * @param {String/HTMLElement/Element} el The element to insert after
9006 * @return {Roo.Element} this
9008 insertAfter: function(el){
9009 el = Roo.getDom(el);
9010 el.parentNode.insertBefore(this.dom, el.nextSibling);
9015 * Inserts (or creates) an element (or DomHelper config) as the first child of the this element
9016 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
9017 * @return {Roo.Element} The new child
9019 insertFirst: function(el, returnDom){
9021 if(typeof el == 'object' && !el.nodeType){ // dh config
9022 return this.createChild(el, this.dom.firstChild, returnDom);
9024 el = Roo.getDom(el);
9025 this.dom.insertBefore(el, this.dom.firstChild);
9026 return !returnDom ? Roo.get(el) : el;
9031 * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
9032 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
9033 * @param {String} where (optional) 'before' or 'after' defaults to before
9034 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
9035 * @return {Roo.Element} the inserted Element
9037 insertSibling: function(el, where, returnDom){
9038 where = where ? where.toLowerCase() : 'before';
9040 var rt, refNode = where == 'before' ? this.dom : this.dom.nextSibling;
9042 if(typeof el == 'object' && !el.nodeType){ // dh config
9043 if(where == 'after' && !this.dom.nextSibling){
9044 rt = Roo.DomHelper.append(this.dom.parentNode, el, !returnDom);
9046 rt = Roo.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
9050 rt = this.dom.parentNode.insertBefore(Roo.getDom(el),
9051 where == 'before' ? this.dom : this.dom.nextSibling);
9060 * Creates and wraps this element with another element
9061 * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
9062 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
9063 * @return {HTMLElement/Element} The newly created wrapper element
9065 wrap: function(config, returnDom){
9067 config = {tag: "div"};
9069 var newEl = Roo.DomHelper.insertBefore(this.dom, config, !returnDom);
9070 newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
9075 * Replaces the passed element with this element
9076 * @param {String/HTMLElement/Element} el The element to replace
9077 * @return {Roo.Element} this
9079 replace: function(el){
9081 this.insertBefore(el);
9087 * Inserts an html fragment into this element
9088 * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
9089 * @param {String} html The HTML fragment
9090 * @param {Boolean} returnEl True to return an Roo.Element
9091 * @return {HTMLElement/Roo.Element} The inserted node (or nearest related if more than 1 inserted)
9093 insertHtml : function(where, html, returnEl){
9094 var el = Roo.DomHelper.insertHtml(where, this.dom, html);
9095 return returnEl ? Roo.get(el) : el;
9099 * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
9100 * @param {Object} o The object with the attributes
9101 * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
9102 * @return {Roo.Element} this
9104 set : function(o, useSet){
9106 useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
9108 if(attr == "style" || typeof o[attr] == "function") continue;
9110 el.className = o["cls"];
9112 if(useSet) el.setAttribute(attr, o[attr]);
9113 else el[attr] = o[attr];
9117 Roo.DomHelper.applyStyles(el, o.style);
9123 * Convenience method for constructing a KeyMap
9124 * @param {Number/Array/Object/String} key Either a string with the keys to listen for, the numeric key code, array of key codes or an object with the following options:
9125 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
9126 * @param {Function} fn The function to call
9127 * @param {Object} scope (optional) The scope of the function
9128 * @return {Roo.KeyMap} The KeyMap created
9130 addKeyListener : function(key, fn, scope){
9132 if(typeof key != "object" || key instanceof Array){
9148 return new Roo.KeyMap(this, config);
9152 * Creates a KeyMap for this element
9153 * @param {Object} config The KeyMap config. See {@link Roo.KeyMap} for more details
9154 * @return {Roo.KeyMap} The KeyMap created
9156 addKeyMap : function(config){
9157 return new Roo.KeyMap(this, config);
9161 * Returns true if this element is scrollable.
9164 isScrollable : function(){
9166 return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
9170 * Scrolls this element the specified scroll point. It does NOT do bounds checking so if you scroll to a weird value it will try to do it. For auto bounds checking, use scroll().
9171 * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
9172 * @param {Number} value The new scroll value
9173 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9174 * @return {Element} this
9177 scrollTo : function(side, value, animate){
9178 var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
9180 this.dom[prop] = value;
9182 var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
9183 this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
9189 * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
9190 * within this element's scrollable range.
9191 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
9192 * @param {Number} distance How far to scroll the element in pixels
9193 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9194 * @return {Boolean} Returns true if a scroll was triggered or false if the element
9195 * was scrolled as far as it could go.
9197 scroll : function(direction, distance, animate){
9198 if(!this.isScrollable()){
9202 var l = el.scrollLeft, t = el.scrollTop;
9203 var w = el.scrollWidth, h = el.scrollHeight;
9204 var cw = el.clientWidth, ch = el.clientHeight;
9205 direction = direction.toLowerCase();
9206 var scrolled = false;
9207 var a = this.preanim(arguments, 2);
9212 var v = Math.min(l + distance, w-cw);
9213 this.scrollTo("left", v, a);
9220 var v = Math.max(l - distance, 0);
9221 this.scrollTo("left", v, a);
9229 var v = Math.max(t - distance, 0);
9230 this.scrollTo("top", v, a);
9238 var v = Math.min(t + distance, h-ch);
9239 this.scrollTo("top", v, a);
9248 * Translates the passed page coordinates into left/top css values for this element
9249 * @param {Number/Array} x The page x or an array containing [x, y]
9250 * @param {Number} y The page y
9251 * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
9253 translatePoints : function(x, y){
9254 if(typeof x == 'object' || x instanceof Array){
9257 var p = this.getStyle('position');
9258 var o = this.getXY();
9260 var l = parseInt(this.getStyle('left'), 10);
9261 var t = parseInt(this.getStyle('top'), 10);
9264 l = (p == "relative") ? 0 : this.dom.offsetLeft;
9267 t = (p == "relative") ? 0 : this.dom.offsetTop;
9270 return {left: (x - o[0] + l), top: (y - o[1] + t)};
9274 * Returns the current scroll position of the element.
9275 * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
9277 getScroll : function(){
9278 var d = this.dom, doc = document;
9279 if(d == doc || d == doc.body){
9280 var l = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
9281 var t = window.pageYOffset || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
9282 return {left: l, top: t};
9284 return {left: d.scrollLeft, top: d.scrollTop};
9289 * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
9290 * are convert to standard 6 digit hex color.
9291 * @param {String} attr The css attribute
9292 * @param {String} defaultValue The default value to use when a valid color isn't found
9293 * @param {String} prefix (optional) defaults to #. Use an empty string when working with
9296 getColor : function(attr, defaultValue, prefix){
9297 var v = this.getStyle(attr);
9298 if(!v || v == "transparent" || v == "inherit") {
9299 return defaultValue;
9301 var color = typeof prefix == "undefined" ? "#" : prefix;
9302 if(v.substr(0, 4) == "rgb("){
9303 var rvs = v.slice(4, v.length -1).split(",");
9304 for(var i = 0; i < 3; i++){
9305 var h = parseInt(rvs[i]).toString(16);
9312 if(v.substr(0, 1) == "#"){
9314 for(var i = 1; i < 4; i++){
9315 var c = v.charAt(i);
9318 }else if(v.length == 7){
9319 color += v.substr(1);
9323 return(color.length > 5 ? color.toLowerCase() : defaultValue);
9327 * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
9328 * gradient background, rounded corners and a 4-way shadow.
9329 * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
9330 * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
9331 * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
9332 * @return {Roo.Element} this
9334 boxWrap : function(cls){
9335 cls = cls || 'x-box';
9336 var el = Roo.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
9337 el.child('.'+cls+'-mc').dom.appendChild(this.dom);
9342 * Returns the value of a namespaced attribute from the element's underlying DOM node.
9343 * @param {String} namespace The namespace in which to look for the attribute
9344 * @param {String} name The attribute name
9345 * @return {String} The attribute value
9347 getAttributeNS : Roo.isIE ? function(ns, name){
9349 var type = typeof d[ns+":"+name];
9350 if(type != 'undefined' && type != 'unknown'){
9351 return d[ns+":"+name];
9354 } : function(ns, name){
9356 return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
9360 var ep = El.prototype;
9363 * Appends an event handler (Shorthand for addListener)
9364 * @param {String} eventName The type of event to append
9365 * @param {Function} fn The method the event invokes
9366 * @param {Object} scope (optional) The scope (this object) of the fn
9367 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
9370 ep.on = ep.addListener;
9372 ep.mon = ep.addListener;
9375 * Removes an event handler from this element (shorthand for removeListener)
9376 * @param {String} eventName the type of event to remove
9377 * @param {Function} fn the method the event invokes
9378 * @return {Roo.Element} this
9381 ep.un = ep.removeListener;
9384 * true to automatically adjust width and height settings for box-model issues (default to true)
9386 ep.autoBoxAdjust = true;
9389 El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
9392 El.addUnits = function(v, defaultUnit){
9393 if(v === "" || v == "auto"){
9396 if(v === undefined){
9399 if(typeof v == "number" || !El.unitPattern.test(v)){
9400 return v + (defaultUnit || 'px');
9405 // special markup used throughout Roo when box wrapping elements
9406 El.boxMarkup = '<div class="{0}-tl"><div class="{0}-tr"><div class="{0}-tc"></div></div></div><div class="{0}-ml"><div class="{0}-mr"><div class="{0}-mc"></div></div></div><div class="{0}-bl"><div class="{0}-br"><div class="{0}-bc"></div></div></div>';
9408 * Visibility mode constant - Use visibility to hide element
9414 * Visibility mode constant - Use display to hide element
9420 El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
9421 El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
9422 El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
9434 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
9435 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
9436 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
9437 * @return {Element} The Element object
9440 El.get = function(el){
9442 if(!el){ return null; }
9443 if(typeof el == "string"){ // element id
9444 if(!(elm = document.getElementById(el))){
9447 if(ex = El.cache[el]){
9450 ex = El.cache[el] = new El(elm);
9453 }else if(el.tagName){ // dom element
9457 if(ex = El.cache[id]){
9460 ex = El.cache[id] = new El(el);
9463 }else if(el instanceof El){
9465 el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
9466 // catch case where it hasn't been appended
9467 El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
9470 }else if(el.isComposite){
9472 }else if(el instanceof Array){
9473 return El.select(el);
9474 }else if(el == document){
9475 // create a bogus element object representing the document object
9477 var f = function(){};
9478 f.prototype = El.prototype;
9480 docEl.dom = document;
9488 El.uncache = function(el){
9489 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
9491 delete El.cache[a[i].id || a[i]];
9497 // Garbage collection - uncache elements/purge listeners on orphaned elements
9498 // so we don't hold a reference and cause the browser to retain them
9499 El.garbageCollect = function(){
9500 if(!Roo.enableGarbageCollector){
9501 clearInterval(El.collectorThread);
9504 for(var eid in El.cache){
9505 var el = El.cache[eid], d = el.dom;
9506 // -------------------------------------------------------
9507 // Determining what is garbage:
9508 // -------------------------------------------------------
9510 // dom node is null, definitely garbage
9511 // -------------------------------------------------------
9513 // no parentNode == direct orphan, definitely garbage
9514 // -------------------------------------------------------
9515 // !d.offsetParent && !document.getElementById(eid)
9516 // display none elements have no offsetParent so we will
9517 // also try to look it up by it's id. However, check
9518 // offsetParent first so we don't do unneeded lookups.
9519 // This enables collection of elements that are not orphans
9520 // directly, but somewhere up the line they have an orphan
9522 // -------------------------------------------------------
9523 if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
9524 delete El.cache[eid];
9525 if(d && Roo.enableListenerCollection){
9531 El.collectorThreadId = setInterval(El.garbageCollect, 30000);
9535 El.Flyweight = function(dom){
9538 El.Flyweight.prototype = El.prototype;
9540 El._flyweights = {};
9542 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
9543 * the dom node can be overwritten by other code.
9544 * @param {String/HTMLElement} el The dom node or id
9545 * @param {String} named (optional) Allows for creation of named reusable flyweights to
9546 * prevent conflicts (e.g. internally Roo uses "_internal")
9548 * @return {Element} The shared Element object
9550 El.fly = function(el, named){
9551 named = named || '_global';
9552 el = Roo.getDom(el);
9556 if(!El._flyweights[named]){
9557 El._flyweights[named] = new El.Flyweight();
9559 El._flyweights[named].dom = el;
9560 return El._flyweights[named];
9564 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
9565 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
9566 * Shorthand of {@link Roo.Element#get}
9567 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
9568 * @return {Element} The Element object
9574 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
9575 * the dom node can be overwritten by other code.
9576 * Shorthand of {@link Roo.Element#fly}
9577 * @param {String/HTMLElement} el The dom node or id
9578 * @param {String} named (optional) Allows for creation of named reusable flyweights to
9579 * prevent conflicts (e.g. internally Roo uses "_internal")
9581 * @return {Element} The shared Element object
9587 // speedy lookup for elements never to box adjust
9588 var noBoxAdjust = Roo.isStrict ? {
9591 input:1, select:1, textarea:1
9593 if(Roo.isIE || Roo.isGecko){
9594 noBoxAdjust['button'] = 1;
9598 Roo.EventManager.on(window, 'unload', function(){
9600 delete El._flyweights;
9608 Roo.Element.selectorFunction = Roo.DomQuery.select;
9611 Roo.Element.select = function(selector, unique, root){
9613 if(typeof selector == "string"){
9614 els = Roo.Element.selectorFunction(selector, root);
9615 }else if(selector.length !== undefined){
9618 throw "Invalid selector";
9620 if(unique === true){
9621 return new Roo.CompositeElement(els);
9623 return new Roo.CompositeElementLite(els);
9627 * Selects elements based on the passed CSS selector to enable working on them as 1.
9628 * @param {String/Array} selector The CSS selector or an array of elements
9629 * @param {Boolean} unique (optional) true to create a unique Roo.Element for each element (defaults to a shared flyweight object)
9630 * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
9631 * @return {CompositeElementLite/CompositeElement}
9635 Roo.select = Roo.Element.select;
9652 * Ext JS Library 1.1.1
9653 * Copyright(c) 2006-2007, Ext JS, LLC.
9655 * Originally Released Under LGPL - original licence link has changed is not relivant.
9658 * <script type="text/javascript">
9663 //Notifies Element that fx methods are available
9664 Roo.enableFx = true;
9668 * <p>A class to provide basic animation and visual effects support. <b>Note:</b> This class is automatically applied
9669 * to the {@link Roo.Element} interface when included, so all effects calls should be performed via Element.
9670 * Conversely, since the effects are not actually defined in Element, Roo.Fx <b>must</b> be included in order for the
9671 * Element effects to work.</p><br/>
9673 * <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
9674 * they return the Element object itself as the method return value, it is not always possible to mix the two in a single
9675 * method chain. The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
9676 * Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately. For this reason,
9677 * while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
9678 * expected results and should be done with care.</p><br/>
9680 * <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
9681 * that will serve as either the start or end point of the animation. Following are all of the supported anchor positions:</p>
9684 ----- -----------------------------
9685 tl The top left corner
9686 t The center of the top edge
9687 tr The top right corner
9688 l The center of the left edge
9689 r The center of the right edge
9690 bl The bottom left corner
9691 b The center of the bottom edge
9692 br The bottom right corner
9694 * <b>Although some Fx methods accept specific custom config parameters, the ones shown in the Config Options section
9695 * below are common options that can be passed to any Fx method.</b>
9696 * @cfg {Function} callback A function called when the effect is finished
9697 * @cfg {Object} scope The scope of the effect function
9698 * @cfg {String} easing A valid Easing value for the effect
9699 * @cfg {String} afterCls A css class to apply after the effect
9700 * @cfg {Number} duration The length of time (in seconds) that the effect should last
9701 * @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
9702 * @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to
9703 * effects that end with the element being visually hidden, ignored otherwise)
9704 * @cfg {String/Object/Function} afterStyle A style specification string, e.g. "width:100px", or an object in the form {width:"100px"}, or
9705 * a function which returns such a specification that will be applied to the Element after the effect finishes
9706 * @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
9707 * @cfg {Boolean} concurrent Whether to allow subsequently-queued effects to run at the same time as the current effect, or to ensure that they run in sequence
9708 * @cfg {Boolean} stopFx Whether subsequent effects should be stopped and removed after the current effect finishes
9712 * Slides the element into view. An anchor point can be optionally passed to set the point of
9713 * origin for the slide effect. This function automatically handles wrapping the element with
9714 * a fixed-size container if needed. See the Fx class overview for valid anchor point options.
9717 // default: slide the element in from the top
9720 // custom: slide the element in from the right with a 2-second duration
9721 el.slideIn('r', { duration: 2 });
9723 // common config options shown with default values
9729 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
9730 * @param {Object} options (optional) Object literal with any of the Fx config options
9731 * @return {Roo.Element} The Element
9733 slideIn : function(anchor, o){
9734 var el = this.getFxEl();
9737 el.queueFx(o, function(){
9739 anchor = anchor || "t";
9741 // fix display to visibility
9744 // restore values after effect
9745 var r = this.getFxRestore();
9746 var b = this.getBox();
9747 // fixed size for slide
9751 var wrap = this.fxWrap(r.pos, o, "hidden");
9753 var st = this.dom.style;
9754 st.visibility = "visible";
9755 st.position = "absolute";
9757 // clear out temp styles after slide and unwrap
9758 var after = function(){
9759 el.fxUnwrap(wrap, r.pos, o);
9761 st.height = r.height;
9764 // time to calc the positions
9765 var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
9767 switch(anchor.toLowerCase()){
9769 wrap.setSize(b.width, 0);
9770 st.left = st.bottom = "0";
9774 wrap.setSize(0, b.height);
9775 st.right = st.top = "0";
9779 wrap.setSize(0, b.height);
9781 st.left = st.top = "0";
9782 a = {width: bw, points: pt};
9785 wrap.setSize(b.width, 0);
9786 wrap.setY(b.bottom);
9787 st.left = st.top = "0";
9788 a = {height: bh, points: pt};
9792 st.right = st.bottom = "0";
9793 a = {width: bw, height: bh};
9797 wrap.setY(b.y+b.height);
9798 st.right = st.top = "0";
9799 a = {width: bw, height: bh, points: pt};
9803 wrap.setXY([b.right, b.bottom]);
9804 st.left = st.top = "0";
9805 a = {width: bw, height: bh, points: pt};
9809 wrap.setX(b.x+b.width);
9810 st.left = st.bottom = "0";
9811 a = {width: bw, height: bh, points: pt};
9814 this.dom.style.visibility = "visible";
9817 arguments.callee.anim = wrap.fxanim(a,
9827 * Slides the element out of view. An anchor point can be optionally passed to set the end point
9828 * for the slide effect. When the effect is completed, the element will be hidden (visibility =
9829 * 'hidden') but block elements will still take up space in the document. The element must be removed
9830 * from the DOM using the 'remove' config option if desired. This function automatically handles
9831 * wrapping the element with a fixed-size container if needed. See the Fx class overview for valid anchor point options.
9834 // default: slide the element out to the top
9837 // custom: slide the element out to the right with a 2-second duration
9838 el.slideOut('r', { duration: 2 });
9840 // common config options shown with default values
9848 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
9849 * @param {Object} options (optional) Object literal with any of the Fx config options
9850 * @return {Roo.Element} The Element
9852 slideOut : function(anchor, o){
9853 var el = this.getFxEl();
9856 el.queueFx(o, function(){
9858 anchor = anchor || "t";
9860 // restore values after effect
9861 var r = this.getFxRestore();
9863 var b = this.getBox();
9864 // fixed size for slide
9868 var wrap = this.fxWrap(r.pos, o, "visible");
9870 var st = this.dom.style;
9871 st.visibility = "visible";
9872 st.position = "absolute";
9876 var after = function(){
9878 el.setDisplayed(false);
9883 el.fxUnwrap(wrap, r.pos, o);
9886 st.height = r.height;
9891 var a, zero = {to: 0};
9892 switch(anchor.toLowerCase()){
9894 st.left = st.bottom = "0";
9898 st.right = st.top = "0";
9902 st.left = st.top = "0";
9903 a = {width: zero, points: {to:[b.right, b.y]}};
9906 st.left = st.top = "0";
9907 a = {height: zero, points: {to:[b.x, b.bottom]}};
9910 st.right = st.bottom = "0";
9911 a = {width: zero, height: zero};
9914 st.right = st.top = "0";
9915 a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
9918 st.left = st.top = "0";
9919 a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
9922 st.left = st.bottom = "0";
9923 a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
9927 arguments.callee.anim = wrap.fxanim(a,
9937 * Fades the element out while slowly expanding it in all directions. When the effect is completed, the
9938 * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document.
9939 * The element must be removed from the DOM using the 'remove' config option if desired.
9945 // common config options shown with default values
9953 * @param {Object} options (optional) Object literal with any of the Fx config options
9954 * @return {Roo.Element} The Element
9957 var el = this.getFxEl();
9960 el.queueFx(o, function(){
9961 this.clearOpacity();
9964 // restore values after effect
9965 var r = this.getFxRestore();
9966 var st = this.dom.style;
9968 var after = function(){
9970 el.setDisplayed(false);
9977 el.setPositioning(r.pos);
9979 st.height = r.height;
9984 var width = this.getWidth();
9985 var height = this.getHeight();
9987 arguments.callee.anim = this.fxanim({
9988 width : {to: this.adjustWidth(width * 2)},
9989 height : {to: this.adjustHeight(height * 2)},
9990 points : {by: [-(width * .5), -(height * .5)]},
9992 fontSize: {to:200, unit: "%"}
10003 * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
10004 * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
10005 * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
10011 // all config options shown with default values
10019 * @param {Object} options (optional) Object literal with any of the Fx config options
10020 * @return {Roo.Element} The Element
10022 switchOff : function(o){
10023 var el = this.getFxEl();
10026 el.queueFx(o, function(){
10027 this.clearOpacity();
10030 // restore values after effect
10031 var r = this.getFxRestore();
10032 var st = this.dom.style;
10034 var after = function(){
10036 el.setDisplayed(false);
10042 el.setPositioning(r.pos);
10043 st.width = r.width;
10044 st.height = r.height;
10049 this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
10050 this.clearOpacity();
10054 points:{by:[0, this.getHeight() * .5]}
10055 }, o, 'motion', 0.3, 'easeIn', after);
10056 }).defer(100, this);
10063 * Highlights the Element by setting a color (applies to the background-color by default, but can be
10064 * changed using the "attr" config option) and then fading back to the original color. If no original
10065 * color is available, you should provide the "endColor" config option which will be cleared after the animation.
10068 // default: highlight background to yellow
10071 // custom: highlight foreground text to blue for 2 seconds
10072 el.highlight("0000ff", { attr: 'color', duration: 2 });
10074 // common config options shown with default values
10075 el.highlight("ffff9c", {
10076 attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
10077 endColor: (current color) or "ffffff",
10082 * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
10083 * @param {Object} options (optional) Object literal with any of the Fx config options
10084 * @return {Roo.Element} The Element
10086 highlight : function(color, o){
10087 var el = this.getFxEl();
10090 el.queueFx(o, function(){
10091 color = color || "ffff9c";
10092 attr = o.attr || "backgroundColor";
10094 this.clearOpacity();
10097 var origColor = this.getColor(attr);
10098 var restoreColor = this.dom.style[attr];
10099 endColor = (o.endColor || origColor) || "ffffff";
10101 var after = function(){
10102 el.dom.style[attr] = restoreColor;
10107 a[attr] = {from: color, to: endColor};
10108 arguments.callee.anim = this.fxanim(a,
10118 * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
10121 // default: a single light blue ripple
10124 // custom: 3 red ripples lasting 3 seconds total
10125 el.frame("ff0000", 3, { duration: 3 });
10127 // common config options shown with default values
10128 el.frame("C3DAF9", 1, {
10129 duration: 1 //duration of entire animation (not each individual ripple)
10130 // Note: Easing is not configurable and will be ignored if included
10133 * @param {String} color (optional) The color of the border. Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
10134 * @param {Number} count (optional) The number of ripples to display (defaults to 1)
10135 * @param {Object} options (optional) Object literal with any of the Fx config options
10136 * @return {Roo.Element} The Element
10138 frame : function(color, count, o){
10139 var el = this.getFxEl();
10142 el.queueFx(o, function(){
10143 color = color || "#C3DAF9";
10144 if(color.length == 6){
10145 color = "#" + color;
10147 count = count || 1;
10148 duration = o.duration || 1;
10151 var b = this.getBox();
10152 var animFn = function(){
10153 var proxy = this.createProxy({
10156 visbility:"hidden",
10157 position:"absolute",
10158 "z-index":"35000", // yee haw
10159 border:"0px solid " + color
10162 var scale = Roo.isBorderBox ? 2 : 1;
10164 top:{from:b.y, to:b.y - 20},
10165 left:{from:b.x, to:b.x - 20},
10166 borderWidth:{from:0, to:10},
10167 opacity:{from:1, to:0},
10168 height:{from:b.height, to:(b.height + (20*scale))},
10169 width:{from:b.width, to:(b.width + (20*scale))}
10170 }, duration, function(){
10174 animFn.defer((duration/2)*1000, this);
10185 * Creates a pause before any subsequent queued effects begin. If there are
10186 * no effects queued after the pause it will have no effect.
10191 * @param {Number} seconds The length of time to pause (in seconds)
10192 * @return {Roo.Element} The Element
10194 pause : function(seconds){
10195 var el = this.getFxEl();
10198 el.queueFx(o, function(){
10199 setTimeout(function(){
10201 }, seconds * 1000);
10207 * Fade an element in (from transparent to opaque). The ending opacity can be specified
10208 * using the "endOpacity" config option.
10211 // default: fade in from opacity 0 to 100%
10214 // custom: fade in from opacity 0 to 75% over 2 seconds
10215 el.fadeIn({ endOpacity: .75, duration: 2});
10217 // common config options shown with default values
10219 endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
10224 * @param {Object} options (optional) Object literal with any of the Fx config options
10225 * @return {Roo.Element} The Element
10227 fadeIn : function(o){
10228 var el = this.getFxEl();
10230 el.queueFx(o, function(){
10231 this.setOpacity(0);
10233 this.dom.style.visibility = 'visible';
10234 var to = o.endOpacity || 1;
10235 arguments.callee.anim = this.fxanim({opacity:{to:to}},
10236 o, null, .5, "easeOut", function(){
10238 this.clearOpacity();
10247 * Fade an element out (from opaque to transparent). The ending opacity can be specified
10248 * using the "endOpacity" config option.
10251 // default: fade out from the element's current opacity to 0
10254 // custom: fade out from the element's current opacity to 25% over 2 seconds
10255 el.fadeOut({ endOpacity: .25, duration: 2});
10257 // common config options shown with default values
10259 endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
10266 * @param {Object} options (optional) Object literal with any of the Fx config options
10267 * @return {Roo.Element} The Element
10269 fadeOut : function(o){
10270 var el = this.getFxEl();
10272 el.queueFx(o, function(){
10273 arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}},
10274 o, null, .5, "easeOut", function(){
10275 if(this.visibilityMode == Roo.Element.DISPLAY || o.useDisplay){
10276 this.dom.style.display = "none";
10278 this.dom.style.visibility = "hidden";
10280 this.clearOpacity();
10288 * Animates the transition of an element's dimensions from a starting height/width
10289 * to an ending height/width.
10292 // change height and width to 100x100 pixels
10293 el.scale(100, 100);
10295 // common config options shown with default values. The height and width will default to
10296 // the element's existing values if passed as null.
10299 [element's height], {
10304 * @param {Number} width The new width (pass undefined to keep the original width)
10305 * @param {Number} height The new height (pass undefined to keep the original height)
10306 * @param {Object} options (optional) Object literal with any of the Fx config options
10307 * @return {Roo.Element} The Element
10309 scale : function(w, h, o){
10310 this.shift(Roo.apply({}, o, {
10318 * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
10319 * Any of these properties not specified in the config object will not be changed. This effect
10320 * requires that at least one new dimension, position or opacity setting must be passed in on
10321 * the config object in order for the function to have any effect.
10324 // slide the element horizontally to x position 200 while changing the height and opacity
10325 el.shift({ x: 200, height: 50, opacity: .8 });
10327 // common config options shown with default values.
10329 width: [element's width],
10330 height: [element's height],
10331 x: [element's x position],
10332 y: [element's y position],
10333 opacity: [element's opacity],
10338 * @param {Object} options Object literal with any of the Fx config options
10339 * @return {Roo.Element} The Element
10341 shift : function(o){
10342 var el = this.getFxEl();
10344 el.queueFx(o, function(){
10345 var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity;
10346 if(w !== undefined){
10347 a.width = {to: this.adjustWidth(w)};
10349 if(h !== undefined){
10350 a.height = {to: this.adjustHeight(h)};
10352 if(x !== undefined || y !== undefined){
10354 x !== undefined ? x : this.getX(),
10355 y !== undefined ? y : this.getY()
10358 if(op !== undefined){
10359 a.opacity = {to: op};
10361 if(o.xy !== undefined){
10362 a.points = {to: o.xy};
10364 arguments.callee.anim = this.fxanim(a,
10365 o, 'motion', .35, "easeOut", function(){
10373 * Slides the element while fading it out of view. An anchor point can be optionally passed to set the
10374 * ending point of the effect.
10377 // default: slide the element downward while fading out
10380 // custom: slide the element out to the right with a 2-second duration
10381 el.ghost('r', { duration: 2 });
10383 // common config options shown with default values
10391 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
10392 * @param {Object} options (optional) Object literal with any of the Fx config options
10393 * @return {Roo.Element} The Element
10395 ghost : function(anchor, o){
10396 var el = this.getFxEl();
10399 el.queueFx(o, function(){
10400 anchor = anchor || "b";
10402 // restore values after effect
10403 var r = this.getFxRestore();
10404 var w = this.getWidth(),
10405 h = this.getHeight();
10407 var st = this.dom.style;
10409 var after = function(){
10411 el.setDisplayed(false);
10417 el.setPositioning(r.pos);
10418 st.width = r.width;
10419 st.height = r.height;
10424 var a = {opacity: {to: 0}, points: {}}, pt = a.points;
10425 switch(anchor.toLowerCase()){
10452 arguments.callee.anim = this.fxanim(a,
10462 * Ensures that all effects queued after syncFx is called on the element are
10463 * run concurrently. This is the opposite of {@link #sequenceFx}.
10464 * @return {Roo.Element} The Element
10466 syncFx : function(){
10467 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
10476 * Ensures that all effects queued after sequenceFx is called on the element are
10477 * run in sequence. This is the opposite of {@link #syncFx}.
10478 * @return {Roo.Element} The Element
10480 sequenceFx : function(){
10481 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
10483 concurrent : false,
10490 nextFx : function(){
10491 var ef = this.fxQueue[0];
10498 * Returns true if the element has any effects actively running or queued, else returns false.
10499 * @return {Boolean} True if element has active effects, else false
10501 hasActiveFx : function(){
10502 return this.fxQueue && this.fxQueue[0];
10506 * Stops any running effects and clears the element's internal effects queue if it contains
10507 * any additional effects that haven't started yet.
10508 * @return {Roo.Element} The Element
10510 stopFx : function(){
10511 if(this.hasActiveFx()){
10512 var cur = this.fxQueue[0];
10513 if(cur && cur.anim && cur.anim.isAnimated()){
10514 this.fxQueue = [cur]; // clear out others
10515 cur.anim.stop(true);
10522 beforeFx : function(o){
10523 if(this.hasActiveFx() && !o.concurrent){
10534 * Returns true if the element is currently blocking so that no other effect can be queued
10535 * until this effect is finished, else returns false if blocking is not set. This is commonly
10536 * used to ensure that an effect initiated by a user action runs to completion prior to the
10537 * same effect being restarted (e.g., firing only one effect even if the user clicks several times).
10538 * @return {Boolean} True if blocking, else false
10540 hasFxBlock : function(){
10541 var q = this.fxQueue;
10542 return q && q[0] && q[0].block;
10546 queueFx : function(o, fn){
10550 if(!this.hasFxBlock()){
10551 Roo.applyIf(o, this.fxDefaults);
10553 var run = this.beforeFx(o);
10554 fn.block = o.block;
10555 this.fxQueue.push(fn);
10567 fxWrap : function(pos, o, vis){
10569 if(!o.wrap || !(wrap = Roo.get(o.wrap))){
10572 wrapXY = this.getXY();
10574 var div = document.createElement("div");
10575 div.style.visibility = vis;
10576 wrap = Roo.get(this.dom.parentNode.insertBefore(div, this.dom));
10577 wrap.setPositioning(pos);
10578 if(wrap.getStyle("position") == "static"){
10579 wrap.position("relative");
10581 this.clearPositioning('auto');
10583 wrap.dom.appendChild(this.dom);
10585 wrap.setXY(wrapXY);
10592 fxUnwrap : function(wrap, pos, o){
10593 this.clearPositioning();
10594 this.setPositioning(pos);
10596 wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
10602 getFxRestore : function(){
10603 var st = this.dom.style;
10604 return {pos: this.getPositioning(), width: st.width, height : st.height};
10608 afterFx : function(o){
10610 this.applyStyles(o.afterStyle);
10613 this.addClass(o.afterCls);
10615 if(o.remove === true){
10618 Roo.callback(o.callback, o.scope, [this]);
10620 this.fxQueue.shift();
10626 getFxEl : function(){ // support for composite element fx
10627 return Roo.get(this.dom);
10631 fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
10632 animType = animType || 'run';
10634 var anim = Roo.lib.Anim[animType](
10636 (opt.duration || defaultDur) || .35,
10637 (opt.easing || defaultEase) || 'easeOut',
10639 Roo.callback(cb, this);
10648 // backwords compat
10649 Roo.Fx.resize = Roo.Fx.scale;
10651 //When included, Roo.Fx is automatically applied to Element so that all basic
10652 //effects are available directly via the Element API
10653 Roo.apply(Roo.Element.prototype, Roo.Fx);/*
10655 * Ext JS Library 1.1.1
10656 * Copyright(c) 2006-2007, Ext JS, LLC.
10658 * Originally Released Under LGPL - original licence link has changed is not relivant.
10661 * <script type="text/javascript">
10666 * @class Roo.CompositeElement
10667 * Standard composite class. Creates a Roo.Element for every element in the collection.
10669 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
10670 * actions will be performed on all the elements in this collection.</b>
10672 * All methods return <i>this</i> and can be chained.
10674 var els = Roo.select("#some-el div.some-class", true);
10675 // or select directly from an existing element
10676 var el = Roo.get('some-el');
10677 el.select('div.some-class', true);
10679 els.setWidth(100); // all elements become 100 width
10680 els.hide(true); // all elements fade out and hide
10682 els.setWidth(100).hide(true);
10685 Roo.CompositeElement = function(els){
10686 this.elements = [];
10687 this.addElements(els);
10689 Roo.CompositeElement.prototype = {
10691 addElements : function(els){
10692 if(!els) return this;
10693 if(typeof els == "string"){
10694 els = Roo.Element.selectorFunction(els);
10696 var yels = this.elements;
10697 var index = yels.length-1;
10698 for(var i = 0, len = els.length; i < len; i++) {
10699 yels[++index] = Roo.get(els[i]);
10705 * Clears this composite and adds the elements returned by the passed selector.
10706 * @param {String/Array} els A string CSS selector, an array of elements or an element
10707 * @return {CompositeElement} this
10709 fill : function(els){
10710 this.elements = [];
10716 * Filters this composite to only elements that match the passed selector.
10717 * @param {String} selector A string CSS selector
10718 * @return {CompositeElement} this
10720 filter : function(selector){
10722 this.each(function(el){
10723 if(el.is(selector)){
10724 els[els.length] = el.dom;
10731 invoke : function(fn, args){
10732 var els = this.elements;
10733 for(var i = 0, len = els.length; i < len; i++) {
10734 Roo.Element.prototype[fn].apply(els[i], args);
10739 * Adds elements to this composite.
10740 * @param {String/Array} els A string CSS selector, an array of elements or an element
10741 * @return {CompositeElement} this
10743 add : function(els){
10744 if(typeof els == "string"){
10745 this.addElements(Roo.Element.selectorFunction(els));
10746 }else if(els.length !== undefined){
10747 this.addElements(els);
10749 this.addElements([els]);
10754 * Calls the passed function passing (el, this, index) for each element in this composite.
10755 * @param {Function} fn The function to call
10756 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
10757 * @return {CompositeElement} this
10759 each : function(fn, scope){
10760 var els = this.elements;
10761 for(var i = 0, len = els.length; i < len; i++){
10762 if(fn.call(scope || els[i], els[i], this, i) === false) {
10770 * Returns the Element object at the specified index
10771 * @param {Number} index
10772 * @return {Roo.Element}
10774 item : function(index){
10775 return this.elements[index] || null;
10779 * Returns the first Element
10780 * @return {Roo.Element}
10782 first : function(){
10783 return this.item(0);
10787 * Returns the last Element
10788 * @return {Roo.Element}
10791 return this.item(this.elements.length-1);
10795 * Returns the number of elements in this composite
10798 getCount : function(){
10799 return this.elements.length;
10803 * Returns true if this composite contains the passed element
10806 contains : function(el){
10807 return this.indexOf(el) !== -1;
10811 * Returns true if this composite contains the passed element
10814 indexOf : function(el){
10815 return this.elements.indexOf(Roo.get(el));
10820 * Removes the specified element(s).
10821 * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
10822 * or an array of any of those.
10823 * @param {Boolean} removeDom (optional) True to also remove the element from the document
10824 * @return {CompositeElement} this
10826 removeElement : function(el, removeDom){
10827 if(el instanceof Array){
10828 for(var i = 0, len = el.length; i < len; i++){
10829 this.removeElement(el[i]);
10833 var index = typeof el == 'number' ? el : this.indexOf(el);
10836 var d = this.elements[index];
10840 d.parentNode.removeChild(d);
10843 this.elements.splice(index, 1);
10849 * Replaces the specified element with the passed element.
10850 * @param {String/HTMLElement/Element/Number} el The id of an element, the Element itself, the index of the element in this composite
10852 * @param {String/HTMLElement/Element} replacement The id of an element or the Element itself.
10853 * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
10854 * @return {CompositeElement} this
10856 replaceElement : function(el, replacement, domReplace){
10857 var index = typeof el == 'number' ? el : this.indexOf(el);
10860 this.elements[index].replaceWith(replacement);
10862 this.elements.splice(index, 1, Roo.get(replacement))
10869 * Removes all elements.
10871 clear : function(){
10872 this.elements = [];
10876 Roo.CompositeElement.createCall = function(proto, fnName){
10877 if(!proto[fnName]){
10878 proto[fnName] = function(){
10879 return this.invoke(fnName, arguments);
10883 for(var fnName in Roo.Element.prototype){
10884 if(typeof Roo.Element.prototype[fnName] == "function"){
10885 Roo.CompositeElement.createCall(Roo.CompositeElement.prototype, fnName);
10891 * Ext JS Library 1.1.1
10892 * Copyright(c) 2006-2007, Ext JS, LLC.
10894 * Originally Released Under LGPL - original licence link has changed is not relivant.
10897 * <script type="text/javascript">
10901 * @class Roo.CompositeElementLite
10902 * @extends Roo.CompositeElement
10903 * Flyweight composite class. Reuses the same Roo.Element for element operations.
10905 var els = Roo.select("#some-el div.some-class");
10906 // or select directly from an existing element
10907 var el = Roo.get('some-el');
10908 el.select('div.some-class');
10910 els.setWidth(100); // all elements become 100 width
10911 els.hide(true); // all elements fade out and hide
10913 els.setWidth(100).hide(true);
10914 </code></pre><br><br>
10915 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
10916 * actions will be performed on all the elements in this collection.</b>
10918 Roo.CompositeElementLite = function(els){
10919 Roo.CompositeElementLite.superclass.constructor.call(this, els);
10920 this.el = new Roo.Element.Flyweight();
10922 Roo.extend(Roo.CompositeElementLite, Roo.CompositeElement, {
10923 addElements : function(els){
10925 if(els instanceof Array){
10926 this.elements = this.elements.concat(els);
10928 var yels = this.elements;
10929 var index = yels.length-1;
10930 for(var i = 0, len = els.length; i < len; i++) {
10931 yels[++index] = els[i];
10937 invoke : function(fn, args){
10938 var els = this.elements;
10940 for(var i = 0, len = els.length; i < len; i++) {
10942 Roo.Element.prototype[fn].apply(el, args);
10947 * Returns a flyweight Element of the dom element object at the specified index
10948 * @param {Number} index
10949 * @return {Roo.Element}
10951 item : function(index){
10952 if(!this.elements[index]){
10955 this.el.dom = this.elements[index];
10959 // fixes scope with flyweight
10960 addListener : function(eventName, handler, scope, opt){
10961 var els = this.elements;
10962 for(var i = 0, len = els.length; i < len; i++) {
10963 Roo.EventManager.on(els[i], eventName, handler, scope || els[i], opt);
10969 * Calls the passed function passing (el, this, index) for each element in this composite. <b>The element
10970 * passed is the flyweight (shared) Roo.Element instance, so if you require a
10971 * a reference to the dom node, use el.dom.</b>
10972 * @param {Function} fn The function to call
10973 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
10974 * @return {CompositeElement} this
10976 each : function(fn, scope){
10977 var els = this.elements;
10979 for(var i = 0, len = els.length; i < len; i++){
10981 if(fn.call(scope || el, el, this, i) === false){
10988 indexOf : function(el){
10989 return this.elements.indexOf(Roo.getDom(el));
10992 replaceElement : function(el, replacement, domReplace){
10993 var index = typeof el == 'number' ? el : this.indexOf(el);
10995 replacement = Roo.getDom(replacement);
10997 var d = this.elements[index];
10998 d.parentNode.insertBefore(replacement, d);
10999 d.parentNode.removeChild(d);
11001 this.elements.splice(index, 1, replacement);
11006 Roo.CompositeElementLite.prototype.on = Roo.CompositeElementLite.prototype.addListener;
11010 * Ext JS Library 1.1.1
11011 * Copyright(c) 2006-2007, Ext JS, LLC.
11013 * Originally Released Under LGPL - original licence link has changed is not relivant.
11016 * <script type="text/javascript">
11022 * @class Roo.data.Connection
11023 * @extends Roo.util.Observable
11024 * The class encapsulates a connection to the page's originating domain, allowing requests to be made
11025 * either to a configured URL, or to a URL specified at request time.<br><br>
11027 * Requests made by this class are asynchronous, and will return immediately. No data from
11028 * the server will be available to the statement immediately following the {@link #request} call.
11029 * To process returned data, use a callback in the request options object, or an event listener.</p><br>
11031 * Note: If you are doing a file upload, you will not get a normal response object sent back to
11032 * your callback or event handler. Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
11033 * The response object is created using the innerHTML of the IFRAME's document as the responseText
11034 * property and, if present, the IFRAME's XML document as the responseXML property.</p><br>
11035 * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
11036 * that it be placed either inside a <textarea> in an HTML document and retrieved from the responseText
11037 * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
11038 * standard DOM methods.
11040 * @param {Object} config a configuration object.
11042 Roo.data.Connection = function(config){
11043 Roo.apply(this, config);
11046 * @event beforerequest
11047 * Fires before a network request is made to retrieve a data object.
11048 * @param {Connection} conn This Connection object.
11049 * @param {Object} options The options config object passed to the {@link #request} method.
11051 "beforerequest" : true,
11053 * @event requestcomplete
11054 * Fires if the request was successfully completed.
11055 * @param {Connection} conn This Connection object.
11056 * @param {Object} response The XHR object containing the response data.
11057 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
11058 * @param {Object} options The options config object passed to the {@link #request} method.
11060 "requestcomplete" : true,
11062 * @event requestexception
11063 * Fires if an error HTTP status was returned from the server.
11064 * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
11065 * @param {Connection} conn This Connection object.
11066 * @param {Object} response The XHR object containing the response data.
11067 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
11068 * @param {Object} options The options config object passed to the {@link #request} method.
11070 "requestexception" : true
11072 Roo.data.Connection.superclass.constructor.call(this);
11075 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
11077 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
11080 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
11081 * extra parameters to each request made by this object. (defaults to undefined)
11084 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
11085 * to each request made by this object. (defaults to undefined)
11088 * @cfg {String} method (Optional) The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
11091 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
11095 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
11101 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
11104 disableCaching: true,
11107 * Sends an HTTP request to a remote server.
11108 * @param {Object} options An object which may contain the following properties:<ul>
11109 * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
11110 * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
11111 * request, a url encoded string or a function to call to get either.</li>
11112 * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
11113 * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
11114 * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
11115 * The callback is called regardless of success or failure and is passed the following parameters:<ul>
11116 * <li>options {Object} The parameter to the request call.</li>
11117 * <li>success {Boolean} True if the request succeeded.</li>
11118 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11120 * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
11121 * The callback is passed the following parameters:<ul>
11122 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11123 * <li>options {Object} The parameter to the request call.</li>
11125 * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
11126 * The callback is passed the following parameters:<ul>
11127 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11128 * <li>options {Object} The parameter to the request call.</li>
11130 * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
11131 * for the callback function. Defaults to the browser window.</li>
11132 * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
11133 * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
11134 * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
11135 * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
11136 * params for the post data. Any params will be appended to the URL.</li>
11137 * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
11139 * @return {Number} transactionId
11141 request : function(o){
11142 if(this.fireEvent("beforerequest", this, o) !== false){
11145 if(typeof p == "function"){
11146 p = p.call(o.scope||window, o);
11148 if(typeof p == "object"){
11149 p = Roo.urlEncode(o.params);
11151 if(this.extraParams){
11152 var extras = Roo.urlEncode(this.extraParams);
11153 p = p ? (p + '&' + extras) : extras;
11156 var url = o.url || this.url;
11157 if(typeof url == 'function'){
11158 url = url.call(o.scope||window, o);
11162 var form = Roo.getDom(o.form);
11163 url = url || form.action;
11165 var enctype = form.getAttribute("enctype");
11166 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
11167 return this.doFormUpload(o, p, url);
11169 var f = Roo.lib.Ajax.serializeForm(form);
11170 p = p ? (p + '&' + f) : f;
11173 var hs = o.headers;
11174 if(this.defaultHeaders){
11175 hs = Roo.apply(hs || {}, this.defaultHeaders);
11182 success: this.handleResponse,
11183 failure: this.handleFailure,
11185 argument: {options: o},
11186 timeout : this.timeout
11189 var method = o.method||this.method||(p ? "POST" : "GET");
11191 if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
11192 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
11195 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
11199 }else if(this.autoAbort !== false){
11203 if((method == 'GET' && p) || o.xmlData){
11204 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
11207 this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
11208 return this.transId;
11210 Roo.callback(o.callback, o.scope, [o, null, null]);
11216 * Determine whether this object has a request outstanding.
11217 * @param {Number} transactionId (Optional) defaults to the last transaction
11218 * @return {Boolean} True if there is an outstanding request.
11220 isLoading : function(transId){
11222 return Roo.lib.Ajax.isCallInProgress(transId);
11224 return this.transId ? true : false;
11229 * Aborts any outstanding request.
11230 * @param {Number} transactionId (Optional) defaults to the last transaction
11232 abort : function(transId){
11233 if(transId || this.isLoading()){
11234 Roo.lib.Ajax.abort(transId || this.transId);
11239 handleResponse : function(response){
11240 this.transId = false;
11241 var options = response.argument.options;
11242 response.argument = options ? options.argument : null;
11243 this.fireEvent("requestcomplete", this, response, options);
11244 Roo.callback(options.success, options.scope, [response, options]);
11245 Roo.callback(options.callback, options.scope, [options, true, response]);
11249 handleFailure : function(response, e){
11250 this.transId = false;
11251 var options = response.argument.options;
11252 response.argument = options ? options.argument : null;
11253 this.fireEvent("requestexception", this, response, options, e);
11254 Roo.callback(options.failure, options.scope, [response, options]);
11255 Roo.callback(options.callback, options.scope, [options, false, response]);
11259 doFormUpload : function(o, ps, url){
11261 var frame = document.createElement('iframe');
11264 frame.className = 'x-hidden';
11266 frame.src = Roo.SSL_SECURE_URL;
11268 document.body.appendChild(frame);
11271 document.frames[id].name = id;
11274 var form = Roo.getDom(o.form);
11276 form.method = 'POST';
11277 form.enctype = form.encoding = 'multipart/form-data';
11283 if(ps){ // add dynamic params
11285 ps = Roo.urlDecode(ps, false);
11287 if(ps.hasOwnProperty(k)){
11288 hd = document.createElement('input');
11289 hd.type = 'hidden';
11292 form.appendChild(hd);
11299 var r = { // bogus response object
11304 r.argument = o ? o.argument : null;
11309 doc = frame.contentWindow.document;
11311 doc = (frame.contentDocument || window.frames[id].document);
11313 if(doc && doc.body){
11314 r.responseText = doc.body.innerHTML;
11316 if(doc && doc.XMLDocument){
11317 r.responseXML = doc.XMLDocument;
11319 r.responseXML = doc;
11326 Roo.EventManager.removeListener(frame, 'load', cb, this);
11328 this.fireEvent("requestcomplete", this, r, o);
11329 Roo.callback(o.success, o.scope, [r, o]);
11330 Roo.callback(o.callback, o.scope, [o, true, r]);
11332 setTimeout(function(){document.body.removeChild(frame);}, 100);
11335 Roo.EventManager.on(frame, 'load', cb, this);
11338 if(hiddens){ // remove dynamic params
11339 for(var i = 0, len = hiddens.length; i < len; i++){
11340 form.removeChild(hiddens[i]);
11348 * @extends Roo.data.Connection
11349 * Global Ajax request class.
11353 Roo.Ajax = new Roo.data.Connection({
11356 * @cfg {String} url @hide
11359 * @cfg {Object} extraParams @hide
11362 * @cfg {Object} defaultHeaders @hide
11365 * @cfg {String} method (Optional) @hide
11368 * @cfg {Number} timeout (Optional) @hide
11371 * @cfg {Boolean} autoAbort (Optional) @hide
11375 * @cfg {Boolean} disableCaching (Optional) @hide
11379 * @property disableCaching
11380 * True to add a unique cache-buster param to GET requests. (defaults to true)
11385 * The default URL to be used for requests to the server. (defaults to undefined)
11389 * @property extraParams
11390 * An object containing properties which are used as
11391 * extra parameters to each request made by this object. (defaults to undefined)
11395 * @property defaultHeaders
11396 * An object containing request headers which are added to each request made by this object. (defaults to undefined)
11401 * The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
11405 * @property timeout
11406 * The timeout in milliseconds to be used for requests. (defaults to 30000)
11411 * @property autoAbort
11412 * Whether a new request should abort any pending requests. (defaults to false)
11418 * Serialize the passed form into a url encoded string
11419 * @param {String/HTMLElement} form
11422 serializeForm : function(form){
11423 return Roo.lib.Ajax.serializeForm(form);
11427 * Ext JS Library 1.1.1
11428 * Copyright(c) 2006-2007, Ext JS, LLC.
11430 * Originally Released Under LGPL - original licence link has changed is not relivant.
11433 * <script type="text/javascript">
11438 * @extends Roo.data.Connection
11439 * Global Ajax request class.
11441 * @instanceOf Roo.data.Connection
11443 Roo.Ajax = new Roo.data.Connection({
11452 * @cfg {String} url @hide
11455 * @cfg {Object} extraParams @hide
11458 * @cfg {Object} defaultHeaders @hide
11461 * @cfg {String} method (Optional) @hide
11464 * @cfg {Number} timeout (Optional) @hide
11467 * @cfg {Boolean} autoAbort (Optional) @hide
11471 * @cfg {Boolean} disableCaching (Optional) @hide
11475 * @property disableCaching
11476 * True to add a unique cache-buster param to GET requests. (defaults to true)
11481 * The default URL to be used for requests to the server. (defaults to undefined)
11485 * @property extraParams
11486 * An object containing properties which are used as
11487 * extra parameters to each request made by this object. (defaults to undefined)
11491 * @property defaultHeaders
11492 * An object containing request headers which are added to each request made by this object. (defaults to undefined)
11497 * The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
11501 * @property timeout
11502 * The timeout in milliseconds to be used for requests. (defaults to 30000)
11507 * @property autoAbort
11508 * Whether a new request should abort any pending requests. (defaults to false)
11514 * Serialize the passed form into a url encoded string
11515 * @param {String/HTMLElement} form
11518 serializeForm : function(form){
11519 return Roo.lib.Ajax.serializeForm(form);
11523 * Ext JS Library 1.1.1
11524 * Copyright(c) 2006-2007, Ext JS, LLC.
11526 * Originally Released Under LGPL - original licence link has changed is not relivant.
11529 * <script type="text/javascript">
11534 * @class Roo.UpdateManager
11535 * @extends Roo.util.Observable
11536 * Provides AJAX-style update for Element object.<br><br>
11539 * // Get it from a Roo.Element object
11540 * var el = Roo.get("foo");
11541 * var mgr = el.getUpdateManager();
11542 * mgr.update("http://myserver.com/index.php", "param1=1&param2=2");
11544 * mgr.formUpdate("myFormId", "http://myserver.com/index.php");
11546 * // or directly (returns the same UpdateManager instance)
11547 * var mgr = new Roo.UpdateManager("myElementId");
11548 * mgr.startAutoRefresh(60, "http://myserver.com/index.php");
11549 * mgr.on("update", myFcnNeedsToKnow);
11551 // short handed call directly from the element object
11552 Roo.get("foo").load({
11556 text: "Loading Foo..."
11560 * Create new UpdateManager directly.
11561 * @param {String/HTMLElement/Roo.Element} el The element to update
11562 * @param {Boolean} forceNew (optional) By default the constructor checks to see if the passed element already has an UpdateManager and if it does it returns the same instance. This will skip that check (useful for extending this class).
11564 Roo.UpdateManager = function(el, forceNew){
11566 if(!forceNew && el.updateManager){
11567 return el.updateManager;
11570 * The Element object
11571 * @type Roo.Element
11575 * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
11578 this.defaultUrl = null;
11582 * @event beforeupdate
11583 * Fired before an update is made, return false from your handler and the update is cancelled.
11584 * @param {Roo.Element} el
11585 * @param {String/Object/Function} url
11586 * @param {String/Object} params
11588 "beforeupdate": true,
11591 * Fired after successful update is made.
11592 * @param {Roo.Element} el
11593 * @param {Object} oResponseObject The response Object
11598 * Fired on update failure.
11599 * @param {Roo.Element} el
11600 * @param {Object} oResponseObject The response Object
11604 var d = Roo.UpdateManager.defaults;
11606 * Blank page URL to use with SSL file uploads (Defaults to Roo.UpdateManager.defaults.sslBlankUrl or "about:blank").
11609 this.sslBlankUrl = d.sslBlankUrl;
11611 * Whether to append unique parameter on get request to disable caching (Defaults to Roo.UpdateManager.defaults.disableCaching or false).
11614 this.disableCaching = d.disableCaching;
11616 * Text for loading indicator (Defaults to Roo.UpdateManager.defaults.indicatorText or '<div class="loading-indicator">Loading...</div>').
11619 this.indicatorText = d.indicatorText;
11621 * Whether to show indicatorText when loading (Defaults to Roo.UpdateManager.defaults.showLoadIndicator or true).
11624 this.showLoadIndicator = d.showLoadIndicator;
11626 * Timeout for requests or form posts in seconds (Defaults to Roo.UpdateManager.defaults.timeout or 30 seconds).
11629 this.timeout = d.timeout;
11632 * True to process scripts in the output (Defaults to Roo.UpdateManager.defaults.loadScripts (false)).
11635 this.loadScripts = d.loadScripts;
11638 * Transaction object of current executing transaction
11640 this.transaction = null;
11645 this.autoRefreshProcId = null;
11647 * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
11650 this.refreshDelegate = this.refresh.createDelegate(this);
11652 * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
11655 this.updateDelegate = this.update.createDelegate(this);
11657 * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
11660 this.formUpdateDelegate = this.formUpdate.createDelegate(this);
11664 this.successDelegate = this.processSuccess.createDelegate(this);
11668 this.failureDelegate = this.processFailure.createDelegate(this);
11670 if(!this.renderer){
11672 * The renderer for this UpdateManager. Defaults to {@link Roo.UpdateManager.BasicRenderer}.
11674 this.renderer = new Roo.UpdateManager.BasicRenderer();
11677 Roo.UpdateManager.superclass.constructor.call(this);
11680 Roo.extend(Roo.UpdateManager, Roo.util.Observable, {
11682 * Get the Element this UpdateManager is bound to
11683 * @return {Roo.Element} The element
11685 getEl : function(){
11689 * Performs an async request, updating this element with the response. If params are specified it uses POST, otherwise it uses GET.
11690 * @param {Object/String/Function} url The url for this request or a function to call to get the url or a config object containing any of the following options:
11693 url: "your-url.php",<br/>
11694 params: {param1: "foo", param2: "bar"}, // or a URL encoded string<br/>
11695 callback: yourFunction,<br/>
11696 scope: yourObject, //(optional scope) <br/>
11697 discardUrl: false, <br/>
11698 nocache: false,<br/>
11699 text: "Loading...",<br/>
11701 scripts: false<br/>
11704 * The only required property is url. The optional properties nocache, text and scripts
11705 * are shorthand for disableCaching, indicatorText and loadScripts and are used to set their associated property on this UpdateManager instance.
11706 * @param {String/Object} params (optional) The parameters to pass as either a url encoded string "param1=1&param2=2" or an object {param1: 1, param2: 2}
11707 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
11708 * @param {Boolean} discardUrl (optional) By default when you execute an update the defaultUrl is changed to the last used url. If true, it will not store the url.
11710 update : function(url, params, callback, discardUrl){
11711 if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
11712 var method = this.method, cfg;
11713 if(typeof url == "object"){ // must be config object
11716 params = params || cfg.params;
11717 callback = callback || cfg.callback;
11718 discardUrl = discardUrl || cfg.discardUrl;
11719 if(callback && cfg.scope){
11720 callback = callback.createDelegate(cfg.scope);
11722 if(typeof cfg.method != "undefined"){method = cfg.method;};
11723 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
11724 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
11725 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
11726 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
11728 this.showLoading();
11730 this.defaultUrl = url;
11732 if(typeof url == "function"){
11733 url = url.call(this);
11736 method = method || (params ? "POST" : "GET");
11737 if(method == "GET"){
11738 url = this.prepareUrl(url);
11741 var o = Roo.apply(cfg ||{}, {
11744 success: this.successDelegate,
11745 failure: this.failureDelegate,
11746 callback: undefined,
11747 timeout: (this.timeout*1000),
11748 argument: {"url": url, "form": null, "callback": callback, "params": params}
11751 this.transaction = Roo.Ajax.request(o);
11756 * Performs an async form post, updating this element with the response. If the form has the attribute enctype="multipart/form-data", it assumes it's a file upload.
11757 * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.
11758 * @param {String/HTMLElement} form The form Id or form element
11759 * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
11760 * @param {Boolean} reset (optional) Whether to try to reset the form after the update
11761 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
11763 formUpdate : function(form, url, reset, callback){
11764 if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
11765 if(typeof url == "function"){
11766 url = url.call(this);
11768 form = Roo.getDom(form);
11769 this.transaction = Roo.Ajax.request({
11772 success: this.successDelegate,
11773 failure: this.failureDelegate,
11774 timeout: (this.timeout*1000),
11775 argument: {"url": url, "form": form, "callback": callback, "reset": reset}
11777 this.showLoading.defer(1, this);
11782 * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
11783 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
11785 refresh : function(callback){
11786 if(this.defaultUrl == null){
11789 this.update(this.defaultUrl, null, callback, true);
11793 * Set this element to auto refresh.
11794 * @param {Number} interval How often to update (in seconds).
11795 * @param {String/Function} url (optional) The url for this request or a function to call to get the url (Defaults to the last used url)
11796 * @param {String/Object} params (optional) The parameters to pass as either a url encoded string "¶m1=1¶m2=2" or as an object {param1: 1, param2: 2}
11797 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
11798 * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
11800 startAutoRefresh : function(interval, url, params, callback, refreshNow){
11802 this.update(url || this.defaultUrl, params, callback, true);
11804 if(this.autoRefreshProcId){
11805 clearInterval(this.autoRefreshProcId);
11807 this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
11811 * Stop auto refresh on this element.
11813 stopAutoRefresh : function(){
11814 if(this.autoRefreshProcId){
11815 clearInterval(this.autoRefreshProcId);
11816 delete this.autoRefreshProcId;
11820 isAutoRefreshing : function(){
11821 return this.autoRefreshProcId ? true : false;
11824 * Called to update the element to "Loading" state. Override to perform custom action.
11826 showLoading : function(){
11827 if(this.showLoadIndicator){
11828 this.el.update(this.indicatorText);
11833 * Adds unique parameter to query string if disableCaching = true
11836 prepareUrl : function(url){
11837 if(this.disableCaching){
11838 var append = "_dc=" + (new Date().getTime());
11839 if(url.indexOf("?") !== -1){
11840 url += "&" + append;
11842 url += "?" + append;
11851 processSuccess : function(response){
11852 this.transaction = null;
11853 if(response.argument.form && response.argument.reset){
11854 try{ // put in try/catch since some older FF releases had problems with this
11855 response.argument.form.reset();
11858 if(this.loadScripts){
11859 this.renderer.render(this.el, response, this,
11860 this.updateComplete.createDelegate(this, [response]));
11862 this.renderer.render(this.el, response, this);
11863 this.updateComplete(response);
11867 updateComplete : function(response){
11868 this.fireEvent("update", this.el, response);
11869 if(typeof response.argument.callback == "function"){
11870 response.argument.callback(this.el, true, response);
11877 processFailure : function(response){
11878 this.transaction = null;
11879 this.fireEvent("failure", this.el, response);
11880 if(typeof response.argument.callback == "function"){
11881 response.argument.callback(this.el, false, response);
11886 * Set the content renderer for this UpdateManager. See {@link Roo.UpdateManager.BasicRenderer#render} for more details.
11887 * @param {Object} renderer The object implementing the render() method
11889 setRenderer : function(renderer){
11890 this.renderer = renderer;
11893 getRenderer : function(){
11894 return this.renderer;
11898 * Set the defaultUrl used for updates
11899 * @param {String/Function} defaultUrl The url or a function to call to get the url
11901 setDefaultUrl : function(defaultUrl){
11902 this.defaultUrl = defaultUrl;
11906 * Aborts the executing transaction
11908 abort : function(){
11909 if(this.transaction){
11910 Roo.Ajax.abort(this.transaction);
11915 * Returns true if an update is in progress
11916 * @return {Boolean}
11918 isUpdating : function(){
11919 if(this.transaction){
11920 return Roo.Ajax.isLoading(this.transaction);
11927 * @class Roo.UpdateManager.defaults
11928 * @static (not really - but it helps the doc tool)
11929 * The defaults collection enables customizing the default properties of UpdateManager
11931 Roo.UpdateManager.defaults = {
11933 * Timeout for requests or form posts in seconds (Defaults 30 seconds).
11939 * True to process scripts by default (Defaults to false).
11942 loadScripts : false,
11945 * Blank page URL to use with SSL file uploads (Defaults to "javascript:false").
11948 sslBlankUrl : (Roo.SSL_SECURE_URL || "javascript:false"),
11950 * Whether to append unique parameter on get request to disable caching (Defaults to false).
11953 disableCaching : false,
11955 * Whether to show indicatorText when loading (Defaults to true).
11958 showLoadIndicator : true,
11960 * Text for loading indicator (Defaults to '<div class="loading-indicator">Loading...</div>').
11963 indicatorText : '<div class="loading-indicator">Loading...</div>'
11967 * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}).
11969 * <pre><code>Roo.UpdateManager.updateElement("my-div", "stuff.php");</code></pre>
11970 * @param {String/HTMLElement/Roo.Element} el The element to update
11971 * @param {String} url The url
11972 * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
11973 * @param {Object} options (optional) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
11976 * @member Roo.UpdateManager
11978 Roo.UpdateManager.updateElement = function(el, url, params, options){
11979 var um = Roo.get(el, true).getUpdateManager();
11980 Roo.apply(um, options);
11981 um.update(url, params, options ? options.callback : null);
11983 // alias for backwards compat
11984 Roo.UpdateManager.update = Roo.UpdateManager.updateElement;
11986 * @class Roo.UpdateManager.BasicRenderer
11987 * Default Content renderer. Updates the elements innerHTML with the responseText.
11989 Roo.UpdateManager.BasicRenderer = function(){};
11991 Roo.UpdateManager.BasicRenderer.prototype = {
11993 * This is called when the transaction is completed and it's time to update the element - The BasicRenderer
11994 * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),
11995 * create an object with a "render(el, response)" method and pass it to setRenderer on the UpdateManager.
11996 * @param {Roo.Element} el The element being rendered
11997 * @param {Object} response The YUI Connect response object
11998 * @param {UpdateManager} updateManager The calling update manager
11999 * @param {Function} callback A callback that will need to be called if loadScripts is true on the UpdateManager
12001 render : function(el, response, updateManager, callback){
12002 el.update(response.responseText, updateManager.loadScripts, callback);
12007 * Ext JS Library 1.1.1
12008 * Copyright(c) 2006-2007, Ext JS, LLC.
12010 * Originally Released Under LGPL - original licence link has changed is not relivant.
12013 * <script type="text/javascript">
12017 * @class Roo.util.DelayedTask
12018 * Provides a convenient method of performing setTimeout where a new
12019 * timeout cancels the old timeout. An example would be performing validation on a keypress.
12020 * You can use this class to buffer
12021 * the keypress events for a certain number of milliseconds, and perform only if they stop
12022 * for that amount of time.
12023 * @constructor The parameters to this constructor serve as defaults and are not required.
12024 * @param {Function} fn (optional) The default function to timeout
12025 * @param {Object} scope (optional) The default scope of that timeout
12026 * @param {Array} args (optional) The default Array of arguments
12028 Roo.util.DelayedTask = function(fn, scope, args){
12029 var id = null, d, t;
12031 var call = function(){
12032 var now = new Date().getTime();
12036 fn.apply(scope, args || []);
12040 * Cancels any pending timeout and queues a new one
12041 * @param {Number} delay The milliseconds to delay
12042 * @param {Function} newFn (optional) Overrides function passed to constructor
12043 * @param {Object} newScope (optional) Overrides scope passed to constructor
12044 * @param {Array} newArgs (optional) Overrides args passed to constructor
12046 this.delay = function(delay, newFn, newScope, newArgs){
12047 if(id && delay != d){
12051 t = new Date().getTime();
12053 scope = newScope || scope;
12054 args = newArgs || args;
12056 id = setInterval(call, d);
12061 * Cancel the last queued timeout
12063 this.cancel = function(){
12071 * Ext JS Library 1.1.1
12072 * Copyright(c) 2006-2007, Ext JS, LLC.
12074 * Originally Released Under LGPL - original licence link has changed is not relivant.
12077 * <script type="text/javascript">
12081 Roo.util.TaskRunner = function(interval){
12082 interval = interval || 10;
12083 var tasks = [], removeQueue = [];
12085 var running = false;
12087 var stopThread = function(){
12093 var startThread = function(){
12096 id = setInterval(runTasks, interval);
12100 var removeTask = function(task){
12101 removeQueue.push(task);
12107 var runTasks = function(){
12108 if(removeQueue.length > 0){
12109 for(var i = 0, len = removeQueue.length; i < len; i++){
12110 tasks.remove(removeQueue[i]);
12113 if(tasks.length < 1){
12118 var now = new Date().getTime();
12119 for(var i = 0, len = tasks.length; i < len; ++i){
12121 var itime = now - t.taskRunTime;
12122 if(t.interval <= itime){
12123 var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
12124 t.taskRunTime = now;
12125 if(rt === false || t.taskRunCount === t.repeat){
12130 if(t.duration && t.duration <= (now - t.taskStartTime)){
12137 * Queues a new task.
12138 * @param {Object} task
12140 this.start = function(task){
12142 task.taskStartTime = new Date().getTime();
12143 task.taskRunTime = 0;
12144 task.taskRunCount = 0;
12149 this.stop = function(task){
12154 this.stopAll = function(){
12156 for(var i = 0, len = tasks.length; i < len; i++){
12157 if(tasks[i].onStop){
12166 Roo.TaskMgr = new Roo.util.TaskRunner();/*
12168 * Ext JS Library 1.1.1
12169 * Copyright(c) 2006-2007, Ext JS, LLC.
12171 * Originally Released Under LGPL - original licence link has changed is not relivant.
12174 * <script type="text/javascript">
12179 * @class Roo.util.MixedCollection
12180 * @extends Roo.util.Observable
12181 * A Collection class that maintains both numeric indexes and keys and exposes events.
12183 * @param {Boolean} allowFunctions True if the addAll function should add function references to the
12184 * collection (defaults to false)
12185 * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
12186 * and return the key value for that item. This is used when available to look up the key on items that
12187 * were passed without an explicit key parameter to a MixedCollection method. Passing this parameter is
12188 * equivalent to providing an implementation for the {@link #getKey} method.
12190 Roo.util.MixedCollection = function(allowFunctions, keyFn){
12198 * Fires when the collection is cleared.
12203 * Fires when an item is added to the collection.
12204 * @param {Number} index The index at which the item was added.
12205 * @param {Object} o The item added.
12206 * @param {String} key The key associated with the added item.
12211 * Fires when an item is replaced in the collection.
12212 * @param {String} key he key associated with the new added.
12213 * @param {Object} old The item being replaced.
12214 * @param {Object} new The new item.
12219 * Fires when an item is removed from the collection.
12220 * @param {Object} o The item being removed.
12221 * @param {String} key (optional) The key associated with the removed item.
12226 this.allowFunctions = allowFunctions === true;
12228 this.getKey = keyFn;
12230 Roo.util.MixedCollection.superclass.constructor.call(this);
12233 Roo.extend(Roo.util.MixedCollection, Roo.util.Observable, {
12234 allowFunctions : false,
12237 * Adds an item to the collection.
12238 * @param {String} key The key to associate with the item
12239 * @param {Object} o The item to add.
12240 * @return {Object} The item added.
12242 add : function(key, o){
12243 if(arguments.length == 1){
12245 key = this.getKey(o);
12247 if(typeof key == "undefined" || key === null){
12249 this.items.push(o);
12250 this.keys.push(null);
12252 var old = this.map[key];
12254 return this.replace(key, o);
12257 this.items.push(o);
12259 this.keys.push(key);
12261 this.fireEvent("add", this.length-1, o, key);
12266 * MixedCollection has a generic way to fetch keys if you implement getKey.
12269 var mc = new Roo.util.MixedCollection();
12270 mc.add(someEl.dom.id, someEl);
12271 mc.add(otherEl.dom.id, otherEl);
12275 var mc = new Roo.util.MixedCollection();
12276 mc.getKey = function(el){
12282 // or via the constructor
12283 var mc = new Roo.util.MixedCollection(false, function(el){
12289 * @param o {Object} The item for which to find the key.
12290 * @return {Object} The key for the passed item.
12292 getKey : function(o){
12297 * Replaces an item in the collection.
12298 * @param {String} key The key associated with the item to replace, or the item to replace.
12299 * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate with that key.
12300 * @return {Object} The new item.
12302 replace : function(key, o){
12303 if(arguments.length == 1){
12305 key = this.getKey(o);
12307 var old = this.item(key);
12308 if(typeof key == "undefined" || key === null || typeof old == "undefined"){
12309 return this.add(key, o);
12311 var index = this.indexOfKey(key);
12312 this.items[index] = o;
12314 this.fireEvent("replace", key, old, o);
12319 * Adds all elements of an Array or an Object to the collection.
12320 * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
12321 * an Array of values, each of which are added to the collection.
12323 addAll : function(objs){
12324 if(arguments.length > 1 || objs instanceof Array){
12325 var args = arguments.length > 1 ? arguments : objs;
12326 for(var i = 0, len = args.length; i < len; i++){
12330 for(var key in objs){
12331 if(this.allowFunctions || typeof objs[key] != "function"){
12332 this.add(key, objs[key]);
12339 * Executes the specified function once for every item in the collection, passing each
12340 * item as the first and only parameter. returning false from the function will stop the iteration.
12341 * @param {Function} fn The function to execute for each item.
12342 * @param {Object} scope (optional) The scope in which to execute the function.
12344 each : function(fn, scope){
12345 var items = [].concat(this.items); // each safe for removal
12346 for(var i = 0, len = items.length; i < len; i++){
12347 if(fn.call(scope || items[i], items[i], i, len) === false){
12354 * Executes the specified function once for every key in the collection, passing each
12355 * key, and its associated item as the first two parameters.
12356 * @param {Function} fn The function to execute for each item.
12357 * @param {Object} scope (optional) The scope in which to execute the function.
12359 eachKey : function(fn, scope){
12360 for(var i = 0, len = this.keys.length; i < len; i++){
12361 fn.call(scope || window, this.keys[i], this.items[i], i, len);
12366 * Returns the first item in the collection which elicits a true return value from the
12367 * passed selection function.
12368 * @param {Function} fn The selection function to execute for each item.
12369 * @param {Object} scope (optional) The scope in which to execute the function.
12370 * @return {Object} The first item in the collection which returned true from the selection function.
12372 find : function(fn, scope){
12373 for(var i = 0, len = this.items.length; i < len; i++){
12374 if(fn.call(scope || window, this.items[i], this.keys[i])){
12375 return this.items[i];
12382 * Inserts an item at the specified index in the collection.
12383 * @param {Number} index The index to insert the item at.
12384 * @param {String} key The key to associate with the new item, or the item itself.
12385 * @param {Object} o (optional) If the second parameter was a key, the new item.
12386 * @return {Object} The item inserted.
12388 insert : function(index, key, o){
12389 if(arguments.length == 2){
12391 key = this.getKey(o);
12393 if(index >= this.length){
12394 return this.add(key, o);
12397 this.items.splice(index, 0, o);
12398 if(typeof key != "undefined" && key != null){
12401 this.keys.splice(index, 0, key);
12402 this.fireEvent("add", index, o, key);
12407 * Removed an item from the collection.
12408 * @param {Object} o The item to remove.
12409 * @return {Object} The item removed.
12411 remove : function(o){
12412 return this.removeAt(this.indexOf(o));
12416 * Remove an item from a specified index in the collection.
12417 * @param {Number} index The index within the collection of the item to remove.
12419 removeAt : function(index){
12420 if(index < this.length && index >= 0){
12422 var o = this.items[index];
12423 this.items.splice(index, 1);
12424 var key = this.keys[index];
12425 if(typeof key != "undefined"){
12426 delete this.map[key];
12428 this.keys.splice(index, 1);
12429 this.fireEvent("remove", o, key);
12434 * Removed an item associated with the passed key fom the collection.
12435 * @param {String} key The key of the item to remove.
12437 removeKey : function(key){
12438 return this.removeAt(this.indexOfKey(key));
12442 * Returns the number of items in the collection.
12443 * @return {Number} the number of items in the collection.
12445 getCount : function(){
12446 return this.length;
12450 * Returns index within the collection of the passed Object.
12451 * @param {Object} o The item to find the index of.
12452 * @return {Number} index of the item.
12454 indexOf : function(o){
12455 if(!this.items.indexOf){
12456 for(var i = 0, len = this.items.length; i < len; i++){
12457 if(this.items[i] == o) return i;
12461 return this.items.indexOf(o);
12466 * Returns index within the collection of the passed key.
12467 * @param {String} key The key to find the index of.
12468 * @return {Number} index of the key.
12470 indexOfKey : function(key){
12471 if(!this.keys.indexOf){
12472 for(var i = 0, len = this.keys.length; i < len; i++){
12473 if(this.keys[i] == key) return i;
12477 return this.keys.indexOf(key);
12482 * Returns the item associated with the passed key OR index. Key has priority over index.
12483 * @param {String/Number} key The key or index of the item.
12484 * @return {Object} The item associated with the passed key.
12486 item : function(key){
12487 var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
12488 return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
12492 * Returns the item at the specified index.
12493 * @param {Number} index The index of the item.
12496 itemAt : function(index){
12497 return this.items[index];
12501 * Returns the item associated with the passed key.
12502 * @param {String/Number} key The key of the item.
12503 * @return {Object} The item associated with the passed key.
12505 key : function(key){
12506 return this.map[key];
12510 * Returns true if the collection contains the passed Object as an item.
12511 * @param {Object} o The Object to look for in the collection.
12512 * @return {Boolean} True if the collection contains the Object as an item.
12514 contains : function(o){
12515 return this.indexOf(o) != -1;
12519 * Returns true if the collection contains the passed Object as a key.
12520 * @param {String} key The key to look for in the collection.
12521 * @return {Boolean} True if the collection contains the Object as a key.
12523 containsKey : function(key){
12524 return typeof this.map[key] != "undefined";
12528 * Removes all items from the collection.
12530 clear : function(){
12535 this.fireEvent("clear");
12539 * Returns the first item in the collection.
12540 * @return {Object} the first item in the collection..
12542 first : function(){
12543 return this.items[0];
12547 * Returns the last item in the collection.
12548 * @return {Object} the last item in the collection..
12551 return this.items[this.length-1];
12554 _sort : function(property, dir, fn){
12555 var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
12556 fn = fn || function(a, b){
12559 var c = [], k = this.keys, items = this.items;
12560 for(var i = 0, len = items.length; i < len; i++){
12561 c[c.length] = {key: k[i], value: items[i], index: i};
12563 c.sort(function(a, b){
12564 var v = fn(a[property], b[property]) * dsc;
12566 v = (a.index < b.index ? -1 : 1);
12570 for(var i = 0, len = c.length; i < len; i++){
12571 items[i] = c[i].value;
12574 this.fireEvent("sort", this);
12578 * Sorts this collection with the passed comparison function
12579 * @param {String} direction (optional) "ASC" or "DESC"
12580 * @param {Function} fn (optional) comparison function
12582 sort : function(dir, fn){
12583 this._sort("value", dir, fn);
12587 * Sorts this collection by keys
12588 * @param {String} direction (optional) "ASC" or "DESC"
12589 * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
12591 keySort : function(dir, fn){
12592 this._sort("key", dir, fn || function(a, b){
12593 return String(a).toUpperCase()-String(b).toUpperCase();
12598 * Returns a range of items in this collection
12599 * @param {Number} startIndex (optional) defaults to 0
12600 * @param {Number} endIndex (optional) default to the last item
12601 * @return {Array} An array of items
12603 getRange : function(start, end){
12604 var items = this.items;
12605 if(items.length < 1){
12608 start = start || 0;
12609 end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
12612 for(var i = start; i <= end; i++) {
12613 r[r.length] = items[i];
12616 for(var i = start; i >= end; i--) {
12617 r[r.length] = items[i];
12624 * Filter the <i>objects</i> in this collection by a specific property.
12625 * Returns a new collection that has been filtered.
12626 * @param {String} property A property on your objects
12627 * @param {String/RegExp} value Either string that the property values
12628 * should start with or a RegExp to test against the property
12629 * @return {MixedCollection} The new filtered collection
12631 filter : function(property, value){
12632 if(!value.exec){ // not a regex
12633 value = String(value);
12634 if(value.length == 0){
12635 return this.clone();
12637 value = new RegExp("^" + Roo.escapeRe(value), "i");
12639 return this.filterBy(function(o){
12640 return o && value.test(o[property]);
12645 * Filter by a function. * Returns a new collection that has been filtered.
12646 * The passed function will be called with each
12647 * object in the collection. If the function returns true, the value is included
12648 * otherwise it is filtered.
12649 * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
12650 * @param {Object} scope (optional) The scope of the function (defaults to this)
12651 * @return {MixedCollection} The new filtered collection
12653 filterBy : function(fn, scope){
12654 var r = new Roo.util.MixedCollection();
12655 r.getKey = this.getKey;
12656 var k = this.keys, it = this.items;
12657 for(var i = 0, len = it.length; i < len; i++){
12658 if(fn.call(scope||this, it[i], k[i])){
12659 r.add(k[i], it[i]);
12666 * Creates a duplicate of this collection
12667 * @return {MixedCollection}
12669 clone : function(){
12670 var r = new Roo.util.MixedCollection();
12671 var k = this.keys, it = this.items;
12672 for(var i = 0, len = it.length; i < len; i++){
12673 r.add(k[i], it[i]);
12675 r.getKey = this.getKey;
12680 * Returns the item associated with the passed key or index.
12682 * @param {String/Number} key The key or index of the item.
12683 * @return {Object} The item associated with the passed key.
12685 Roo.util.MixedCollection.prototype.get = Roo.util.MixedCollection.prototype.item;/*
12687 * Ext JS Library 1.1.1
12688 * Copyright(c) 2006-2007, Ext JS, LLC.
12690 * Originally Released Under LGPL - original licence link has changed is not relivant.
12693 * <script type="text/javascript">
12696 * @class Roo.util.JSON
12697 * Modified version of Douglas Crockford"s json.js that doesn"t
12698 * mess with the Object prototype
12699 * http://www.json.org/js.html
12702 Roo.util.JSON = new (function(){
12703 var useHasOwn = {}.hasOwnProperty ? true : false;
12705 // crashes Safari in some instances
12706 //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
12708 var pad = function(n) {
12709 return n < 10 ? "0" + n : n;
12722 var encodeString = function(s){
12723 if (/["\\\x00-\x1f]/.test(s)) {
12724 return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
12729 c = b.charCodeAt();
12731 Math.floor(c / 16).toString(16) +
12732 (c % 16).toString(16);
12735 return '"' + s + '"';
12738 var encodeArray = function(o){
12739 var a = ["["], b, i, l = o.length, v;
12740 for (i = 0; i < l; i += 1) {
12742 switch (typeof v) {
12751 a.push(v === null ? "null" : Roo.util.JSON.encode(v));
12759 var encodeDate = function(o){
12760 return '"' + o.getFullYear() + "-" +
12761 pad(o.getMonth() + 1) + "-" +
12762 pad(o.getDate()) + "T" +
12763 pad(o.getHours()) + ":" +
12764 pad(o.getMinutes()) + ":" +
12765 pad(o.getSeconds()) + '"';
12769 * Encodes an Object, Array or other value
12770 * @param {Mixed} o The variable to encode
12771 * @return {String} The JSON string
12773 this.encode = function(o){
12774 if(typeof o == "undefined" || o === null){
12776 }else if(o instanceof Array){
12777 return encodeArray(o);
12778 }else if(o instanceof Date){
12779 return encodeDate(o);
12780 }else if(typeof o == "string"){
12781 return encodeString(o);
12782 }else if(typeof o == "number"){
12783 return isFinite(o) ? String(o) : "null";
12784 }else if(typeof o == "boolean"){
12787 var a = ["{"], b, i, v;
12789 if(!useHasOwn || o.hasOwnProperty(i)) {
12791 switch (typeof v) {
12800 a.push(this.encode(i), ":",
12801 v === null ? "null" : this.encode(v));
12812 * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
12813 * @param {String} json The JSON string
12814 * @return {Object} The resulting object
12816 this.decode = function(json){
12820 return eval("(" + json + ')');
12824 * Shorthand for {@link Roo.util.JSON#encode}
12825 * @member Roo encode
12827 Roo.encode = Roo.util.JSON.encode;
12829 * Shorthand for {@link Roo.util.JSON#decode}
12830 * @member Roo decode
12832 Roo.decode = Roo.util.JSON.decode;
12835 * Ext JS Library 1.1.1
12836 * Copyright(c) 2006-2007, Ext JS, LLC.
12838 * Originally Released Under LGPL - original licence link has changed is not relivant.
12841 * <script type="text/javascript">
12845 * @class Roo.util.Format
12846 * Reusable data formatting functions
12849 Roo.util.Format = function(){
12850 var trimRe = /^\s+|\s+$/g;
12853 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
12854 * @param {String} value The string to truncate
12855 * @param {Number} length The maximum length to allow before truncating
12856 * @return {String} The converted text
12858 ellipsis : function(value, len){
12859 if(value && value.length > len){
12860 return value.substr(0, len-3)+"...";
12866 * Checks a reference and converts it to empty string if it is undefined
12867 * @param {Mixed} value Reference to check
12868 * @return {Mixed} Empty string if converted, otherwise the original value
12870 undef : function(value){
12871 return typeof value != "undefined" ? value : "";
12875 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
12876 * @param {String} value The string to encode
12877 * @return {String} The encoded text
12879 htmlEncode : function(value){
12880 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
12884 * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
12885 * @param {String} value The string to decode
12886 * @return {String} The decoded text
12888 htmlDecode : function(value){
12889 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');
12893 * Trims any whitespace from either side of a string
12894 * @param {String} value The text to trim
12895 * @return {String} The trimmed text
12897 trim : function(value){
12898 return String(value).replace(trimRe, "");
12902 * Returns a substring from within an original string
12903 * @param {String} value The original text
12904 * @param {Number} start The start index of the substring
12905 * @param {Number} length The length of the substring
12906 * @return {String} The substring
12908 substr : function(value, start, length){
12909 return String(value).substr(start, length);
12913 * Converts a string to all lower case letters
12914 * @param {String} value The text to convert
12915 * @return {String} The converted text
12917 lowercase : function(value){
12918 return String(value).toLowerCase();
12922 * Converts a string to all upper case letters
12923 * @param {String} value The text to convert
12924 * @return {String} The converted text
12926 uppercase : function(value){
12927 return String(value).toUpperCase();
12931 * Converts the first character only of a string to upper case
12932 * @param {String} value The text to convert
12933 * @return {String} The converted text
12935 capitalize : function(value){
12936 return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
12940 call : function(value, fn){
12941 if(arguments.length > 2){
12942 var args = Array.prototype.slice.call(arguments, 2);
12943 args.unshift(value);
12945 return /** eval:var:value */ eval(fn).apply(window, args);
12947 /** eval:var:value */
12948 return /** eval:var:value */ eval(fn).call(window, value);
12953 * Format a number as US currency
12954 * @param {Number/String} value The numeric value to format
12955 * @return {String} The formatted currency string
12957 usMoney : function(v){
12958 v = (Math.round((v-0)*100))/100;
12959 v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
12961 var ps = v.split('.');
12963 var sub = ps[1] ? '.'+ ps[1] : '.00';
12964 var r = /(\d+)(\d{3})/;
12965 while (r.test(whole)) {
12966 whole = whole.replace(r, '$1' + ',' + '$2');
12968 return "$" + whole + sub ;
12972 * Parse a value into a formatted date using the specified format pattern.
12973 * @param {Mixed} value The value to format
12974 * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
12975 * @return {String} The formatted date string
12977 date : function(v, format){
12981 if(!(v instanceof Date)){
12982 v = new Date(Date.parse(v));
12984 return v.dateFormat(format || "m/d/Y");
12988 * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
12989 * @param {String} format Any valid date format string
12990 * @return {Function} The date formatting function
12992 dateRenderer : function(format){
12993 return function(v){
12994 return Roo.util.Format.date(v, format);
12999 stripTagsRE : /<\/?[^>]+>/gi,
13002 * Strips all HTML tags
13003 * @param {Mixed} value The text from which to strip tags
13004 * @return {String} The stripped text
13006 stripTags : function(v){
13007 return !v ? v : String(v).replace(this.stripTagsRE, "");
13012 * Ext JS Library 1.1.1
13013 * Copyright(c) 2006-2007, Ext JS, LLC.
13015 * Originally Released Under LGPL - original licence link has changed is not relivant.
13018 * <script type="text/javascript">
13025 * @class Roo.MasterTemplate
13026 * @extends Roo.Template
13027 * Provides a template that can have child templates. The syntax is:
13029 var t = new Roo.MasterTemplate(
13030 '<select name="{name}">',
13031 '<tpl name="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
13034 t.add('options', {value: 'foo', text: 'bar'});
13035 // or you can add multiple child elements in one shot
13036 t.addAll('options', [
13037 {value: 'foo', text: 'bar'},
13038 {value: 'foo2', text: 'bar2'},
13039 {value: 'foo3', text: 'bar3'}
13041 // then append, applying the master template values
13042 t.append('my-form', {name: 'my-select'});
13044 * A name attribute for the child template is not required if you have only one child
13045 * template or you want to refer to them by index.
13047 Roo.MasterTemplate = function(){
13048 Roo.MasterTemplate.superclass.constructor.apply(this, arguments);
13049 this.originalHtml = this.html;
13051 var m, re = this.subTemplateRe;
13054 while(m = re.exec(this.html)){
13055 var name = m[1], content = m[2];
13060 tpl : new Roo.Template(content)
13063 st[name] = st[subIndex];
13065 st[subIndex].tpl.compile();
13066 st[subIndex].tpl.call = this.call.createDelegate(this);
13069 this.subCount = subIndex;
13072 Roo.extend(Roo.MasterTemplate, Roo.Template, {
13074 * The regular expression used to match sub templates
13078 subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi,
13081 * Applies the passed values to a child template.
13082 * @param {String/Number} name (optional) The name or index of the child template
13083 * @param {Array/Object} values The values to be applied to the template
13084 * @return {MasterTemplate} this
13086 add : function(name, values){
13087 if(arguments.length == 1){
13088 values = arguments[0];
13091 var s = this.subs[name];
13092 s.buffer[s.buffer.length] = s.tpl.apply(values);
13097 * Applies all the passed values to a child template.
13098 * @param {String/Number} name (optional) The name or index of the child template
13099 * @param {Array} values The values to be applied to the template, this should be an array of objects.
13100 * @param {Boolean} reset (optional) True to reset the template first
13101 * @return {MasterTemplate} this
13103 fill : function(name, values, reset){
13105 if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){
13113 for(var i = 0, len = values.length; i < len; i++){
13114 this.add(name, values[i]);
13120 * Resets the template for reuse
13121 * @return {MasterTemplate} this
13123 reset : function(){
13125 for(var i = 0; i < this.subCount; i++){
13131 applyTemplate : function(values){
13133 var replaceIndex = -1;
13134 this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){
13135 return s[++replaceIndex].buffer.join("");
13137 return Roo.MasterTemplate.superclass.applyTemplate.call(this, values);
13140 apply : function(){
13141 return this.applyTemplate.apply(this, arguments);
13144 compile : function(){return this;}
13148 * Alias for fill().
13151 Roo.MasterTemplate.prototype.addAll = Roo.MasterTemplate.prototype.fill;
13153 * Creates a template from the passed element's value (display:none textarea, preferred) or innerHTML. e.g.
13154 * var tpl = Roo.MasterTemplate.from('element-id');
13155 * @param {String/HTMLElement} el
13156 * @param {Object} config
13159 Roo.MasterTemplate.from = function(el, config){
13160 el = Roo.getDom(el);
13161 return new Roo.MasterTemplate(el.value || el.innerHTML, config || '');
13164 * Ext JS Library 1.1.1
13165 * Copyright(c) 2006-2007, Ext JS, LLC.
13167 * Originally Released Under LGPL - original licence link has changed is not relivant.
13170 * <script type="text/javascript">
13175 * @class Roo.util.CSS
13176 * Utility class for manipulating CSS rules
13179 Roo.util.CSS = function(){
13181 var doc = document;
13183 var camelRe = /(-[a-z])/gi;
13184 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
13188 * Very simple dynamic creation of stylesheets from a text blob of rules. The text will wrapped in a style
13189 * tag and appended to the HEAD of the document.
13190 * @param {String|Object} cssText The text containing the css rules
13191 * @param {String} id An id to add to the stylesheet for later removal
13192 * @return {StyleSheet}
13194 createStyleSheet : function(cssText, id){
13196 var head = doc.getElementsByTagName("head")[0];
13197 var nrules = doc.createElement("style");
13198 nrules.setAttribute("type", "text/css");
13200 nrules.setAttribute("id", id);
13202 if (typeof(cssText) != 'string') {
13203 // support object maps..
13204 // not sure if this a good idea..
13205 // perhaps it should be merged with the general css handling
13206 // and handle js style props.
13207 var cssTextNew = [];
13208 for(var n in cssText) {
13210 for(var k in cssText[n]) {
13211 citems.push( k + ' : ' +cssText[n][k] + ';' );
13213 cssTextNew.push( n + ' { ' + citems.join(' ') + '} ');
13216 cssText = cssTextNew.join("\n");
13222 head.appendChild(nrules);
13223 ss = nrules.styleSheet;
13224 ss.cssText = cssText;
13227 nrules.appendChild(doc.createTextNode(cssText));
13229 nrules.cssText = cssText;
13231 head.appendChild(nrules);
13232 ss = nrules.styleSheet ? nrules.styleSheet : (nrules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
13234 this.cacheStyleSheet(ss);
13239 * Removes a style or link tag by id
13240 * @param {String} id The id of the tag
13242 removeStyleSheet : function(id){
13243 var existing = doc.getElementById(id);
13245 existing.parentNode.removeChild(existing);
13250 * Dynamically swaps an existing stylesheet reference for a new one
13251 * @param {String} id The id of an existing link tag to remove
13252 * @param {String} url The href of the new stylesheet to include
13254 swapStyleSheet : function(id, url){
13255 this.removeStyleSheet(id);
13256 var ss = doc.createElement("link");
13257 ss.setAttribute("rel", "stylesheet");
13258 ss.setAttribute("type", "text/css");
13259 ss.setAttribute("id", id);
13260 ss.setAttribute("href", url);
13261 doc.getElementsByTagName("head")[0].appendChild(ss);
13265 * Refresh the rule cache if you have dynamically added stylesheets
13266 * @return {Object} An object (hash) of rules indexed by selector
13268 refreshCache : function(){
13269 return this.getRules(true);
13273 cacheStyleSheet : function(stylesheet){
13277 try{// try catch for cross domain access issue
13278 var ssRules = stylesheet.cssRules || stylesheet.rules;
13279 for(var j = ssRules.length-1; j >= 0; --j){
13280 rules[ssRules[j].selectorText] = ssRules[j];
13286 * Gets all css rules for the document
13287 * @param {Boolean} refreshCache true to refresh the internal cache
13288 * @return {Object} An object (hash) of rules indexed by selector
13290 getRules : function(refreshCache){
13291 if(rules == null || refreshCache){
13293 var ds = doc.styleSheets;
13294 for(var i =0, len = ds.length; i < len; i++){
13296 this.cacheStyleSheet(ds[i]);
13304 * Gets an an individual CSS rule by selector(s)
13305 * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
13306 * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
13307 * @return {CSSRule} The CSS rule or null if one is not found
13309 getRule : function(selector, refreshCache){
13310 var rs = this.getRules(refreshCache);
13311 if(!(selector instanceof Array)){
13312 return rs[selector];
13314 for(var i = 0; i < selector.length; i++){
13315 if(rs[selector[i]]){
13316 return rs[selector[i]];
13324 * Updates a rule property
13325 * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
13326 * @param {String} property The css property
13327 * @param {String} value The new value for the property
13328 * @return {Boolean} true If a rule was found and updated
13330 updateRule : function(selector, property, value){
13331 if(!(selector instanceof Array)){
13332 var rule = this.getRule(selector);
13334 rule.style[property.replace(camelRe, camelFn)] = value;
13338 for(var i = 0; i < selector.length; i++){
13339 if(this.updateRule(selector[i], property, value)){
13349 * Ext JS Library 1.1.1
13350 * Copyright(c) 2006-2007, Ext JS, LLC.
13352 * Originally Released Under LGPL - original licence link has changed is not relivant.
13355 * <script type="text/javascript">
13361 * @class Roo.util.ClickRepeater
13362 * @extends Roo.util.Observable
13364 * A wrapper class which can be applied to any element. Fires a "click" event while the
13365 * mouse is pressed. The interval between firings may be specified in the config but
13366 * defaults to 10 milliseconds.
13368 * Optionally, a CSS class may be applied to the element during the time it is pressed.
13370 * @cfg {String/HTMLElement/Element} el The element to act as a button.
13371 * @cfg {Number} delay The initial delay before the repeating event begins firing.
13372 * Similar to an autorepeat key delay.
13373 * @cfg {Number} interval The interval between firings of the "click" event. Default 10 ms.
13374 * @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
13375 * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
13376 * "interval" and "delay" are ignored. "immediate" is honored.
13377 * @cfg {Boolean} preventDefault True to prevent the default click event
13378 * @cfg {Boolean} stopDefault True to stop the default click event
13381 * 2007-02-02 jvs Original code contributed by Nige "Animal" White
13382 * 2007-02-02 jvs Renamed to ClickRepeater
13383 * 2007-02-03 jvs Modifications for FF Mac and Safari
13386 * @param {String/HTMLElement/Element} el The element to listen on
13387 * @param {Object} config
13389 Roo.util.ClickRepeater = function(el, config)
13391 this.el = Roo.get(el);
13392 this.el.unselectable();
13394 Roo.apply(this, config);
13399 * Fires when the mouse button is depressed.
13400 * @param {Roo.util.ClickRepeater} this
13402 "mousedown" : true,
13405 * Fires on a specified interval during the time the element is pressed.
13406 * @param {Roo.util.ClickRepeater} this
13411 * Fires when the mouse key is released.
13412 * @param {Roo.util.ClickRepeater} this
13417 this.el.on("mousedown", this.handleMouseDown, this);
13418 if(this.preventDefault || this.stopDefault){
13419 this.el.on("click", function(e){
13420 if(this.preventDefault){
13421 e.preventDefault();
13423 if(this.stopDefault){
13429 // allow inline handler
13431 this.on("click", this.handler, this.scope || this);
13434 Roo.util.ClickRepeater.superclass.constructor.call(this);
13437 Roo.extend(Roo.util.ClickRepeater, Roo.util.Observable, {
13440 preventDefault : true,
13441 stopDefault : false,
13445 handleMouseDown : function(){
13446 clearTimeout(this.timer);
13448 if(this.pressClass){
13449 this.el.addClass(this.pressClass);
13451 this.mousedownTime = new Date();
13453 Roo.get(document).on("mouseup", this.handleMouseUp, this);
13454 this.el.on("mouseout", this.handleMouseOut, this);
13456 this.fireEvent("mousedown", this);
13457 this.fireEvent("click", this);
13459 this.timer = this.click.defer(this.delay || this.interval, this);
13463 click : function(){
13464 this.fireEvent("click", this);
13465 this.timer = this.click.defer(this.getInterval(), this);
13469 getInterval: function(){
13470 if(!this.accelerate){
13471 return this.interval;
13473 var pressTime = this.mousedownTime.getElapsed();
13474 if(pressTime < 500){
13476 }else if(pressTime < 1700){
13478 }else if(pressTime < 2600){
13480 }else if(pressTime < 3500){
13482 }else if(pressTime < 4400){
13484 }else if(pressTime < 5300){
13486 }else if(pressTime < 6200){
13494 handleMouseOut : function(){
13495 clearTimeout(this.timer);
13496 if(this.pressClass){
13497 this.el.removeClass(this.pressClass);
13499 this.el.on("mouseover", this.handleMouseReturn, this);
13503 handleMouseReturn : function(){
13504 this.el.un("mouseover", this.handleMouseReturn);
13505 if(this.pressClass){
13506 this.el.addClass(this.pressClass);
13512 handleMouseUp : function(){
13513 clearTimeout(this.timer);
13514 this.el.un("mouseover", this.handleMouseReturn);
13515 this.el.un("mouseout", this.handleMouseOut);
13516 Roo.get(document).un("mouseup", this.handleMouseUp);
13517 this.el.removeClass(this.pressClass);
13518 this.fireEvent("mouseup", this);
13522 * Ext JS Library 1.1.1
13523 * Copyright(c) 2006-2007, Ext JS, LLC.
13525 * Originally Released Under LGPL - original licence link has changed is not relivant.
13528 * <script type="text/javascript">
13533 * @class Roo.KeyNav
13534 * <p>Provides a convenient wrapper for normalized keyboard navigation. KeyNav allows you to bind
13535 * navigation keys to function calls that will get called when the keys are pressed, providing an easy
13536 * way to implement custom navigation schemes for any UI component.</p>
13537 * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
13538 * pageUp, pageDown, del, home, end. Usage:</p>
13540 var nav = new Roo.KeyNav("my-element", {
13541 "left" : function(e){
13542 this.moveLeft(e.ctrlKey);
13544 "right" : function(e){
13545 this.moveRight(e.ctrlKey);
13547 "enter" : function(e){
13554 * @param {String/HTMLElement/Roo.Element} el The element to bind to
13555 * @param {Object} config The config
13557 Roo.KeyNav = function(el, config){
13558 this.el = Roo.get(el);
13559 Roo.apply(this, config);
13560 if(!this.disabled){
13561 this.disabled = true;
13566 Roo.KeyNav.prototype = {
13568 * @cfg {Boolean} disabled
13569 * True to disable this KeyNav instance (defaults to false)
13573 * @cfg {String} defaultEventAction
13574 * The method to call on the {@link Roo.EventObject} after this KeyNav intercepts a key. Valid values are
13575 * {@link Roo.EventObject#stopEvent}, {@link Roo.EventObject#preventDefault} and
13576 * {@link Roo.EventObject#stopPropagation} (defaults to 'stopEvent')
13578 defaultEventAction: "stopEvent",
13580 * @cfg {Boolean} forceKeyDown
13581 * Handle the keydown event instead of keypress (defaults to false). KeyNav automatically does this for IE since
13582 * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
13583 * handle keydown instead of keypress.
13585 forceKeyDown : false,
13588 prepareEvent : function(e){
13589 var k = e.getKey();
13590 var h = this.keyToHandler[k];
13591 //if(h && this[h]){
13592 // e.stopPropagation();
13594 if(Roo.isSafari && h && k >= 37 && k <= 40){
13600 relay : function(e){
13601 var k = e.getKey();
13602 var h = this.keyToHandler[k];
13604 if(this.doRelay(e, this[h], h) !== true){
13605 e[this.defaultEventAction]();
13611 doRelay : function(e, h, hname){
13612 return h.call(this.scope || this, e);
13615 // possible handlers
13629 // quick lookup hash
13646 * Enable this KeyNav
13648 enable: function(){
13650 // ie won't do special keys on keypress, no one else will repeat keys with keydown
13651 // the EventObject will normalize Safari automatically
13652 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
13653 this.el.on("keydown", this.relay, this);
13655 this.el.on("keydown", this.prepareEvent, this);
13656 this.el.on("keypress", this.relay, this);
13658 this.disabled = false;
13663 * Disable this KeyNav
13665 disable: function(){
13666 if(!this.disabled){
13667 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
13668 this.el.un("keydown", this.relay);
13670 this.el.un("keydown", this.prepareEvent);
13671 this.el.un("keypress", this.relay);
13673 this.disabled = true;
13678 * Ext JS Library 1.1.1
13679 * Copyright(c) 2006-2007, Ext JS, LLC.
13681 * Originally Released Under LGPL - original licence link has changed is not relivant.
13684 * <script type="text/javascript">
13689 * @class Roo.KeyMap
13690 * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
13691 * The constructor accepts the same config object as defined by {@link #addBinding}.
13692 * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
13693 * combination it will call the function with this signature (if the match is a multi-key
13694 * combination the callback will still be called only once): (String key, Roo.EventObject e)
13695 * A KeyMap can also handle a string representation of keys.<br />
13698 // map one key by key code
13699 var map = new Roo.KeyMap("my-element", {
13700 key: 13, // or Roo.EventObject.ENTER
13705 // map multiple keys to one action by string
13706 var map = new Roo.KeyMap("my-element", {
13712 // map multiple keys to multiple actions by strings and array of codes
13713 var map = new Roo.KeyMap("my-element", [
13716 fn: function(){ alert("Return was pressed"); }
13719 fn: function(){ alert('a, b or c was pressed'); }
13724 fn: function(){ alert('Control + shift + tab was pressed.'); }
13728 * <b>Note: A KeyMap starts enabled</b>
13730 * @param {String/HTMLElement/Roo.Element} el The element to bind to
13731 * @param {Object} config The config (see {@link #addBinding})
13732 * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
13734 Roo.KeyMap = function(el, config, eventName){
13735 this.el = Roo.get(el);
13736 this.eventName = eventName || "keydown";
13737 this.bindings = [];
13739 this.addBinding(config);
13744 Roo.KeyMap.prototype = {
13746 * True to stop the event from bubbling and prevent the default browser action if the
13747 * key was handled by the KeyMap (defaults to false)
13753 * Add a new binding to this KeyMap. The following config object properties are supported:
13755 Property Type Description
13756 ---------- --------------- ----------------------------------------------------------------------
13757 key String/Array A single keycode or an array of keycodes to handle
13758 shift Boolean True to handle key only when shift is pressed (defaults to false)
13759 ctrl Boolean True to handle key only when ctrl is pressed (defaults to false)
13760 alt Boolean True to handle key only when alt is pressed (defaults to false)
13761 fn Function The function to call when KeyMap finds the expected key combination
13762 scope Object The scope of the callback function
13768 var map = new Roo.KeyMap(document, {
13769 key: Roo.EventObject.ENTER,
13774 //Add a new binding to the existing KeyMap later
13782 * @param {Object/Array} config A single KeyMap config or an array of configs
13784 addBinding : function(config){
13785 if(config instanceof Array){
13786 for(var i = 0, len = config.length; i < len; i++){
13787 this.addBinding(config[i]);
13791 var keyCode = config.key,
13792 shift = config.shift,
13793 ctrl = config.ctrl,
13796 scope = config.scope;
13797 if(typeof keyCode == "string"){
13799 var keyString = keyCode.toUpperCase();
13800 for(var j = 0, len = keyString.length; j < len; j++){
13801 ks.push(keyString.charCodeAt(j));
13805 var keyArray = keyCode instanceof Array;
13806 var handler = function(e){
13807 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
13808 var k = e.getKey();
13810 for(var i = 0, len = keyCode.length; i < len; i++){
13811 if(keyCode[i] == k){
13812 if(this.stopEvent){
13815 fn.call(scope || window, k, e);
13821 if(this.stopEvent){
13824 fn.call(scope || window, k, e);
13829 this.bindings.push(handler);
13833 * Shorthand for adding a single key listener
13834 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
13835 * following options:
13836 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
13837 * @param {Function} fn The function to call
13838 * @param {Object} scope (optional) The scope of the function
13840 on : function(key, fn, scope){
13841 var keyCode, shift, ctrl, alt;
13842 if(typeof key == "object" && !(key instanceof Array)){
13861 handleKeyDown : function(e){
13862 if(this.enabled){ //just in case
13863 var b = this.bindings;
13864 for(var i = 0, len = b.length; i < len; i++){
13865 b[i].call(this, e);
13871 * Returns true if this KeyMap is enabled
13872 * @return {Boolean}
13874 isEnabled : function(){
13875 return this.enabled;
13879 * Enables this KeyMap
13881 enable: function(){
13883 this.el.on(this.eventName, this.handleKeyDown, this);
13884 this.enabled = true;
13889 * Disable this KeyMap
13891 disable: function(){
13893 this.el.removeListener(this.eventName, this.handleKeyDown, this);
13894 this.enabled = false;
13899 * Ext JS Library 1.1.1
13900 * Copyright(c) 2006-2007, Ext JS, LLC.
13902 * Originally Released Under LGPL - original licence link has changed is not relivant.
13905 * <script type="text/javascript">
13910 * @class Roo.util.TextMetrics
13911 * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
13912 * wide, in pixels, a given block of text will be.
13915 Roo.util.TextMetrics = function(){
13919 * Measures the size of the specified text
13920 * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
13921 * that can affect the size of the rendered text
13922 * @param {String} text The text to measure
13923 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
13924 * in order to accurately measure the text height
13925 * @return {Object} An object containing the text's size {width: (width), height: (height)}
13927 measure : function(el, text, fixedWidth){
13929 shared = Roo.util.TextMetrics.Instance(el, fixedWidth);
13932 shared.setFixedWidth(fixedWidth || 'auto');
13933 return shared.getSize(text);
13937 * Return a unique TextMetrics instance that can be bound directly to an element and reused. This reduces
13938 * the overhead of multiple calls to initialize the style properties on each measurement.
13939 * @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
13940 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
13941 * in order to accurately measure the text height
13942 * @return {Roo.util.TextMetrics.Instance} instance The new instance
13944 createInstance : function(el, fixedWidth){
13945 return Roo.util.TextMetrics.Instance(el, fixedWidth);
13952 Roo.util.TextMetrics.Instance = function(bindTo, fixedWidth){
13953 var ml = new Roo.Element(document.createElement('div'));
13954 document.body.appendChild(ml.dom);
13955 ml.position('absolute');
13956 ml.setLeftTop(-1000, -1000);
13960 ml.setWidth(fixedWidth);
13965 * Returns the size of the specified text based on the internal element's style and width properties
13966 * @memberOf Roo.util.TextMetrics.Instance#
13967 * @param {String} text The text to measure
13968 * @return {Object} An object containing the text's size {width: (width), height: (height)}
13970 getSize : function(text){
13972 var s = ml.getSize();
13978 * Binds this TextMetrics instance to an element from which to copy existing CSS styles
13979 * that can affect the size of the rendered text
13980 * @memberOf Roo.util.TextMetrics.Instance#
13981 * @param {String/HTMLElement} el The element, dom node or id
13983 bind : function(el){
13985 Roo.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
13990 * Sets a fixed width on the internal measurement element. If the text will be multiline, you have
13991 * to set a fixed width in order to accurately measure the text height.
13992 * @memberOf Roo.util.TextMetrics.Instance#
13993 * @param {Number} width The width to set on the element
13995 setFixedWidth : function(width){
13996 ml.setWidth(width);
14000 * Returns the measured width of the specified text
14001 * @memberOf Roo.util.TextMetrics.Instance#
14002 * @param {String} text The text to measure
14003 * @return {Number} width The width in pixels
14005 getWidth : function(text){
14006 ml.dom.style.width = 'auto';
14007 return this.getSize(text).width;
14011 * Returns the measured height of the specified text. For multiline text, be sure to call
14012 * {@link #setFixedWidth} if necessary.
14013 * @memberOf Roo.util.TextMetrics.Instance#
14014 * @param {String} text The text to measure
14015 * @return {Number} height The height in pixels
14017 getHeight : function(text){
14018 return this.getSize(text).height;
14022 instance.bind(bindTo);
14027 // backwards compat
14028 Roo.Element.measureText = Roo.util.TextMetrics.measure;/*
14030 * Ext JS Library 1.1.1
14031 * Copyright(c) 2006-2007, Ext JS, LLC.
14033 * Originally Released Under LGPL - original licence link has changed is not relivant.
14036 * <script type="text/javascript">
14040 * @class Roo.state.Provider
14041 * Abstract base class for state provider implementations. This class provides methods
14042 * for encoding and decoding <b>typed</b> variables including dates and defines the
14043 * Provider interface.
14045 Roo.state.Provider = function(){
14047 * @event statechange
14048 * Fires when a state change occurs.
14049 * @param {Provider} this This state provider
14050 * @param {String} key The state key which was changed
14051 * @param {String} value The encoded value for the state
14054 "statechange": true
14057 Roo.state.Provider.superclass.constructor.call(this);
14059 Roo.extend(Roo.state.Provider, Roo.util.Observable, {
14061 * Returns the current value for a key
14062 * @param {String} name The key name
14063 * @param {Mixed} defaultValue A default value to return if the key's value is not found
14064 * @return {Mixed} The state data
14066 get : function(name, defaultValue){
14067 return typeof this.state[name] == "undefined" ?
14068 defaultValue : this.state[name];
14072 * Clears a value from the state
14073 * @param {String} name The key name
14075 clear : function(name){
14076 delete this.state[name];
14077 this.fireEvent("statechange", this, name, null);
14081 * Sets the value for a key
14082 * @param {String} name The key name
14083 * @param {Mixed} value The value to set
14085 set : function(name, value){
14086 this.state[name] = value;
14087 this.fireEvent("statechange", this, name, value);
14091 * Decodes a string previously encoded with {@link #encodeValue}.
14092 * @param {String} value The value to decode
14093 * @return {Mixed} The decoded value
14095 decodeValue : function(cookie){
14096 var re = /^(a|n|d|b|s|o)\:(.*)$/;
14097 var matches = re.exec(unescape(cookie));
14098 if(!matches || !matches[1]) return; // non state cookie
14099 var type = matches[1];
14100 var v = matches[2];
14103 return parseFloat(v);
14105 return new Date(Date.parse(v));
14110 var values = v.split("^");
14111 for(var i = 0, len = values.length; i < len; i++){
14112 all.push(this.decodeValue(values[i]));
14117 var values = v.split("^");
14118 for(var i = 0, len = values.length; i < len; i++){
14119 var kv = values[i].split("=");
14120 all[kv[0]] = this.decodeValue(kv[1]);
14129 * Encodes a value including type information. Decode with {@link #decodeValue}.
14130 * @param {Mixed} value The value to encode
14131 * @return {String} The encoded value
14133 encodeValue : function(v){
14135 if(typeof v == "number"){
14137 }else if(typeof v == "boolean"){
14138 enc = "b:" + (v ? "1" : "0");
14139 }else if(v instanceof Date){
14140 enc = "d:" + v.toGMTString();
14141 }else if(v instanceof Array){
14143 for(var i = 0, len = v.length; i < len; i++){
14144 flat += this.encodeValue(v[i]);
14145 if(i != len-1) flat += "^";
14148 }else if(typeof v == "object"){
14151 if(typeof v[key] != "function"){
14152 flat += key + "=" + this.encodeValue(v[key]) + "^";
14155 enc = "o:" + flat.substring(0, flat.length-1);
14159 return escape(enc);
14165 * Ext JS Library 1.1.1
14166 * Copyright(c) 2006-2007, Ext JS, LLC.
14168 * Originally Released Under LGPL - original licence link has changed is not relivant.
14171 * <script type="text/javascript">
14174 * @class Roo.state.Manager
14175 * This is the global state manager. By default all components that are "state aware" check this class
14176 * for state information if you don't pass them a custom state provider. In order for this class
14177 * to be useful, it must be initialized with a provider when your application initializes.
14179 // in your initialization function
14181 Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
14183 // supposed you have a {@link Roo.BorderLayout}
14184 var layout = new Roo.BorderLayout(...);
14185 layout.restoreState();
14186 // or a {Roo.BasicDialog}
14187 var dialog = new Roo.BasicDialog(...);
14188 dialog.restoreState();
14192 Roo.state.Manager = function(){
14193 var provider = new Roo.state.Provider();
14197 * Configures the default state provider for your application
14198 * @param {Provider} stateProvider The state provider to set
14200 setProvider : function(stateProvider){
14201 provider = stateProvider;
14205 * Returns the current value for a key
14206 * @param {String} name The key name
14207 * @param {Mixed} defaultValue The default value to return if the key lookup does not match
14208 * @return {Mixed} The state data
14210 get : function(key, defaultValue){
14211 return provider.get(key, defaultValue);
14215 * Sets the value for a key
14216 * @param {String} name The key name
14217 * @param {Mixed} value The state data
14219 set : function(key, value){
14220 provider.set(key, value);
14224 * Clears a value from the state
14225 * @param {String} name The key name
14227 clear : function(key){
14228 provider.clear(key);
14232 * Gets the currently configured state provider
14233 * @return {Provider} The state provider
14235 getProvider : function(){
14242 * Ext JS Library 1.1.1
14243 * Copyright(c) 2006-2007, Ext JS, LLC.
14245 * Originally Released Under LGPL - original licence link has changed is not relivant.
14248 * <script type="text/javascript">
14251 * @class Roo.state.CookieProvider
14252 * @extends Roo.state.Provider
14253 * The default Provider implementation which saves state via cookies.
14256 var cp = new Roo.state.CookieProvider({
14258 expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30 days
14259 domain: "roojs.com"
14261 Roo.state.Manager.setProvider(cp);
14263 * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
14264 * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
14265 * @cfg {String} domain The domain to save the cookie for. Note that you cannot specify a different domain than
14266 * your page is on, but you can specify a sub-domain, or simply the domain itself like 'roojs.com' to include
14267 * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
14268 * domain the page is running on including the 'www' like 'www.roojs.com')
14269 * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
14271 * Create a new CookieProvider
14272 * @param {Object} config The configuration object
14274 Roo.state.CookieProvider = function(config){
14275 Roo.state.CookieProvider.superclass.constructor.call(this);
14277 this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
14278 this.domain = null;
14279 this.secure = false;
14280 Roo.apply(this, config);
14281 this.state = this.readCookies();
14284 Roo.extend(Roo.state.CookieProvider, Roo.state.Provider, {
14286 set : function(name, value){
14287 if(typeof value == "undefined" || value === null){
14291 this.setCookie(name, value);
14292 Roo.state.CookieProvider.superclass.set.call(this, name, value);
14296 clear : function(name){
14297 this.clearCookie(name);
14298 Roo.state.CookieProvider.superclass.clear.call(this, name);
14302 readCookies : function(){
14304 var c = document.cookie + ";";
14305 var re = /\s?(.*?)=(.*?);/g;
14307 while((matches = re.exec(c)) != null){
14308 var name = matches[1];
14309 var value = matches[2];
14310 if(name && name.substring(0,3) == "ys-"){
14311 cookies[name.substr(3)] = this.decodeValue(value);
14318 setCookie : function(name, value){
14319 document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
14320 ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
14321 ((this.path == null) ? "" : ("; path=" + this.path)) +
14322 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
14323 ((this.secure == true) ? "; secure" : "");
14327 clearCookie : function(name){
14328 document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
14329 ((this.path == null) ? "" : ("; path=" + this.path)) +
14330 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
14331 ((this.secure == true) ? "; secure" : "");
14335 * Ext JS Library 1.1.1
14336 * Copyright(c) 2006-2007, Ext JS, LLC.
14338 * Originally Released Under LGPL - original licence link has changed is not relivant.
14341 * <script type="text/javascript">
14347 * These classes are derivatives of the similarly named classes in the YUI Library.
14348 * The original license:
14349 * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
14350 * Code licensed under the BSD License:
14351 * http://developer.yahoo.net/yui/license.txt
14356 var Event=Roo.EventManager;
14357 var Dom=Roo.lib.Dom;
14360 * @class Roo.dd.DragDrop
14361 * Defines the interface and base operation of items that that can be
14362 * dragged or can be drop targets. It was designed to be extended, overriding
14363 * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
14364 * Up to three html elements can be associated with a DragDrop instance:
14366 * <li>linked element: the element that is passed into the constructor.
14367 * This is the element which defines the boundaries for interaction with
14368 * other DragDrop objects.</li>
14369 * <li>handle element(s): The drag operation only occurs if the element that
14370 * was clicked matches a handle element. By default this is the linked
14371 * element, but there are times that you will want only a portion of the
14372 * linked element to initiate the drag operation, and the setHandleElId()
14373 * method provides a way to define this.</li>
14374 * <li>drag element: this represents the element that would be moved along
14375 * with the cursor during a drag operation. By default, this is the linked
14376 * element itself as in {@link Roo.dd.DD}. setDragElId() lets you define
14377 * a separate element that would be moved, as in {@link Roo.dd.DDProxy}.
14380 * This class should not be instantiated until the onload event to ensure that
14381 * the associated elements are available.
14382 * The following would define a DragDrop obj that would interact with any
14383 * other DragDrop obj in the "group1" group:
14385 * dd = new Roo.dd.DragDrop("div1", "group1");
14387 * Since none of the event handlers have been implemented, nothing would
14388 * actually happen if you were to run the code above. Normally you would
14389 * override this class or one of the default implementations, but you can
14390 * also override the methods you want on an instance of the class...
14392 * dd.onDragDrop = function(e, id) {
14393 * alert("dd was dropped on " + id);
14397 * @param {String} id of the element that is linked to this instance
14398 * @param {String} sGroup the group of related DragDrop objects
14399 * @param {object} config an object containing configurable attributes
14400 * Valid properties for DragDrop:
14401 * padding, isTarget, maintainOffset, primaryButtonOnly
14403 Roo.dd.DragDrop = function(id, sGroup, config) {
14405 this.init(id, sGroup, config);
14409 Roo.dd.DragDrop.prototype = {
14412 * The id of the element associated with this object. This is what we
14413 * refer to as the "linked element" because the size and position of
14414 * this element is used to determine when the drag and drop objects have
14422 * Configuration attributes passed into the constructor
14429 * The id of the element that will be dragged. By default this is same
14430 * as the linked element , but could be changed to another element. Ex:
14432 * @property dragElId
14439 * the id of the element that initiates the drag operation. By default
14440 * this is the linked element, but could be changed to be a child of this
14441 * element. This lets us do things like only starting the drag when the
14442 * header element within the linked html element is clicked.
14443 * @property handleElId
14450 * An associative array of HTML tags that will be ignored if clicked.
14451 * @property invalidHandleTypes
14452 * @type {string: string}
14454 invalidHandleTypes: null,
14457 * An associative array of ids for elements that will be ignored if clicked
14458 * @property invalidHandleIds
14459 * @type {string: string}
14461 invalidHandleIds: null,
14464 * An indexted array of css class names for elements that will be ignored
14466 * @property invalidHandleClasses
14469 invalidHandleClasses: null,
14472 * The linked element's absolute X position at the time the drag was
14474 * @property startPageX
14481 * The linked element's absolute X position at the time the drag was
14483 * @property startPageY
14490 * The group defines a logical collection of DragDrop objects that are
14491 * related. Instances only get events when interacting with other
14492 * DragDrop object in the same group. This lets us define multiple
14493 * groups using a single DragDrop subclass if we want.
14495 * @type {string: string}
14500 * Individual drag/drop instances can be locked. This will prevent
14501 * onmousedown start drag.
14509 * Lock this instance
14512 lock: function() { this.locked = true; },
14515 * Unlock this instace
14518 unlock: function() { this.locked = false; },
14521 * By default, all insances can be a drop target. This can be disabled by
14522 * setting isTarget to false.
14529 * The padding configured for this drag and drop object for calculating
14530 * the drop zone intersection with this object.
14537 * Cached reference to the linked element
14538 * @property _domRef
14544 * Internal typeof flag
14545 * @property __ygDragDrop
14548 __ygDragDrop: true,
14551 * Set to true when horizontal contraints are applied
14552 * @property constrainX
14559 * Set to true when vertical contraints are applied
14560 * @property constrainY
14567 * The left constraint
14575 * The right constraint
14583 * The up constraint
14592 * The down constraint
14600 * Maintain offsets when we resetconstraints. Set to true when you want
14601 * the position of the element relative to its parent to stay the same
14602 * when the page changes
14604 * @property maintainOffset
14607 maintainOffset: false,
14610 * Array of pixel locations the element will snap to if we specified a
14611 * horizontal graduation/interval. This array is generated automatically
14612 * when you define a tick interval.
14619 * Array of pixel locations the element will snap to if we specified a
14620 * vertical graduation/interval. This array is generated automatically
14621 * when you define a tick interval.
14628 * By default the drag and drop instance will only respond to the primary
14629 * button click (left button for a right-handed mouse). Set to true to
14630 * allow drag and drop to start with any mouse click that is propogated
14632 * @property primaryButtonOnly
14635 primaryButtonOnly: true,
14638 * The availabe property is false until the linked dom element is accessible.
14639 * @property available
14645 * By default, drags can only be initiated if the mousedown occurs in the
14646 * region the linked element is. This is done in part to work around a
14647 * bug in some browsers that mis-report the mousedown if the previous
14648 * mouseup happened outside of the window. This property is set to true
14649 * if outer handles are defined.
14651 * @property hasOuterHandles
14655 hasOuterHandles: false,
14658 * Code that executes immediately before the startDrag event
14659 * @method b4StartDrag
14662 b4StartDrag: function(x, y) { },
14665 * Abstract method called after a drag/drop object is clicked
14666 * and the drag or mousedown time thresholds have beeen met.
14667 * @method startDrag
14668 * @param {int} X click location
14669 * @param {int} Y click location
14671 startDrag: function(x, y) { /* override this */ },
14674 * Code that executes immediately before the onDrag event
14678 b4Drag: function(e) { },
14681 * Abstract method called during the onMouseMove event while dragging an
14684 * @param {Event} e the mousemove event
14686 onDrag: function(e) { /* override this */ },
14689 * Abstract method called when this element fist begins hovering over
14690 * another DragDrop obj
14691 * @method onDragEnter
14692 * @param {Event} e the mousemove event
14693 * @param {String|DragDrop[]} id In POINT mode, the element
14694 * id this is hovering over. In INTERSECT mode, an array of one or more
14695 * dragdrop items being hovered over.
14697 onDragEnter: function(e, id) { /* override this */ },
14700 * Code that executes immediately before the onDragOver event
14701 * @method b4DragOver
14704 b4DragOver: function(e) { },
14707 * Abstract method called when this element is hovering over another
14709 * @method onDragOver
14710 * @param {Event} e the mousemove event
14711 * @param {String|DragDrop[]} id In POINT mode, the element
14712 * id this is hovering over. In INTERSECT mode, an array of dd items
14713 * being hovered over.
14715 onDragOver: function(e, id) { /* override this */ },
14718 * Code that executes immediately before the onDragOut event
14719 * @method b4DragOut
14722 b4DragOut: function(e) { },
14725 * Abstract method called when we are no longer hovering over an element
14726 * @method onDragOut
14727 * @param {Event} e the mousemove event
14728 * @param {String|DragDrop[]} id In POINT mode, the element
14729 * id this was hovering over. In INTERSECT mode, an array of dd items
14730 * that the mouse is no longer over.
14732 onDragOut: function(e, id) { /* override this */ },
14735 * Code that executes immediately before the onDragDrop event
14736 * @method b4DragDrop
14739 b4DragDrop: function(e) { },
14742 * Abstract method called when this item is dropped on another DragDrop
14744 * @method onDragDrop
14745 * @param {Event} e the mouseup event
14746 * @param {String|DragDrop[]} id In POINT mode, the element
14747 * id this was dropped on. In INTERSECT mode, an array of dd items this
14750 onDragDrop: function(e, id) { /* override this */ },
14753 * Abstract method called when this item is dropped on an area with no
14755 * @method onInvalidDrop
14756 * @param {Event} e the mouseup event
14758 onInvalidDrop: function(e) { /* override this */ },
14761 * Code that executes immediately before the endDrag event
14762 * @method b4EndDrag
14765 b4EndDrag: function(e) { },
14768 * Fired when we are done dragging the object
14770 * @param {Event} e the mouseup event
14772 endDrag: function(e) { /* override this */ },
14775 * Code executed immediately before the onMouseDown event
14776 * @method b4MouseDown
14777 * @param {Event} e the mousedown event
14780 b4MouseDown: function(e) { },
14783 * Event handler that fires when a drag/drop obj gets a mousedown
14784 * @method onMouseDown
14785 * @param {Event} e the mousedown event
14787 onMouseDown: function(e) { /* override this */ },
14790 * Event handler that fires when a drag/drop obj gets a mouseup
14791 * @method onMouseUp
14792 * @param {Event} e the mouseup event
14794 onMouseUp: function(e) { /* override this */ },
14797 * Override the onAvailable method to do what is needed after the initial
14798 * position was determined.
14799 * @method onAvailable
14801 onAvailable: function () {
14805 * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
14808 defaultPadding : {left:0, right:0, top:0, bottom:0},
14811 * Initializes the drag drop object's constraints to restrict movement to a certain element.
14815 var dd = new Roo.dd.DDProxy("dragDiv1", "proxytest",
14816 { dragElId: "existingProxyDiv" });
14817 dd.startDrag = function(){
14818 this.constrainTo("parent-id");
14821 * Or you can initalize it using the {@link Roo.Element} object:
14823 Roo.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
14824 startDrag : function(){
14825 this.constrainTo("parent-id");
14829 * @param {String/HTMLElement/Element} constrainTo The element to constrain to.
14830 * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
14831 * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
14832 * an object containing the sides to pad. For example: {right:10, bottom:10}
14833 * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
14835 constrainTo : function(constrainTo, pad, inContent){
14836 if(typeof pad == "number"){
14837 pad = {left: pad, right:pad, top:pad, bottom:pad};
14839 pad = pad || this.defaultPadding;
14840 var b = Roo.get(this.getEl()).getBox();
14841 var ce = Roo.get(constrainTo);
14842 var s = ce.getScroll();
14843 var c, cd = ce.dom;
14844 if(cd == document.body){
14845 c = { x: s.left, y: s.top, width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
14848 c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
14852 var topSpace = b.y - c.y;
14853 var leftSpace = b.x - c.x;
14855 this.resetConstraints();
14856 this.setXConstraint(leftSpace - (pad.left||0), // left
14857 c.width - leftSpace - b.width - (pad.right||0) //right
14859 this.setYConstraint(topSpace - (pad.top||0), //top
14860 c.height - topSpace - b.height - (pad.bottom||0) //bottom
14865 * Returns a reference to the linked element
14867 * @return {HTMLElement} the html element
14869 getEl: function() {
14870 if (!this._domRef) {
14871 this._domRef = Roo.getDom(this.id);
14874 return this._domRef;
14878 * Returns a reference to the actual element to drag. By default this is
14879 * the same as the html element, but it can be assigned to another
14880 * element. An example of this can be found in Roo.dd.DDProxy
14881 * @method getDragEl
14882 * @return {HTMLElement} the html element
14884 getDragEl: function() {
14885 return Roo.getDom(this.dragElId);
14889 * Sets up the DragDrop object. Must be called in the constructor of any
14890 * Roo.dd.DragDrop subclass
14892 * @param id the id of the linked element
14893 * @param {String} sGroup the group of related items
14894 * @param {object} config configuration attributes
14896 init: function(id, sGroup, config) {
14897 this.initTarget(id, sGroup, config);
14898 Event.on(this.id, "mousedown", this.handleMouseDown, this);
14899 // Event.on(this.id, "selectstart", Event.preventDefault);
14903 * Initializes Targeting functionality only... the object does not
14904 * get a mousedown handler.
14905 * @method initTarget
14906 * @param id the id of the linked element
14907 * @param {String} sGroup the group of related items
14908 * @param {object} config configuration attributes
14910 initTarget: function(id, sGroup, config) {
14912 // configuration attributes
14913 this.config = config || {};
14915 // create a local reference to the drag and drop manager
14916 this.DDM = Roo.dd.DDM;
14917 // initialize the groups array
14920 // assume that we have an element reference instead of an id if the
14921 // parameter is not a string
14922 if (typeof id !== "string") {
14929 // add to an interaction group
14930 this.addToGroup((sGroup) ? sGroup : "default");
14932 // We don't want to register this as the handle with the manager
14933 // so we just set the id rather than calling the setter.
14934 this.handleElId = id;
14936 // the linked element is the element that gets dragged by default
14937 this.setDragElId(id);
14939 // by default, clicked anchors will not start drag operations.
14940 this.invalidHandleTypes = { A: "A" };
14941 this.invalidHandleIds = {};
14942 this.invalidHandleClasses = [];
14944 this.applyConfig();
14946 this.handleOnAvailable();
14950 * Applies the configuration parameters that were passed into the constructor.
14951 * This is supposed to happen at each level through the inheritance chain. So
14952 * a DDProxy implentation will execute apply config on DDProxy, DD, and
14953 * DragDrop in order to get all of the parameters that are available in
14955 * @method applyConfig
14957 applyConfig: function() {
14959 // configurable properties:
14960 // padding, isTarget, maintainOffset, primaryButtonOnly
14961 this.padding = this.config.padding || [0, 0, 0, 0];
14962 this.isTarget = (this.config.isTarget !== false);
14963 this.maintainOffset = (this.config.maintainOffset);
14964 this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
14969 * Executed when the linked element is available
14970 * @method handleOnAvailable
14973 handleOnAvailable: function() {
14974 this.available = true;
14975 this.resetConstraints();
14976 this.onAvailable();
14980 * Configures the padding for the target zone in px. Effectively expands
14981 * (or reduces) the virtual object size for targeting calculations.
14982 * Supports css-style shorthand; if only one parameter is passed, all sides
14983 * will have that padding, and if only two are passed, the top and bottom
14984 * will have the first param, the left and right the second.
14985 * @method setPadding
14986 * @param {int} iTop Top pad
14987 * @param {int} iRight Right pad
14988 * @param {int} iBot Bot pad
14989 * @param {int} iLeft Left pad
14991 setPadding: function(iTop, iRight, iBot, iLeft) {
14992 // this.padding = [iLeft, iRight, iTop, iBot];
14993 if (!iRight && 0 !== iRight) {
14994 this.padding = [iTop, iTop, iTop, iTop];
14995 } else if (!iBot && 0 !== iBot) {
14996 this.padding = [iTop, iRight, iTop, iRight];
14998 this.padding = [iTop, iRight, iBot, iLeft];
15003 * Stores the initial placement of the linked element.
15004 * @method setInitialPosition
15005 * @param {int} diffX the X offset, default 0
15006 * @param {int} diffY the Y offset, default 0
15008 setInitPosition: function(diffX, diffY) {
15009 var el = this.getEl();
15011 if (!this.DDM.verifyEl(el)) {
15015 var dx = diffX || 0;
15016 var dy = diffY || 0;
15018 var p = Dom.getXY( el );
15020 this.initPageX = p[0] - dx;
15021 this.initPageY = p[1] - dy;
15023 this.lastPageX = p[0];
15024 this.lastPageY = p[1];
15027 this.setStartPosition(p);
15031 * Sets the start position of the element. This is set when the obj
15032 * is initialized, the reset when a drag is started.
15033 * @method setStartPosition
15034 * @param pos current position (from previous lookup)
15037 setStartPosition: function(pos) {
15038 var p = pos || Dom.getXY( this.getEl() );
15039 this.deltaSetXY = null;
15041 this.startPageX = p[0];
15042 this.startPageY = p[1];
15046 * Add this instance to a group of related drag/drop objects. All
15047 * instances belong to at least one group, and can belong to as many
15048 * groups as needed.
15049 * @method addToGroup
15050 * @param sGroup {string} the name of the group
15052 addToGroup: function(sGroup) {
15053 this.groups[sGroup] = true;
15054 this.DDM.regDragDrop(this, sGroup);
15058 * Remove's this instance from the supplied interaction group
15059 * @method removeFromGroup
15060 * @param {string} sGroup The group to drop
15062 removeFromGroup: function(sGroup) {
15063 if (this.groups[sGroup]) {
15064 delete this.groups[sGroup];
15067 this.DDM.removeDDFromGroup(this, sGroup);
15071 * Allows you to specify that an element other than the linked element
15072 * will be moved with the cursor during a drag
15073 * @method setDragElId
15074 * @param id {string} the id of the element that will be used to initiate the drag
15076 setDragElId: function(id) {
15077 this.dragElId = id;
15081 * Allows you to specify a child of the linked element that should be
15082 * used to initiate the drag operation. An example of this would be if
15083 * you have a content div with text and links. Clicking anywhere in the
15084 * content area would normally start the drag operation. Use this method
15085 * to specify that an element inside of the content div is the element
15086 * that starts the drag operation.
15087 * @method setHandleElId
15088 * @param id {string} the id of the element that will be used to
15089 * initiate the drag.
15091 setHandleElId: function(id) {
15092 if (typeof id !== "string") {
15095 this.handleElId = id;
15096 this.DDM.regHandle(this.id, id);
15100 * Allows you to set an element outside of the linked element as a drag
15102 * @method setOuterHandleElId
15103 * @param id the id of the element that will be used to initiate the drag
15105 setOuterHandleElId: function(id) {
15106 if (typeof id !== "string") {
15109 Event.on(id, "mousedown",
15110 this.handleMouseDown, this);
15111 this.setHandleElId(id);
15113 this.hasOuterHandles = true;
15117 * Remove all drag and drop hooks for this element
15120 unreg: function() {
15121 Event.un(this.id, "mousedown",
15122 this.handleMouseDown);
15123 this._domRef = null;
15124 this.DDM._remove(this);
15127 destroy : function(){
15132 * Returns true if this instance is locked, or the drag drop mgr is locked
15133 * (meaning that all drag/drop is disabled on the page.)
15135 * @return {boolean} true if this obj or all drag/drop is locked, else
15138 isLocked: function() {
15139 return (this.DDM.isLocked() || this.locked);
15143 * Fired when this object is clicked
15144 * @method handleMouseDown
15146 * @param {Roo.dd.DragDrop} oDD the clicked dd object (this dd obj)
15149 handleMouseDown: function(e, oDD){
15150 if (this.primaryButtonOnly && e.button != 0) {
15154 if (this.isLocked()) {
15158 this.DDM.refreshCache(this.groups);
15160 var pt = new Roo.lib.Point(Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e));
15161 if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
15163 if (this.clickValidator(e)) {
15165 // set the initial element position
15166 this.setStartPosition();
15169 this.b4MouseDown(e);
15170 this.onMouseDown(e);
15172 this.DDM.handleMouseDown(e, this);
15174 this.DDM.stopEvent(e);
15182 clickValidator: function(e) {
15183 var target = e.getTarget();
15184 return ( this.isValidHandleChild(target) &&
15185 (this.id == this.handleElId ||
15186 this.DDM.handleWasClicked(target, this.id)) );
15190 * Allows you to specify a tag name that should not start a drag operation
15191 * when clicked. This is designed to facilitate embedding links within a
15192 * drag handle that do something other than start the drag.
15193 * @method addInvalidHandleType
15194 * @param {string} tagName the type of element to exclude
15196 addInvalidHandleType: function(tagName) {
15197 var type = tagName.toUpperCase();
15198 this.invalidHandleTypes[type] = type;
15202 * Lets you to specify an element id for a child of a drag handle
15203 * that should not initiate a drag
15204 * @method addInvalidHandleId
15205 * @param {string} id the element id of the element you wish to ignore
15207 addInvalidHandleId: function(id) {
15208 if (typeof id !== "string") {
15211 this.invalidHandleIds[id] = id;
15215 * Lets you specify a css class of elements that will not initiate a drag
15216 * @method addInvalidHandleClass
15217 * @param {string} cssClass the class of the elements you wish to ignore
15219 addInvalidHandleClass: function(cssClass) {
15220 this.invalidHandleClasses.push(cssClass);
15224 * Unsets an excluded tag name set by addInvalidHandleType
15225 * @method removeInvalidHandleType
15226 * @param {string} tagName the type of element to unexclude
15228 removeInvalidHandleType: function(tagName) {
15229 var type = tagName.toUpperCase();
15230 // this.invalidHandleTypes[type] = null;
15231 delete this.invalidHandleTypes[type];
15235 * Unsets an invalid handle id
15236 * @method removeInvalidHandleId
15237 * @param {string} id the id of the element to re-enable
15239 removeInvalidHandleId: function(id) {
15240 if (typeof id !== "string") {
15243 delete this.invalidHandleIds[id];
15247 * Unsets an invalid css class
15248 * @method removeInvalidHandleClass
15249 * @param {string} cssClass the class of the element(s) you wish to
15252 removeInvalidHandleClass: function(cssClass) {
15253 for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
15254 if (this.invalidHandleClasses[i] == cssClass) {
15255 delete this.invalidHandleClasses[i];
15261 * Checks the tag exclusion list to see if this click should be ignored
15262 * @method isValidHandleChild
15263 * @param {HTMLElement} node the HTMLElement to evaluate
15264 * @return {boolean} true if this is a valid tag type, false if not
15266 isValidHandleChild: function(node) {
15269 // var n = (node.nodeName == "#text") ? node.parentNode : node;
15272 nodeName = node.nodeName.toUpperCase();
15274 nodeName = node.nodeName;
15276 valid = valid && !this.invalidHandleTypes[nodeName];
15277 valid = valid && !this.invalidHandleIds[node.id];
15279 for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
15280 valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
15289 * Create the array of horizontal tick marks if an interval was specified
15290 * in setXConstraint().
15291 * @method setXTicks
15294 setXTicks: function(iStartX, iTickSize) {
15296 this.xTickSize = iTickSize;
15300 for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
15302 this.xTicks[this.xTicks.length] = i;
15307 for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
15309 this.xTicks[this.xTicks.length] = i;
15314 this.xTicks.sort(this.DDM.numericSort) ;
15318 * Create the array of vertical tick marks if an interval was specified in
15319 * setYConstraint().
15320 * @method setYTicks
15323 setYTicks: function(iStartY, iTickSize) {
15325 this.yTickSize = iTickSize;
15329 for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
15331 this.yTicks[this.yTicks.length] = i;
15336 for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
15338 this.yTicks[this.yTicks.length] = i;
15343 this.yTicks.sort(this.DDM.numericSort) ;
15347 * By default, the element can be dragged any place on the screen. Use
15348 * this method to limit the horizontal travel of the element. Pass in
15349 * 0,0 for the parameters if you want to lock the drag to the y axis.
15350 * @method setXConstraint
15351 * @param {int} iLeft the number of pixels the element can move to the left
15352 * @param {int} iRight the number of pixels the element can move to the
15354 * @param {int} iTickSize optional parameter for specifying that the
15356 * should move iTickSize pixels at a time.
15358 setXConstraint: function(iLeft, iRight, iTickSize) {
15359 this.leftConstraint = iLeft;
15360 this.rightConstraint = iRight;
15362 this.minX = this.initPageX - iLeft;
15363 this.maxX = this.initPageX + iRight;
15364 if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
15366 this.constrainX = true;
15370 * Clears any constraints applied to this instance. Also clears ticks
15371 * since they can't exist independent of a constraint at this time.
15372 * @method clearConstraints
15374 clearConstraints: function() {
15375 this.constrainX = false;
15376 this.constrainY = false;
15381 * Clears any tick interval defined for this instance
15382 * @method clearTicks
15384 clearTicks: function() {
15385 this.xTicks = null;
15386 this.yTicks = null;
15387 this.xTickSize = 0;
15388 this.yTickSize = 0;
15392 * By default, the element can be dragged any place on the screen. Set
15393 * this to limit the vertical travel of the element. Pass in 0,0 for the
15394 * parameters if you want to lock the drag to the x axis.
15395 * @method setYConstraint
15396 * @param {int} iUp the number of pixels the element can move up
15397 * @param {int} iDown the number of pixels the element can move down
15398 * @param {int} iTickSize optional parameter for specifying that the
15399 * element should move iTickSize pixels at a time.
15401 setYConstraint: function(iUp, iDown, iTickSize) {
15402 this.topConstraint = iUp;
15403 this.bottomConstraint = iDown;
15405 this.minY = this.initPageY - iUp;
15406 this.maxY = this.initPageY + iDown;
15407 if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
15409 this.constrainY = true;
15414 * resetConstraints must be called if you manually reposition a dd element.
15415 * @method resetConstraints
15416 * @param {boolean} maintainOffset
15418 resetConstraints: function() {
15421 // Maintain offsets if necessary
15422 if (this.initPageX || this.initPageX === 0) {
15423 // figure out how much this thing has moved
15424 var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
15425 var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
15427 this.setInitPosition(dx, dy);
15429 // This is the first time we have detected the element's position
15431 this.setInitPosition();
15434 if (this.constrainX) {
15435 this.setXConstraint( this.leftConstraint,
15436 this.rightConstraint,
15440 if (this.constrainY) {
15441 this.setYConstraint( this.topConstraint,
15442 this.bottomConstraint,
15448 * Normally the drag element is moved pixel by pixel, but we can specify
15449 * that it move a number of pixels at a time. This method resolves the
15450 * location when we have it set up like this.
15452 * @param {int} val where we want to place the object
15453 * @param {int[]} tickArray sorted array of valid points
15454 * @return {int} the closest tick
15457 getTick: function(val, tickArray) {
15460 // If tick interval is not defined, it is effectively 1 pixel,
15461 // so we return the value passed to us.
15463 } else if (tickArray[0] >= val) {
15464 // The value is lower than the first tick, so we return the first
15466 return tickArray[0];
15468 for (var i=0, len=tickArray.length; i<len; ++i) {
15470 if (tickArray[next] && tickArray[next] >= val) {
15471 var diff1 = val - tickArray[i];
15472 var diff2 = tickArray[next] - val;
15473 return (diff2 > diff1) ? tickArray[i] : tickArray[next];
15477 // The value is larger than the last tick, so we return the last
15479 return tickArray[tickArray.length - 1];
15486 * @return {string} string representation of the dd obj
15488 toString: function() {
15489 return ("DragDrop " + this.id);
15497 * Ext JS Library 1.1.1
15498 * Copyright(c) 2006-2007, Ext JS, LLC.
15500 * Originally Released Under LGPL - original licence link has changed is not relivant.
15503 * <script type="text/javascript">
15508 * The drag and drop utility provides a framework for building drag and drop
15509 * applications. In addition to enabling drag and drop for specific elements,
15510 * the drag and drop elements are tracked by the manager class, and the
15511 * interactions between the various elements are tracked during the drag and
15512 * the implementing code is notified about these important moments.
15515 // Only load the library once. Rewriting the manager class would orphan
15516 // existing drag and drop instances.
15517 if (!Roo.dd.DragDropMgr) {
15520 * @class Roo.dd.DragDropMgr
15521 * DragDropMgr is a singleton that tracks the element interaction for
15522 * all DragDrop items in the window. Generally, you will not call
15523 * this class directly, but it does have helper methods that could
15524 * be useful in your DragDrop implementations.
15527 Roo.dd.DragDropMgr = function() {
15529 var Event = Roo.EventManager;
15534 * Two dimensional Array of registered DragDrop objects. The first
15535 * dimension is the DragDrop item group, the second the DragDrop
15538 * @type {string: string}
15545 * Array of element ids defined as drag handles. Used to determine
15546 * if the element that generated the mousedown event is actually the
15547 * handle and not the html element itself.
15548 * @property handleIds
15549 * @type {string: string}
15556 * the DragDrop object that is currently being dragged
15557 * @property dragCurrent
15565 * the DragDrop object(s) that are being hovered over
15566 * @property dragOvers
15574 * the X distance between the cursor and the object being dragged
15583 * the Y distance between the cursor and the object being dragged
15592 * Flag to determine if we should prevent the default behavior of the
15593 * events we define. By default this is true, but this can be set to
15594 * false if you need the default behavior (not recommended)
15595 * @property preventDefault
15599 preventDefault: true,
15602 * Flag to determine if we should stop the propagation of the events
15603 * we generate. This is true by default but you may want to set it to
15604 * false if the html element contains other features that require the
15606 * @property stopPropagation
15610 stopPropagation: true,
15613 * Internal flag that is set to true when drag and drop has been
15615 * @property initialized
15622 * All drag and drop can be disabled.
15630 * Called the first time an element is registered.
15636 this.initialized = true;
15640 * In point mode, drag and drop interaction is defined by the
15641 * location of the cursor during the drag/drop
15649 * In intersect mode, drag and drop interactio nis defined by the
15650 * overlap of two or more drag and drop objects.
15651 * @property INTERSECT
15658 * The current drag and drop mode. Default: POINT
15666 * Runs method on all drag and drop objects
15667 * @method _execOnAll
15671 _execOnAll: function(sMethod, args) {
15672 for (var i in this.ids) {
15673 for (var j in this.ids[i]) {
15674 var oDD = this.ids[i][j];
15675 if (! this.isTypeOfDD(oDD)) {
15678 oDD[sMethod].apply(oDD, args);
15684 * Drag and drop initialization. Sets up the global event handlers
15689 _onLoad: function() {
15694 Event.on(document, "mouseup", this.handleMouseUp, this, true);
15695 Event.on(document, "mousemove", this.handleMouseMove, this, true);
15696 Event.on(window, "unload", this._onUnload, this, true);
15697 Event.on(window, "resize", this._onResize, this, true);
15698 // Event.on(window, "mouseout", this._test);
15703 * Reset constraints on all drag and drop objs
15704 * @method _onResize
15708 _onResize: function(e) {
15709 this._execOnAll("resetConstraints", []);
15713 * Lock all drag and drop functionality
15717 lock: function() { this.locked = true; },
15720 * Unlock all drag and drop functionality
15724 unlock: function() { this.locked = false; },
15727 * Is drag and drop locked?
15729 * @return {boolean} True if drag and drop is locked, false otherwise.
15732 isLocked: function() { return this.locked; },
15735 * Location cache that is set for all drag drop objects when a drag is
15736 * initiated, cleared when the drag is finished.
15737 * @property locationCache
15744 * Set useCache to false if you want to force object the lookup of each
15745 * drag and drop linked element constantly during a drag.
15746 * @property useCache
15753 * The number of pixels that the mouse needs to move after the
15754 * mousedown before the drag is initiated. Default=3;
15755 * @property clickPixelThresh
15759 clickPixelThresh: 3,
15762 * The number of milliseconds after the mousedown event to initiate the
15763 * drag if we don't get a mouseup event. Default=1000
15764 * @property clickTimeThresh
15768 clickTimeThresh: 350,
15771 * Flag that indicates that either the drag pixel threshold or the
15772 * mousdown time threshold has been met
15773 * @property dragThreshMet
15778 dragThreshMet: false,
15781 * Timeout used for the click time threshold
15782 * @property clickTimeout
15787 clickTimeout: null,
15790 * The X position of the mousedown event stored for later use when a
15791 * drag threshold is met.
15800 * The Y position of the mousedown event stored for later use when a
15801 * drag threshold is met.
15810 * Each DragDrop instance must be registered with the DragDropMgr.
15811 * This is executed in DragDrop.init()
15812 * @method regDragDrop
15813 * @param {DragDrop} oDD the DragDrop object to register
15814 * @param {String} sGroup the name of the group this element belongs to
15817 regDragDrop: function(oDD, sGroup) {
15818 if (!this.initialized) { this.init(); }
15820 if (!this.ids[sGroup]) {
15821 this.ids[sGroup] = {};
15823 this.ids[sGroup][oDD.id] = oDD;
15827 * Removes the supplied dd instance from the supplied group. Executed
15828 * by DragDrop.removeFromGroup, so don't call this function directly.
15829 * @method removeDDFromGroup
15833 removeDDFromGroup: function(oDD, sGroup) {
15834 if (!this.ids[sGroup]) {
15835 this.ids[sGroup] = {};
15838 var obj = this.ids[sGroup];
15839 if (obj && obj[oDD.id]) {
15840 delete obj[oDD.id];
15845 * Unregisters a drag and drop item. This is executed in
15846 * DragDrop.unreg, use that method instead of calling this directly.
15851 _remove: function(oDD) {
15852 for (var g in oDD.groups) {
15853 if (g && this.ids[g][oDD.id]) {
15854 delete this.ids[g][oDD.id];
15857 delete this.handleIds[oDD.id];
15861 * Each DragDrop handle element must be registered. This is done
15862 * automatically when executing DragDrop.setHandleElId()
15863 * @method regHandle
15864 * @param {String} sDDId the DragDrop id this element is a handle for
15865 * @param {String} sHandleId the id of the element that is the drag
15869 regHandle: function(sDDId, sHandleId) {
15870 if (!this.handleIds[sDDId]) {
15871 this.handleIds[sDDId] = {};
15873 this.handleIds[sDDId][sHandleId] = sHandleId;
15877 * Utility function to determine if a given element has been
15878 * registered as a drag drop item.
15879 * @method isDragDrop
15880 * @param {String} id the element id to check
15881 * @return {boolean} true if this element is a DragDrop item,
15885 isDragDrop: function(id) {
15886 return ( this.getDDById(id) ) ? true : false;
15890 * Returns the drag and drop instances that are in all groups the
15891 * passed in instance belongs to.
15892 * @method getRelated
15893 * @param {DragDrop} p_oDD the obj to get related data for
15894 * @param {boolean} bTargetsOnly if true, only return targetable objs
15895 * @return {DragDrop[]} the related instances
15898 getRelated: function(p_oDD, bTargetsOnly) {
15900 for (var i in p_oDD.groups) {
15901 for (j in this.ids[i]) {
15902 var dd = this.ids[i][j];
15903 if (! this.isTypeOfDD(dd)) {
15906 if (!bTargetsOnly || dd.isTarget) {
15907 oDDs[oDDs.length] = dd;
15916 * Returns true if the specified dd target is a legal target for
15917 * the specifice drag obj
15918 * @method isLegalTarget
15919 * @param {DragDrop} the drag obj
15920 * @param {DragDrop} the target
15921 * @return {boolean} true if the target is a legal target for the
15925 isLegalTarget: function (oDD, oTargetDD) {
15926 var targets = this.getRelated(oDD, true);
15927 for (var i=0, len=targets.length;i<len;++i) {
15928 if (targets[i].id == oTargetDD.id) {
15937 * My goal is to be able to transparently determine if an object is
15938 * typeof DragDrop, and the exact subclass of DragDrop. typeof
15939 * returns "object", oDD.constructor.toString() always returns
15940 * "DragDrop" and not the name of the subclass. So for now it just
15941 * evaluates a well-known variable in DragDrop.
15942 * @method isTypeOfDD
15943 * @param {Object} the object to evaluate
15944 * @return {boolean} true if typeof oDD = DragDrop
15947 isTypeOfDD: function (oDD) {
15948 return (oDD && oDD.__ygDragDrop);
15952 * Utility function to determine if a given element has been
15953 * registered as a drag drop handle for the given Drag Drop object.
15955 * @param {String} id the element id to check
15956 * @return {boolean} true if this element is a DragDrop handle, false
15960 isHandle: function(sDDId, sHandleId) {
15961 return ( this.handleIds[sDDId] &&
15962 this.handleIds[sDDId][sHandleId] );
15966 * Returns the DragDrop instance for a given id
15967 * @method getDDById
15968 * @param {String} id the id of the DragDrop object
15969 * @return {DragDrop} the drag drop object, null if it is not found
15972 getDDById: function(id) {
15973 for (var i in this.ids) {
15974 if (this.ids[i][id]) {
15975 return this.ids[i][id];
15982 * Fired after a registered DragDrop object gets the mousedown event.
15983 * Sets up the events required to track the object being dragged
15984 * @method handleMouseDown
15985 * @param {Event} e the event
15986 * @param oDD the DragDrop object being dragged
15990 handleMouseDown: function(e, oDD) {
15992 Roo.QuickTips.disable();
15994 this.currentTarget = e.getTarget();
15996 this.dragCurrent = oDD;
15998 var el = oDD.getEl();
16000 // track start position
16001 this.startX = e.getPageX();
16002 this.startY = e.getPageY();
16004 this.deltaX = this.startX - el.offsetLeft;
16005 this.deltaY = this.startY - el.offsetTop;
16007 this.dragThreshMet = false;
16009 this.clickTimeout = setTimeout(
16011 var DDM = Roo.dd.DDM;
16012 DDM.startDrag(DDM.startX, DDM.startY);
16014 this.clickTimeThresh );
16018 * Fired when either the drag pixel threshol or the mousedown hold
16019 * time threshold has been met.
16020 * @method startDrag
16021 * @param x {int} the X position of the original mousedown
16022 * @param y {int} the Y position of the original mousedown
16025 startDrag: function(x, y) {
16026 clearTimeout(this.clickTimeout);
16027 if (this.dragCurrent) {
16028 this.dragCurrent.b4StartDrag(x, y);
16029 this.dragCurrent.startDrag(x, y);
16031 this.dragThreshMet = true;
16035 * Internal function to handle the mouseup event. Will be invoked
16036 * from the context of the document.
16037 * @method handleMouseUp
16038 * @param {Event} e the event
16042 handleMouseUp: function(e) {
16045 Roo.QuickTips.enable();
16047 if (! this.dragCurrent) {
16051 clearTimeout(this.clickTimeout);
16053 if (this.dragThreshMet) {
16054 this.fireEvents(e, true);
16064 * Utility to stop event propagation and event default, if these
16065 * features are turned on.
16066 * @method stopEvent
16067 * @param {Event} e the event as returned by this.getEvent()
16070 stopEvent: function(e){
16071 if(this.stopPropagation) {
16072 e.stopPropagation();
16075 if (this.preventDefault) {
16076 e.preventDefault();
16081 * Internal function to clean up event handlers after the drag
16082 * operation is complete
16084 * @param {Event} e the event
16088 stopDrag: function(e) {
16089 // Fire the drag end event for the item that was dragged
16090 if (this.dragCurrent) {
16091 if (this.dragThreshMet) {
16092 this.dragCurrent.b4EndDrag(e);
16093 this.dragCurrent.endDrag(e);
16096 this.dragCurrent.onMouseUp(e);
16099 this.dragCurrent = null;
16100 this.dragOvers = {};
16104 * Internal function to handle the mousemove event. Will be invoked
16105 * from the context of the html element.
16107 * @TODO figure out what we can do about mouse events lost when the
16108 * user drags objects beyond the window boundary. Currently we can
16109 * detect this in internet explorer by verifying that the mouse is
16110 * down during the mousemove event. Firefox doesn't give us the
16111 * button state on the mousemove event.
16112 * @method handleMouseMove
16113 * @param {Event} e the event
16117 handleMouseMove: function(e) {
16118 if (! this.dragCurrent) {
16122 // var button = e.which || e.button;
16124 // check for IE mouseup outside of page boundary
16125 if (Roo.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
16127 return this.handleMouseUp(e);
16130 if (!this.dragThreshMet) {
16131 var diffX = Math.abs(this.startX - e.getPageX());
16132 var diffY = Math.abs(this.startY - e.getPageY());
16133 if (diffX > this.clickPixelThresh ||
16134 diffY > this.clickPixelThresh) {
16135 this.startDrag(this.startX, this.startY);
16139 if (this.dragThreshMet) {
16140 this.dragCurrent.b4Drag(e);
16141 this.dragCurrent.onDrag(e);
16142 if(!this.dragCurrent.moveOnly){
16143 this.fireEvents(e, false);
16153 * Iterates over all of the DragDrop elements to find ones we are
16154 * hovering over or dropping on
16155 * @method fireEvents
16156 * @param {Event} e the event
16157 * @param {boolean} isDrop is this a drop op or a mouseover op?
16161 fireEvents: function(e, isDrop) {
16162 var dc = this.dragCurrent;
16164 // If the user did the mouse up outside of the window, we could
16165 // get here even though we have ended the drag.
16166 if (!dc || dc.isLocked()) {
16170 var pt = e.getPoint();
16172 // cache the previous dragOver array
16178 var enterEvts = [];
16180 // Check to see if the object(s) we were hovering over is no longer
16181 // being hovered over so we can fire the onDragOut event
16182 for (var i in this.dragOvers) {
16184 var ddo = this.dragOvers[i];
16186 if (! this.isTypeOfDD(ddo)) {
16190 if (! this.isOverTarget(pt, ddo, this.mode)) {
16191 outEvts.push( ddo );
16194 oldOvers[i] = true;
16195 delete this.dragOvers[i];
16198 for (var sGroup in dc.groups) {
16200 if ("string" != typeof sGroup) {
16204 for (i in this.ids[sGroup]) {
16205 var oDD = this.ids[sGroup][i];
16206 if (! this.isTypeOfDD(oDD)) {
16210 if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
16211 if (this.isOverTarget(pt, oDD, this.mode)) {
16212 // look for drop interactions
16214 dropEvts.push( oDD );
16215 // look for drag enter and drag over interactions
16218 // initial drag over: dragEnter fires
16219 if (!oldOvers[oDD.id]) {
16220 enterEvts.push( oDD );
16221 // subsequent drag overs: dragOver fires
16223 overEvts.push( oDD );
16226 this.dragOvers[oDD.id] = oDD;
16234 if (outEvts.length) {
16235 dc.b4DragOut(e, outEvts);
16236 dc.onDragOut(e, outEvts);
16239 if (enterEvts.length) {
16240 dc.onDragEnter(e, enterEvts);
16243 if (overEvts.length) {
16244 dc.b4DragOver(e, overEvts);
16245 dc.onDragOver(e, overEvts);
16248 if (dropEvts.length) {
16249 dc.b4DragDrop(e, dropEvts);
16250 dc.onDragDrop(e, dropEvts);
16254 // fire dragout events
16256 for (i=0, len=outEvts.length; i<len; ++i) {
16257 dc.b4DragOut(e, outEvts[i].id);
16258 dc.onDragOut(e, outEvts[i].id);
16261 // fire enter events
16262 for (i=0,len=enterEvts.length; i<len; ++i) {
16263 // dc.b4DragEnter(e, oDD.id);
16264 dc.onDragEnter(e, enterEvts[i].id);
16267 // fire over events
16268 for (i=0,len=overEvts.length; i<len; ++i) {
16269 dc.b4DragOver(e, overEvts[i].id);
16270 dc.onDragOver(e, overEvts[i].id);
16273 // fire drop events
16274 for (i=0, len=dropEvts.length; i<len; ++i) {
16275 dc.b4DragDrop(e, dropEvts[i].id);
16276 dc.onDragDrop(e, dropEvts[i].id);
16281 // notify about a drop that did not find a target
16282 if (isDrop && !dropEvts.length) {
16283 dc.onInvalidDrop(e);
16289 * Helper function for getting the best match from the list of drag
16290 * and drop objects returned by the drag and drop events when we are
16291 * in INTERSECT mode. It returns either the first object that the
16292 * cursor is over, or the object that has the greatest overlap with
16293 * the dragged element.
16294 * @method getBestMatch
16295 * @param {DragDrop[]} dds The array of drag and drop objects
16297 * @return {DragDrop} The best single match
16300 getBestMatch: function(dds) {
16302 // Return null if the input is not what we expect
16303 //if (!dds || !dds.length || dds.length == 0) {
16305 // If there is only one item, it wins
16306 //} else if (dds.length == 1) {
16308 var len = dds.length;
16313 // Loop through the targeted items
16314 for (var i=0; i<len; ++i) {
16316 // If the cursor is over the object, it wins. If the
16317 // cursor is over multiple matches, the first one we come
16319 if (dd.cursorIsOver) {
16322 // Otherwise the object with the most overlap wins
16325 winner.overlap.getArea() < dd.overlap.getArea()) {
16336 * Refreshes the cache of the top-left and bottom-right points of the
16337 * drag and drop objects in the specified group(s). This is in the
16338 * format that is stored in the drag and drop instance, so typical
16341 * Roo.dd.DragDropMgr.refreshCache(ddinstance.groups);
16345 * Roo.dd.DragDropMgr.refreshCache({group1:true, group2:true});
16347 * @TODO this really should be an indexed array. Alternatively this
16348 * method could accept both.
16349 * @method refreshCache
16350 * @param {Object} groups an associative array of groups to refresh
16353 refreshCache: function(groups) {
16354 for (var sGroup in groups) {
16355 if ("string" != typeof sGroup) {
16358 for (var i in this.ids[sGroup]) {
16359 var oDD = this.ids[sGroup][i];
16361 if (this.isTypeOfDD(oDD)) {
16362 // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
16363 var loc = this.getLocation(oDD);
16365 this.locationCache[oDD.id] = loc;
16367 delete this.locationCache[oDD.id];
16368 // this will unregister the drag and drop object if
16369 // the element is not in a usable state
16378 * This checks to make sure an element exists and is in the DOM. The
16379 * main purpose is to handle cases where innerHTML is used to remove
16380 * drag and drop objects from the DOM. IE provides an 'unspecified
16381 * error' when trying to access the offsetParent of such an element
16383 * @param {HTMLElement} el the element to check
16384 * @return {boolean} true if the element looks usable
16387 verifyEl: function(el) {
16392 parent = el.offsetParent;
16395 parent = el.offsetParent;
16406 * Returns a Region object containing the drag and drop element's position
16407 * and size, including the padding configured for it
16408 * @method getLocation
16409 * @param {DragDrop} oDD the drag and drop object to get the
16411 * @return {Roo.lib.Region} a Region object representing the total area
16412 * the element occupies, including any padding
16413 * the instance is configured for.
16416 getLocation: function(oDD) {
16417 if (! this.isTypeOfDD(oDD)) {
16421 var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
16424 pos= Roo.lib.Dom.getXY(el);
16432 x2 = x1 + el.offsetWidth;
16434 y2 = y1 + el.offsetHeight;
16436 t = y1 - oDD.padding[0];
16437 r = x2 + oDD.padding[1];
16438 b = y2 + oDD.padding[2];
16439 l = x1 - oDD.padding[3];
16441 return new Roo.lib.Region( t, r, b, l );
16445 * Checks the cursor location to see if it over the target
16446 * @method isOverTarget
16447 * @param {Roo.lib.Point} pt The point to evaluate
16448 * @param {DragDrop} oTarget the DragDrop object we are inspecting
16449 * @return {boolean} true if the mouse is over the target
16453 isOverTarget: function(pt, oTarget, intersect) {
16454 // use cache if available
16455 var loc = this.locationCache[oTarget.id];
16456 if (!loc || !this.useCache) {
16457 loc = this.getLocation(oTarget);
16458 this.locationCache[oTarget.id] = loc;
16466 oTarget.cursorIsOver = loc.contains( pt );
16468 // DragDrop is using this as a sanity check for the initial mousedown
16469 // in this case we are done. In POINT mode, if the drag obj has no
16470 // contraints, we are also done. Otherwise we need to evaluate the
16471 // location of the target as related to the actual location of the
16472 // dragged element.
16473 var dc = this.dragCurrent;
16474 if (!dc || !dc.getTargetCoord ||
16475 (!intersect && !dc.constrainX && !dc.constrainY)) {
16476 return oTarget.cursorIsOver;
16479 oTarget.overlap = null;
16481 // Get the current location of the drag element, this is the
16482 // location of the mouse event less the delta that represents
16483 // where the original mousedown happened on the element. We
16484 // need to consider constraints and ticks as well.
16485 var pos = dc.getTargetCoord(pt.x, pt.y);
16487 var el = dc.getDragEl();
16488 var curRegion = new Roo.lib.Region( pos.y,
16489 pos.x + el.offsetWidth,
16490 pos.y + el.offsetHeight,
16493 var overlap = curRegion.intersect(loc);
16496 oTarget.overlap = overlap;
16497 return (intersect) ? true : oTarget.cursorIsOver;
16504 * unload event handler
16505 * @method _onUnload
16509 _onUnload: function(e, me) {
16510 Roo.dd.DragDropMgr.unregAll();
16514 * Cleans up the drag and drop events and objects.
16519 unregAll: function() {
16521 if (this.dragCurrent) {
16523 this.dragCurrent = null;
16526 this._execOnAll("unreg", []);
16528 for (i in this.elementCache) {
16529 delete this.elementCache[i];
16532 this.elementCache = {};
16537 * A cache of DOM elements
16538 * @property elementCache
16545 * Get the wrapper for the DOM element specified
16546 * @method getElWrapper
16547 * @param {String} id the id of the element to get
16548 * @return {Roo.dd.DDM.ElementWrapper} the wrapped element
16550 * @deprecated This wrapper isn't that useful
16553 getElWrapper: function(id) {
16554 var oWrapper = this.elementCache[id];
16555 if (!oWrapper || !oWrapper.el) {
16556 oWrapper = this.elementCache[id] =
16557 new this.ElementWrapper(Roo.getDom(id));
16563 * Returns the actual DOM element
16564 * @method getElement
16565 * @param {String} id the id of the elment to get
16566 * @return {Object} The element
16567 * @deprecated use Roo.getDom instead
16570 getElement: function(id) {
16571 return Roo.getDom(id);
16575 * Returns the style property for the DOM element (i.e.,
16576 * document.getElById(id).style)
16578 * @param {String} id the id of the elment to get
16579 * @return {Object} The style property of the element
16580 * @deprecated use Roo.getDom instead
16583 getCss: function(id) {
16584 var el = Roo.getDom(id);
16585 return (el) ? el.style : null;
16589 * Inner class for cached elements
16590 * @class DragDropMgr.ElementWrapper
16595 ElementWrapper: function(el) {
16600 this.el = el || null;
16605 this.id = this.el && el.id;
16607 * A reference to the style property
16610 this.css = this.el && el.style;
16614 * Returns the X position of an html element
16616 * @param el the element for which to get the position
16617 * @return {int} the X coordinate
16619 * @deprecated use Roo.lib.Dom.getX instead
16622 getPosX: function(el) {
16623 return Roo.lib.Dom.getX(el);
16627 * Returns the Y position of an html element
16629 * @param el the element for which to get the position
16630 * @return {int} the Y coordinate
16631 * @deprecated use Roo.lib.Dom.getY instead
16634 getPosY: function(el) {
16635 return Roo.lib.Dom.getY(el);
16639 * Swap two nodes. In IE, we use the native method, for others we
16640 * emulate the IE behavior
16642 * @param n1 the first node to swap
16643 * @param n2 the other node to swap
16646 swapNode: function(n1, n2) {
16650 var p = n2.parentNode;
16651 var s = n2.nextSibling;
16654 p.insertBefore(n1, n2);
16655 } else if (n2 == n1.nextSibling) {
16656 p.insertBefore(n2, n1);
16658 n1.parentNode.replaceChild(n2, n1);
16659 p.insertBefore(n1, s);
16665 * Returns the current scroll position
16666 * @method getScroll
16670 getScroll: function () {
16671 var t, l, dde=document.documentElement, db=document.body;
16672 if (dde && (dde.scrollTop || dde.scrollLeft)) {
16674 l = dde.scrollLeft;
16681 return { top: t, left: l };
16685 * Returns the specified element style property
16687 * @param {HTMLElement} el the element
16688 * @param {string} styleProp the style property
16689 * @return {string} The value of the style property
16690 * @deprecated use Roo.lib.Dom.getStyle
16693 getStyle: function(el, styleProp) {
16694 return Roo.fly(el).getStyle(styleProp);
16698 * Gets the scrollTop
16699 * @method getScrollTop
16700 * @return {int} the document's scrollTop
16703 getScrollTop: function () { return this.getScroll().top; },
16706 * Gets the scrollLeft
16707 * @method getScrollLeft
16708 * @return {int} the document's scrollTop
16711 getScrollLeft: function () { return this.getScroll().left; },
16714 * Sets the x/y position of an element to the location of the
16717 * @param {HTMLElement} moveEl The element to move
16718 * @param {HTMLElement} targetEl The position reference element
16721 moveToEl: function (moveEl, targetEl) {
16722 var aCoord = Roo.lib.Dom.getXY(targetEl);
16723 Roo.lib.Dom.setXY(moveEl, aCoord);
16727 * Numeric array sort function
16728 * @method numericSort
16731 numericSort: function(a, b) { return (a - b); },
16735 * @property _timeoutCount
16742 * Trying to make the load order less important. Without this we get
16743 * an error if this file is loaded before the Event Utility.
16744 * @method _addListeners
16748 _addListeners: function() {
16749 var DDM = Roo.dd.DDM;
16750 if ( Roo.lib.Event && document ) {
16753 if (DDM._timeoutCount > 2000) {
16755 setTimeout(DDM._addListeners, 10);
16756 if (document && document.body) {
16757 DDM._timeoutCount += 1;
16764 * Recursively searches the immediate parent and all child nodes for
16765 * the handle element in order to determine wheter or not it was
16767 * @method handleWasClicked
16768 * @param node the html element to inspect
16771 handleWasClicked: function(node, id) {
16772 if (this.isHandle(id, node.id)) {
16775 // check to see if this is a text node child of the one we want
16776 var p = node.parentNode;
16779 if (this.isHandle(id, p.id)) {
16794 // shorter alias, save a few bytes
16795 Roo.dd.DDM = Roo.dd.DragDropMgr;
16796 Roo.dd.DDM._addListeners();
16800 * Ext JS Library 1.1.1
16801 * Copyright(c) 2006-2007, Ext JS, LLC.
16803 * Originally Released Under LGPL - original licence link has changed is not relivant.
16806 * <script type="text/javascript">
16811 * A DragDrop implementation where the linked element follows the
16812 * mouse cursor during a drag.
16813 * @extends Roo.dd.DragDrop
16815 * @param {String} id the id of the linked element
16816 * @param {String} sGroup the group of related DragDrop items
16817 * @param {object} config an object containing configurable attributes
16818 * Valid properties for DD:
16821 Roo.dd.DD = function(id, sGroup, config) {
16823 this.init(id, sGroup, config);
16827 Roo.extend(Roo.dd.DD, Roo.dd.DragDrop, {
16830 * When set to true, the utility automatically tries to scroll the browser
16831 * window wehn a drag and drop element is dragged near the viewport boundary.
16832 * Defaults to true.
16839 * Sets the pointer offset to the distance between the linked element's top
16840 * left corner and the location the element was clicked
16841 * @method autoOffset
16842 * @param {int} iPageX the X coordinate of the click
16843 * @param {int} iPageY the Y coordinate of the click
16845 autoOffset: function(iPageX, iPageY) {
16846 var x = iPageX - this.startPageX;
16847 var y = iPageY - this.startPageY;
16848 this.setDelta(x, y);
16852 * Sets the pointer offset. You can call this directly to force the
16853 * offset to be in a particular location (e.g., pass in 0,0 to set it
16854 * to the center of the object)
16856 * @param {int} iDeltaX the distance from the left
16857 * @param {int} iDeltaY the distance from the top
16859 setDelta: function(iDeltaX, iDeltaY) {
16860 this.deltaX = iDeltaX;
16861 this.deltaY = iDeltaY;
16865 * Sets the drag element to the location of the mousedown or click event,
16866 * maintaining the cursor location relative to the location on the element
16867 * that was clicked. Override this if you want to place the element in a
16868 * location other than where the cursor is.
16869 * @method setDragElPos
16870 * @param {int} iPageX the X coordinate of the mousedown or drag event
16871 * @param {int} iPageY the Y coordinate of the mousedown or drag event
16873 setDragElPos: function(iPageX, iPageY) {
16874 // the first time we do this, we are going to check to make sure
16875 // the element has css positioning
16877 var el = this.getDragEl();
16878 this.alignElWithMouse(el, iPageX, iPageY);
16882 * Sets the element to the location of the mousedown or click event,
16883 * maintaining the cursor location relative to the location on the element
16884 * that was clicked. Override this if you want to place the element in a
16885 * location other than where the cursor is.
16886 * @method alignElWithMouse
16887 * @param {HTMLElement} el the element to move
16888 * @param {int} iPageX the X coordinate of the mousedown or drag event
16889 * @param {int} iPageY the Y coordinate of the mousedown or drag event
16891 alignElWithMouse: function(el, iPageX, iPageY) {
16892 var oCoord = this.getTargetCoord(iPageX, iPageY);
16893 var fly = el.dom ? el : Roo.fly(el);
16894 if (!this.deltaSetXY) {
16895 var aCoord = [oCoord.x, oCoord.y];
16897 var newLeft = fly.getLeft(true);
16898 var newTop = fly.getTop(true);
16899 this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
16901 fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
16904 this.cachePosition(oCoord.x, oCoord.y);
16905 this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
16910 * Saves the most recent position so that we can reset the constraints and
16911 * tick marks on-demand. We need to know this so that we can calculate the
16912 * number of pixels the element is offset from its original position.
16913 * @method cachePosition
16914 * @param iPageX the current x position (optional, this just makes it so we
16915 * don't have to look it up again)
16916 * @param iPageY the current y position (optional, this just makes it so we
16917 * don't have to look it up again)
16919 cachePosition: function(iPageX, iPageY) {
16921 this.lastPageX = iPageX;
16922 this.lastPageY = iPageY;
16924 var aCoord = Roo.lib.Dom.getXY(this.getEl());
16925 this.lastPageX = aCoord[0];
16926 this.lastPageY = aCoord[1];
16931 * Auto-scroll the window if the dragged object has been moved beyond the
16932 * visible window boundary.
16933 * @method autoScroll
16934 * @param {int} x the drag element's x position
16935 * @param {int} y the drag element's y position
16936 * @param {int} h the height of the drag element
16937 * @param {int} w the width of the drag element
16940 autoScroll: function(x, y, h, w) {
16943 // The client height
16944 var clientH = Roo.lib.Dom.getViewWidth();
16946 // The client width
16947 var clientW = Roo.lib.Dom.getViewHeight();
16949 // The amt scrolled down
16950 var st = this.DDM.getScrollTop();
16952 // The amt scrolled right
16953 var sl = this.DDM.getScrollLeft();
16955 // Location of the bottom of the element
16958 // Location of the right of the element
16961 // The distance from the cursor to the bottom of the visible area,
16962 // adjusted so that we don't scroll if the cursor is beyond the
16963 // element drag constraints
16964 var toBot = (clientH + st - y - this.deltaY);
16966 // The distance from the cursor to the right of the visible area
16967 var toRight = (clientW + sl - x - this.deltaX);
16970 // How close to the edge the cursor must be before we scroll
16971 // var thresh = (document.all) ? 100 : 40;
16974 // How many pixels to scroll per autoscroll op. This helps to reduce
16975 // clunky scrolling. IE is more sensitive about this ... it needs this
16976 // value to be higher.
16977 var scrAmt = (document.all) ? 80 : 30;
16979 // Scroll down if we are near the bottom of the visible page and the
16980 // obj extends below the crease
16981 if ( bot > clientH && toBot < thresh ) {
16982 window.scrollTo(sl, st + scrAmt);
16985 // Scroll up if the window is scrolled down and the top of the object
16986 // goes above the top border
16987 if ( y < st && st > 0 && y - st < thresh ) {
16988 window.scrollTo(sl, st - scrAmt);
16991 // Scroll right if the obj is beyond the right border and the cursor is
16992 // near the border.
16993 if ( right > clientW && toRight < thresh ) {
16994 window.scrollTo(sl + scrAmt, st);
16997 // Scroll left if the window has been scrolled to the right and the obj
16998 // extends past the left border
16999 if ( x < sl && sl > 0 && x - sl < thresh ) {
17000 window.scrollTo(sl - scrAmt, st);
17006 * Finds the location the element should be placed if we want to move
17007 * it to where the mouse location less the click offset would place us.
17008 * @method getTargetCoord
17009 * @param {int} iPageX the X coordinate of the click
17010 * @param {int} iPageY the Y coordinate of the click
17011 * @return an object that contains the coordinates (Object.x and Object.y)
17014 getTargetCoord: function(iPageX, iPageY) {
17017 var x = iPageX - this.deltaX;
17018 var y = iPageY - this.deltaY;
17020 if (this.constrainX) {
17021 if (x < this.minX) { x = this.minX; }
17022 if (x > this.maxX) { x = this.maxX; }
17025 if (this.constrainY) {
17026 if (y < this.minY) { y = this.minY; }
17027 if (y > this.maxY) { y = this.maxY; }
17030 x = this.getTick(x, this.xTicks);
17031 y = this.getTick(y, this.yTicks);
17038 * Sets up config options specific to this class. Overrides
17039 * Roo.dd.DragDrop, but all versions of this method through the
17040 * inheritance chain are called
17042 applyConfig: function() {
17043 Roo.dd.DD.superclass.applyConfig.call(this);
17044 this.scroll = (this.config.scroll !== false);
17048 * Event that fires prior to the onMouseDown event. Overrides
17051 b4MouseDown: function(e) {
17052 // this.resetConstraints();
17053 this.autoOffset(e.getPageX(),
17058 * Event that fires prior to the onDrag event. Overrides
17061 b4Drag: function(e) {
17062 this.setDragElPos(e.getPageX(),
17066 toString: function() {
17067 return ("DD " + this.id);
17070 //////////////////////////////////////////////////////////////////////////
17071 // Debugging ygDragDrop events that can be overridden
17072 //////////////////////////////////////////////////////////////////////////
17074 startDrag: function(x, y) {
17077 onDrag: function(e) {
17080 onDragEnter: function(e, id) {
17083 onDragOver: function(e, id) {
17086 onDragOut: function(e, id) {
17089 onDragDrop: function(e, id) {
17092 endDrag: function(e) {
17099 * Ext JS Library 1.1.1
17100 * Copyright(c) 2006-2007, Ext JS, LLC.
17102 * Originally Released Under LGPL - original licence link has changed is not relivant.
17105 * <script type="text/javascript">
17109 * @class Roo.dd.DDProxy
17110 * A DragDrop implementation that inserts an empty, bordered div into
17111 * the document that follows the cursor during drag operations. At the time of
17112 * the click, the frame div is resized to the dimensions of the linked html
17113 * element, and moved to the exact location of the linked element.
17115 * References to the "frame" element refer to the single proxy element that
17116 * was created to be dragged in place of all DDProxy elements on the
17119 * @extends Roo.dd.DD
17121 * @param {String} id the id of the linked html element
17122 * @param {String} sGroup the group of related DragDrop objects
17123 * @param {object} config an object containing configurable attributes
17124 * Valid properties for DDProxy in addition to those in DragDrop:
17125 * resizeFrame, centerFrame, dragElId
17127 Roo.dd.DDProxy = function(id, sGroup, config) {
17129 this.init(id, sGroup, config);
17135 * The default drag frame div id
17136 * @property Roo.dd.DDProxy.dragElId
17140 Roo.dd.DDProxy.dragElId = "ygddfdiv";
17142 Roo.extend(Roo.dd.DDProxy, Roo.dd.DD, {
17145 * By default we resize the drag frame to be the same size as the element
17146 * we want to drag (this is to get the frame effect). We can turn it off
17147 * if we want a different behavior.
17148 * @property resizeFrame
17154 * By default the frame is positioned exactly where the drag element is, so
17155 * we use the cursor offset provided by Roo.dd.DD. Another option that works only if
17156 * you do not have constraints on the obj is to have the drag frame centered
17157 * around the cursor. Set centerFrame to true for this effect.
17158 * @property centerFrame
17161 centerFrame: false,
17164 * Creates the proxy element if it does not yet exist
17165 * @method createFrame
17167 createFrame: function() {
17169 var body = document.body;
17171 if (!body || !body.firstChild) {
17172 setTimeout( function() { self.createFrame(); }, 50 );
17176 var div = this.getDragEl();
17179 div = document.createElement("div");
17180 div.id = this.dragElId;
17183 s.position = "absolute";
17184 s.visibility = "hidden";
17186 s.border = "2px solid #aaa";
17189 // appendChild can blow up IE if invoked prior to the window load event
17190 // while rendering a table. It is possible there are other scenarios
17191 // that would cause this to happen as well.
17192 body.insertBefore(div, body.firstChild);
17197 * Initialization for the drag frame element. Must be called in the
17198 * constructor of all subclasses
17199 * @method initFrame
17201 initFrame: function() {
17202 this.createFrame();
17205 applyConfig: function() {
17206 Roo.dd.DDProxy.superclass.applyConfig.call(this);
17208 this.resizeFrame = (this.config.resizeFrame !== false);
17209 this.centerFrame = (this.config.centerFrame);
17210 this.setDragElId(this.config.dragElId || Roo.dd.DDProxy.dragElId);
17214 * Resizes the drag frame to the dimensions of the clicked object, positions
17215 * it over the object, and finally displays it
17216 * @method showFrame
17217 * @param {int} iPageX X click position
17218 * @param {int} iPageY Y click position
17221 showFrame: function(iPageX, iPageY) {
17222 var el = this.getEl();
17223 var dragEl = this.getDragEl();
17224 var s = dragEl.style;
17226 this._resizeProxy();
17228 if (this.centerFrame) {
17229 this.setDelta( Math.round(parseInt(s.width, 10)/2),
17230 Math.round(parseInt(s.height, 10)/2) );
17233 this.setDragElPos(iPageX, iPageY);
17235 Roo.fly(dragEl).show();
17239 * The proxy is automatically resized to the dimensions of the linked
17240 * element when a drag is initiated, unless resizeFrame is set to false
17241 * @method _resizeProxy
17244 _resizeProxy: function() {
17245 if (this.resizeFrame) {
17246 var el = this.getEl();
17247 Roo.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
17251 // overrides Roo.dd.DragDrop
17252 b4MouseDown: function(e) {
17253 var x = e.getPageX();
17254 var y = e.getPageY();
17255 this.autoOffset(x, y);
17256 this.setDragElPos(x, y);
17259 // overrides Roo.dd.DragDrop
17260 b4StartDrag: function(x, y) {
17261 // show the drag frame
17262 this.showFrame(x, y);
17265 // overrides Roo.dd.DragDrop
17266 b4EndDrag: function(e) {
17267 Roo.fly(this.getDragEl()).hide();
17270 // overrides Roo.dd.DragDrop
17271 // By default we try to move the element to the last location of the frame.
17272 // This is so that the default behavior mirrors that of Roo.dd.DD.
17273 endDrag: function(e) {
17275 var lel = this.getEl();
17276 var del = this.getDragEl();
17278 // Show the drag frame briefly so we can get its position
17279 del.style.visibility = "";
17282 // Hide the linked element before the move to get around a Safari
17284 lel.style.visibility = "hidden";
17285 Roo.dd.DDM.moveToEl(lel, del);
17286 del.style.visibility = "hidden";
17287 lel.style.visibility = "";
17292 beforeMove : function(){
17296 afterDrag : function(){
17300 toString: function() {
17301 return ("DDProxy " + this.id);
17307 * Ext JS Library 1.1.1
17308 * Copyright(c) 2006-2007, Ext JS, LLC.
17310 * Originally Released Under LGPL - original licence link has changed is not relivant.
17313 * <script type="text/javascript">
17317 * @class Roo.dd.DDTarget
17318 * A DragDrop implementation that does not move, but can be a drop
17319 * target. You would get the same result by simply omitting implementation
17320 * for the event callbacks, but this way we reduce the processing cost of the
17321 * event listener and the callbacks.
17322 * @extends Roo.dd.DragDrop
17324 * @param {String} id the id of the element that is a drop target
17325 * @param {String} sGroup the group of related DragDrop objects
17326 * @param {object} config an object containing configurable attributes
17327 * Valid properties for DDTarget in addition to those in
17331 Roo.dd.DDTarget = function(id, sGroup, config) {
17333 this.initTarget(id, sGroup, config);
17337 // Roo.dd.DDTarget.prototype = new Roo.dd.DragDrop();
17338 Roo.extend(Roo.dd.DDTarget, Roo.dd.DragDrop, {
17339 toString: function() {
17340 return ("DDTarget " + this.id);
17345 * Ext JS Library 1.1.1
17346 * Copyright(c) 2006-2007, Ext JS, LLC.
17348 * Originally Released Under LGPL - original licence link has changed is not relivant.
17351 * <script type="text/javascript">
17356 * @class Roo.dd.ScrollManager
17357 * Provides automatic scrolling of overflow regions in the page during drag operations.<br><br>
17358 * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
17361 Roo.dd.ScrollManager = function(){
17362 var ddm = Roo.dd.DragDropMgr;
17367 var onStop = function(e){
17372 var triggerRefresh = function(){
17373 if(ddm.dragCurrent){
17374 ddm.refreshCache(ddm.dragCurrent.groups);
17378 var doScroll = function(){
17379 if(ddm.dragCurrent){
17380 var dds = Roo.dd.ScrollManager;
17382 if(proc.el.scroll(proc.dir, dds.increment)){
17386 proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
17391 var clearProc = function(){
17393 clearInterval(proc.id);
17400 var startProc = function(el, dir){
17404 proc.id = setInterval(doScroll, Roo.dd.ScrollManager.frequency);
17407 var onFire = function(e, isDrop){
17408 if(isDrop || !ddm.dragCurrent){ return; }
17409 var dds = Roo.dd.ScrollManager;
17410 if(!dragEl || dragEl != ddm.dragCurrent){
17411 dragEl = ddm.dragCurrent;
17412 // refresh regions on drag start
17413 dds.refreshCache();
17416 var xy = Roo.lib.Event.getXY(e);
17417 var pt = new Roo.lib.Point(xy[0], xy[1]);
17418 for(var id in els){
17419 var el = els[id], r = el._region;
17420 if(r && r.contains(pt) && el.isScrollable()){
17421 if(r.bottom - pt.y <= dds.thresh){
17423 startProc(el, "down");
17426 }else if(r.right - pt.x <= dds.thresh){
17428 startProc(el, "left");
17431 }else if(pt.y - r.top <= dds.thresh){
17433 startProc(el, "up");
17436 }else if(pt.x - r.left <= dds.thresh){
17438 startProc(el, "right");
17447 ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
17448 ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
17452 * Registers new overflow element(s) to auto scroll
17453 * @param {String/HTMLElement/Element/Array} el The id of or the element to be scrolled or an array of either
17455 register : function(el){
17456 if(el instanceof Array){
17457 for(var i = 0, len = el.length; i < len; i++) {
17458 this.register(el[i]);
17467 * Unregisters overflow element(s) so they are no longer scrolled
17468 * @param {String/HTMLElement/Element/Array} el The id of or the element to be removed or an array of either
17470 unregister : function(el){
17471 if(el instanceof Array){
17472 for(var i = 0, len = el.length; i < len; i++) {
17473 this.unregister(el[i]);
17482 * The number of pixels from the edge of a container the pointer needs to be to
17483 * trigger scrolling (defaults to 25)
17489 * The number of pixels to scroll in each scroll increment (defaults to 50)
17495 * The frequency of scrolls in milliseconds (defaults to 500)
17501 * True to animate the scroll (defaults to true)
17507 * The animation duration in seconds -
17508 * MUST BE less than Roo.dd.ScrollManager.frequency! (defaults to .4)
17514 * Manually trigger a cache refresh.
17516 refreshCache : function(){
17517 for(var id in els){
17518 if(typeof els[id] == 'object'){ // for people extending the object prototype
17519 els[id]._region = els[id].getRegion();
17526 * Ext JS Library 1.1.1
17527 * Copyright(c) 2006-2007, Ext JS, LLC.
17529 * Originally Released Under LGPL - original licence link has changed is not relivant.
17532 * <script type="text/javascript">
17537 * @class Roo.dd.Registry
17538 * Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either
17539 * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
17542 Roo.dd.Registry = function(){
17545 var autoIdSeed = 0;
17547 var getId = function(el, autogen){
17548 if(typeof el == "string"){
17552 if(!id && autogen !== false){
17553 id = "roodd-" + (++autoIdSeed);
17561 * Register a drag drop element
17562 * @param {String|HTMLElement} element The id or DOM node to register
17563 * @param {Object} data (optional) A custom data object that will be passed between the elements that are involved
17564 * in drag drop operations. You can populate this object with any arbitrary properties that your own code
17565 * knows how to interpret, plus there are some specific properties known to the Registry that should be
17566 * populated in the data object (if applicable):
17568 Value Description<br />
17569 --------- ------------------------------------------<br />
17570 handles Array of DOM nodes that trigger dragging<br />
17571 for the element being registered<br />
17572 isHandle True if the element passed in triggers<br />
17573 dragging itself, else false
17576 register : function(el, data){
17578 if(typeof el == "string"){
17579 el = document.getElementById(el);
17582 elements[getId(el)] = data;
17583 if(data.isHandle !== false){
17584 handles[data.ddel.id] = data;
17587 var hs = data.handles;
17588 for(var i = 0, len = hs.length; i < len; i++){
17589 handles[getId(hs[i])] = data;
17595 * Unregister a drag drop element
17596 * @param {String|HTMLElement} element The id or DOM node to unregister
17598 unregister : function(el){
17599 var id = getId(el, false);
17600 var data = elements[id];
17602 delete elements[id];
17604 var hs = data.handles;
17605 for(var i = 0, len = hs.length; i < len; i++){
17606 delete handles[getId(hs[i], false)];
17613 * Returns the handle registered for a DOM Node by id
17614 * @param {String|HTMLElement} id The DOM node or id to look up
17615 * @return {Object} handle The custom handle data
17617 getHandle : function(id){
17618 if(typeof id != "string"){ // must be element?
17621 return handles[id];
17625 * Returns the handle that is registered for the DOM node that is the target of the event
17626 * @param {Event} e The event
17627 * @return {Object} handle The custom handle data
17629 getHandleFromEvent : function(e){
17630 var t = Roo.lib.Event.getTarget(e);
17631 return t ? handles[t.id] : null;
17635 * Returns a custom data object that is registered for a DOM node by id
17636 * @param {String|HTMLElement} id The DOM node or id to look up
17637 * @return {Object} data The custom data
17639 getTarget : function(id){
17640 if(typeof id != "string"){ // must be element?
17643 return elements[id];
17647 * Returns a custom data object that is registered for the DOM node that is the target of the event
17648 * @param {Event} e The event
17649 * @return {Object} data The custom data
17651 getTargetFromEvent : function(e){
17652 var t = Roo.lib.Event.getTarget(e);
17653 return t ? elements[t.id] || handles[t.id] : null;
17658 * Ext JS Library 1.1.1
17659 * Copyright(c) 2006-2007, Ext JS, LLC.
17661 * Originally Released Under LGPL - original licence link has changed is not relivant.
17664 * <script type="text/javascript">
17669 * @class Roo.dd.StatusProxy
17670 * A specialized drag proxy that supports a drop status icon, {@link Roo.Layer} styles and auto-repair. This is the
17671 * default drag proxy used by all Roo.dd components.
17673 * @param {Object} config
17675 Roo.dd.StatusProxy = function(config){
17676 Roo.apply(this, config);
17677 this.id = this.id || Roo.id();
17678 this.el = new Roo.Layer({
17680 id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
17681 {tag: "div", cls: "x-dd-drop-icon"},
17682 {tag: "div", cls: "x-dd-drag-ghost"}
17685 shadow: !config || config.shadow !== false
17687 this.ghost = Roo.get(this.el.dom.childNodes[1]);
17688 this.dropStatus = this.dropNotAllowed;
17691 Roo.dd.StatusProxy.prototype = {
17693 * @cfg {String} dropAllowed
17694 * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
17696 dropAllowed : "x-dd-drop-ok",
17698 * @cfg {String} dropNotAllowed
17699 * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
17701 dropNotAllowed : "x-dd-drop-nodrop",
17704 * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
17705 * over the current target element.
17706 * @param {String} cssClass The css class for the new drop status indicator image
17708 setStatus : function(cssClass){
17709 cssClass = cssClass || this.dropNotAllowed;
17710 if(this.dropStatus != cssClass){
17711 this.el.replaceClass(this.dropStatus, cssClass);
17712 this.dropStatus = cssClass;
17717 * Resets the status indicator to the default dropNotAllowed value
17718 * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
17720 reset : function(clearGhost){
17721 this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
17722 this.dropStatus = this.dropNotAllowed;
17724 this.ghost.update("");
17729 * Updates the contents of the ghost element
17730 * @param {String} html The html that will replace the current innerHTML of the ghost element
17732 update : function(html){
17733 if(typeof html == "string"){
17734 this.ghost.update(html);
17736 this.ghost.update("");
17737 html.style.margin = "0";
17738 this.ghost.dom.appendChild(html);
17740 // ensure float = none set?? cant remember why though.
17741 var el = this.ghost.dom.firstChild;
17743 Roo.fly(el).setStyle('float', 'none');
17748 * Returns the underlying proxy {@link Roo.Layer}
17749 * @return {Roo.Layer} el
17751 getEl : function(){
17756 * Returns the ghost element
17757 * @return {Roo.Element} el
17759 getGhost : function(){
17765 * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
17767 hide : function(clear){
17775 * Stops the repair animation if it's currently running
17778 if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
17784 * Displays this proxy
17791 * Force the Layer to sync its shadow and shim positions to the element
17798 * Causes the proxy to return to its position of origin via an animation. Should be called after an
17799 * invalid drop operation by the item being dragged.
17800 * @param {Array} xy The XY position of the element ([x, y])
17801 * @param {Function} callback The function to call after the repair is complete
17802 * @param {Object} scope The scope in which to execute the callback
17804 repair : function(xy, callback, scope){
17805 this.callback = callback;
17806 this.scope = scope;
17807 if(xy && this.animRepair !== false){
17808 this.el.addClass("x-dd-drag-repair");
17809 this.el.hideUnders(true);
17810 this.anim = this.el.shift({
17811 duration: this.repairDuration || .5,
17815 callback: this.afterRepair,
17819 this.afterRepair();
17824 afterRepair : function(){
17826 if(typeof this.callback == "function"){
17827 this.callback.call(this.scope || this);
17829 this.callback = null;
17834 * Ext JS Library 1.1.1
17835 * Copyright(c) 2006-2007, Ext JS, LLC.
17837 * Originally Released Under LGPL - original licence link has changed is not relivant.
17840 * <script type="text/javascript">
17844 * @class Roo.dd.DragSource
17845 * @extends Roo.dd.DDProxy
17846 * A simple class that provides the basic implementation needed to make any element draggable.
17848 * @param {String/HTMLElement/Element} el The container element
17849 * @param {Object} config
17851 Roo.dd.DragSource = function(el, config){
17852 this.el = Roo.get(el);
17853 this.dragData = {};
17855 Roo.apply(this, config);
17858 this.proxy = new Roo.dd.StatusProxy();
17861 Roo.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
17862 {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
17864 this.dragging = false;
17867 Roo.extend(Roo.dd.DragSource, Roo.dd.DDProxy, {
17869 * @cfg {String} dropAllowed
17870 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
17872 dropAllowed : "x-dd-drop-ok",
17874 * @cfg {String} dropNotAllowed
17875 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
17877 dropNotAllowed : "x-dd-drop-nodrop",
17880 * Returns the data object associated with this drag source
17881 * @return {Object} data An object containing arbitrary data
17883 getDragData : function(e){
17884 return this.dragData;
17888 onDragEnter : function(e, id){
17889 var target = Roo.dd.DragDropMgr.getDDById(id);
17890 this.cachedTarget = target;
17891 if(this.beforeDragEnter(target, e, id) !== false){
17892 if(target.isNotifyTarget){
17893 var status = target.notifyEnter(this, e, this.dragData);
17894 this.proxy.setStatus(status);
17896 this.proxy.setStatus(this.dropAllowed);
17899 if(this.afterDragEnter){
17901 * An empty function by default, but provided so that you can perform a custom action
17902 * when the dragged item enters the drop target by providing an implementation.
17903 * @param {Roo.dd.DragDrop} target The drop target
17904 * @param {Event} e The event object
17905 * @param {String} id The id of the dragged element
17906 * @method afterDragEnter
17908 this.afterDragEnter(target, e, id);
17914 * An empty function by default, but provided so that you can perform a custom action
17915 * before the dragged item enters the drop target and optionally cancel the onDragEnter.
17916 * @param {Roo.dd.DragDrop} target The drop target
17917 * @param {Event} e The event object
17918 * @param {String} id The id of the dragged element
17919 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
17921 beforeDragEnter : function(target, e, id){
17926 alignElWithMouse: function() {
17927 Roo.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
17932 onDragOver : function(e, id){
17933 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
17934 if(this.beforeDragOver(target, e, id) !== false){
17935 if(target.isNotifyTarget){
17936 var status = target.notifyOver(this, e, this.dragData);
17937 this.proxy.setStatus(status);
17940 if(this.afterDragOver){
17942 * An empty function by default, but provided so that you can perform a custom action
17943 * while the dragged item is over the drop target by providing an implementation.
17944 * @param {Roo.dd.DragDrop} target The drop target
17945 * @param {Event} e The event object
17946 * @param {String} id The id of the dragged element
17947 * @method afterDragOver
17949 this.afterDragOver(target, e, id);
17955 * An empty function by default, but provided so that you can perform a custom action
17956 * while the dragged item is over the drop target and optionally cancel the onDragOver.
17957 * @param {Roo.dd.DragDrop} target The drop target
17958 * @param {Event} e The event object
17959 * @param {String} id The id of the dragged element
17960 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
17962 beforeDragOver : function(target, e, id){
17967 onDragOut : function(e, id){
17968 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
17969 if(this.beforeDragOut(target, e, id) !== false){
17970 if(target.isNotifyTarget){
17971 target.notifyOut(this, e, this.dragData);
17973 this.proxy.reset();
17974 if(this.afterDragOut){
17976 * An empty function by default, but provided so that you can perform a custom action
17977 * after the dragged item is dragged out of the target without dropping.
17978 * @param {Roo.dd.DragDrop} target The drop target
17979 * @param {Event} e The event object
17980 * @param {String} id The id of the dragged element
17981 * @method afterDragOut
17983 this.afterDragOut(target, e, id);
17986 this.cachedTarget = null;
17990 * An empty function by default, but provided so that you can perform a custom action before the dragged
17991 * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
17992 * @param {Roo.dd.DragDrop} target The drop target
17993 * @param {Event} e The event object
17994 * @param {String} id The id of the dragged element
17995 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
17997 beforeDragOut : function(target, e, id){
18002 onDragDrop : function(e, id){
18003 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
18004 if(this.beforeDragDrop(target, e, id) !== false){
18005 if(target.isNotifyTarget){
18006 if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
18007 this.onValidDrop(target, e, id);
18009 this.onInvalidDrop(target, e, id);
18012 this.onValidDrop(target, e, id);
18015 if(this.afterDragDrop){
18017 * An empty function by default, but provided so that you can perform a custom action
18018 * after a valid drag drop has occurred by providing an implementation.
18019 * @param {Roo.dd.DragDrop} target The drop target
18020 * @param {Event} e The event object
18021 * @param {String} id The id of the dropped element
18022 * @method afterDragDrop
18024 this.afterDragDrop(target, e, id);
18027 delete this.cachedTarget;
18031 * An empty function by default, but provided so that you can perform a custom action before the dragged
18032 * item is dropped onto the target and optionally cancel the onDragDrop.
18033 * @param {Roo.dd.DragDrop} target The drop target
18034 * @param {Event} e The event object
18035 * @param {String} id The id of the dragged element
18036 * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
18038 beforeDragDrop : function(target, e, id){
18043 onValidDrop : function(target, e, id){
18045 if(this.afterValidDrop){
18047 * An empty function by default, but provided so that you can perform a custom action
18048 * after a valid drop has occurred by providing an implementation.
18049 * @param {Object} target The target DD
18050 * @param {Event} e The event object
18051 * @param {String} id The id of the dropped element
18052 * @method afterInvalidDrop
18054 this.afterValidDrop(target, e, id);
18059 getRepairXY : function(e, data){
18060 return this.el.getXY();
18064 onInvalidDrop : function(target, e, id){
18065 this.beforeInvalidDrop(target, e, id);
18066 if(this.cachedTarget){
18067 if(this.cachedTarget.isNotifyTarget){
18068 this.cachedTarget.notifyOut(this, e, this.dragData);
18070 this.cacheTarget = null;
18072 this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
18074 if(this.afterInvalidDrop){
18076 * An empty function by default, but provided so that you can perform a custom action
18077 * after an invalid drop has occurred by providing an implementation.
18078 * @param {Event} e The event object
18079 * @param {String} id The id of the dropped element
18080 * @method afterInvalidDrop
18082 this.afterInvalidDrop(e, id);
18087 afterRepair : function(){
18089 this.el.highlight(this.hlColor || "c3daf9");
18091 this.dragging = false;
18095 * An empty function by default, but provided so that you can perform a custom action after an invalid
18096 * drop has occurred.
18097 * @param {Roo.dd.DragDrop} target The drop target
18098 * @param {Event} e The event object
18099 * @param {String} id The id of the dragged element
18100 * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
18102 beforeInvalidDrop : function(target, e, id){
18107 handleMouseDown : function(e){
18108 if(this.dragging) {
18111 var data = this.getDragData(e);
18112 if(data && this.onBeforeDrag(data, e) !== false){
18113 this.dragData = data;
18115 Roo.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
18120 * An empty function by default, but provided so that you can perform a custom action before the initial
18121 * drag event begins and optionally cancel it.
18122 * @param {Object} data An object containing arbitrary data to be shared with drop targets
18123 * @param {Event} e The event object
18124 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
18126 onBeforeDrag : function(data, e){
18131 * An empty function by default, but provided so that you can perform a custom action once the initial
18132 * drag event has begun. The drag cannot be canceled from this function.
18133 * @param {Number} x The x position of the click on the dragged object
18134 * @param {Number} y The y position of the click on the dragged object
18136 onStartDrag : Roo.emptyFn,
18138 // private - YUI override
18139 startDrag : function(x, y){
18140 this.proxy.reset();
18141 this.dragging = true;
18142 this.proxy.update("");
18143 this.onInitDrag(x, y);
18148 onInitDrag : function(x, y){
18149 var clone = this.el.dom.cloneNode(true);
18150 clone.id = Roo.id(); // prevent duplicate ids
18151 this.proxy.update(clone);
18152 this.onStartDrag(x, y);
18157 * Returns the drag source's underlying {@link Roo.dd.StatusProxy}
18158 * @return {Roo.dd.StatusProxy} proxy The StatusProxy
18160 getProxy : function(){
18165 * Hides the drag source's {@link Roo.dd.StatusProxy}
18167 hideProxy : function(){
18169 this.proxy.reset(true);
18170 this.dragging = false;
18174 triggerCacheRefresh : function(){
18175 Roo.dd.DDM.refreshCache(this.groups);
18178 // private - override to prevent hiding
18179 b4EndDrag: function(e) {
18182 // private - override to prevent moving
18183 endDrag : function(e){
18184 this.onEndDrag(this.dragData, e);
18188 onEndDrag : function(data, e){
18191 // private - pin to cursor
18192 autoOffset : function(x, y) {
18193 this.setDelta(-12, -20);
18197 * Ext JS Library 1.1.1
18198 * Copyright(c) 2006-2007, Ext JS, LLC.
18200 * Originally Released Under LGPL - original licence link has changed is not relivant.
18203 * <script type="text/javascript">
18208 * @class Roo.dd.DropTarget
18209 * @extends Roo.dd.DDTarget
18210 * A simple class that provides the basic implementation needed to make any element a drop target that can have
18211 * draggable items dropped onto it. The drop has no effect until an implementation of notifyDrop is provided.
18213 * @param {String/HTMLElement/Element} el The container element
18214 * @param {Object} config
18216 Roo.dd.DropTarget = function(el, config){
18217 this.el = Roo.get(el);
18219 Roo.apply(this, config);
18221 if(this.containerScroll){
18222 Roo.dd.ScrollManager.register(this.el);
18225 Roo.dd.DropTarget.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
18230 Roo.extend(Roo.dd.DropTarget, Roo.dd.DDTarget, {
18232 * @cfg {String} overClass
18233 * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
18236 * @cfg {String} dropAllowed
18237 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
18239 dropAllowed : "x-dd-drop-ok",
18241 * @cfg {String} dropNotAllowed
18242 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
18244 dropNotAllowed : "x-dd-drop-nodrop",
18250 isNotifyTarget : true,
18253 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source is now over the
18254 * target. This default implementation adds the CSS class specified by overClass (if any) to the drop element
18255 * and returns the dropAllowed config value. This method should be overridden if drop validation is required.
18256 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
18257 * @param {Event} e The event
18258 * @param {Object} data An object containing arbitrary data supplied by the drag source
18259 * @return {String} status The CSS class that communicates the drop status back to the source so that the
18260 * underlying {@link Roo.dd.StatusProxy} can be updated
18262 notifyEnter : function(dd, e, data){
18263 if(this.overClass){
18264 this.el.addClass(this.overClass);
18266 return this.dropAllowed;
18270 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the target.
18271 * This method will be called on every mouse movement while the drag source is over the drop target.
18272 * This default implementation simply returns the dropAllowed config value.
18273 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
18274 * @param {Event} e The event
18275 * @param {Object} data An object containing arbitrary data supplied by the drag source
18276 * @return {String} status The CSS class that communicates the drop status back to the source so that the
18277 * underlying {@link Roo.dd.StatusProxy} can be updated
18279 notifyOver : function(dd, e, data){
18280 return this.dropAllowed;
18284 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source has been dragged
18285 * out of the target without dropping. This default implementation simply removes the CSS class specified by
18286 * overClass (if any) from the drop element.
18287 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
18288 * @param {Event} e The event
18289 * @param {Object} data An object containing arbitrary data supplied by the drag source
18291 notifyOut : function(dd, e, data){
18292 if(this.overClass){
18293 this.el.removeClass(this.overClass);
18298 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the dragged item has
18299 * been dropped on it. This method has no default implementation and returns false, so you must provide an
18300 * implementation that does something to process the drop event and returns true so that the drag source's
18301 * repair action does not run.
18302 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
18303 * @param {Event} e The event
18304 * @param {Object} data An object containing arbitrary data supplied by the drag source
18305 * @return {Boolean} True if the drop was valid, else false
18307 notifyDrop : function(dd, e, data){
18312 * Ext JS Library 1.1.1
18313 * Copyright(c) 2006-2007, Ext JS, LLC.
18315 * Originally Released Under LGPL - original licence link has changed is not relivant.
18318 * <script type="text/javascript">
18323 * @class Roo.dd.DragZone
18324 * @extends Roo.dd.DragSource
18325 * This class provides a container DD instance that proxies for multiple child node sources.<br />
18326 * By default, this class requires that draggable child nodes are registered with {@link Roo.dd.Registry}.
18328 * @param {String/HTMLElement/Element} el The container element
18329 * @param {Object} config
18331 Roo.dd.DragZone = function(el, config){
18332 Roo.dd.DragZone.superclass.constructor.call(this, el, config);
18333 if(this.containerScroll){
18334 Roo.dd.ScrollManager.register(this.el);
18338 Roo.extend(Roo.dd.DragZone, Roo.dd.DragSource, {
18340 * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
18341 * for auto scrolling during drag operations.
18344 * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
18345 * method after a failed drop (defaults to "c3daf9" - light blue)
18349 * Called when a mousedown occurs in this container. Looks in {@link Roo.dd.Registry}
18350 * for a valid target to drag based on the mouse down. Override this method
18351 * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
18352 * object has a "ddel" attribute (with an HTML Element) for other functions to work.
18353 * @param {EventObject} e The mouse down event
18354 * @return {Object} The dragData
18356 getDragData : function(e){
18357 return Roo.dd.Registry.getHandleFromEvent(e);
18361 * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
18362 * this.dragData.ddel
18363 * @param {Number} x The x position of the click on the dragged object
18364 * @param {Number} y The y position of the click on the dragged object
18365 * @return {Boolean} true to continue the drag, false to cancel
18367 onInitDrag : function(x, y){
18368 this.proxy.update(this.dragData.ddel.cloneNode(true));
18369 this.onStartDrag(x, y);
18374 * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel
18376 afterRepair : function(){
18378 Roo.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
18380 this.dragging = false;
18384 * Called before a repair of an invalid drop to get the XY to animate to. By default returns
18385 * the XY of this.dragData.ddel
18386 * @param {EventObject} e The mouse up event
18387 * @return {Array} The xy location (e.g. [100, 200])
18389 getRepairXY : function(e){
18390 return Roo.Element.fly(this.dragData.ddel).getXY();
18394 * Ext JS Library 1.1.1
18395 * Copyright(c) 2006-2007, Ext JS, LLC.
18397 * Originally Released Under LGPL - original licence link has changed is not relivant.
18400 * <script type="text/javascript">
18403 * @class Roo.dd.DropZone
18404 * @extends Roo.dd.DropTarget
18405 * This class provides a container DD instance that proxies for multiple child node targets.<br />
18406 * By default, this class requires that child nodes accepting drop are registered with {@link Roo.dd.Registry}.
18408 * @param {String/HTMLElement/Element} el The container element
18409 * @param {Object} config
18411 Roo.dd.DropZone = function(el, config){
18412 Roo.dd.DropZone.superclass.constructor.call(this, el, config);
18415 Roo.extend(Roo.dd.DropZone, Roo.dd.DropTarget, {
18417 * Returns a custom data object associated with the DOM node that is the target of the event. By default
18418 * this looks up the event target in the {@link Roo.dd.Registry}, although you can override this method to
18419 * provide your own custom lookup.
18420 * @param {Event} e The event
18421 * @return {Object} data The custom data
18423 getTargetFromEvent : function(e){
18424 return Roo.dd.Registry.getTargetFromEvent(e);
18428 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has entered a drop node
18429 * that it has registered. This method has no default implementation and should be overridden to provide
18430 * node-specific processing if necessary.
18431 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
18432 * {@link #getTargetFromEvent} for this node)
18433 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
18434 * @param {Event} e The event
18435 * @param {Object} data An object containing arbitrary data supplied by the drag source
18437 onNodeEnter : function(n, dd, e, data){
18442 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is over a drop node
18443 * that it has registered. The default implementation returns this.dropNotAllowed, so it should be
18444 * overridden to provide the proper feedback.
18445 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
18446 * {@link #getTargetFromEvent} for this node)
18447 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
18448 * @param {Event} e The event
18449 * @param {Object} data An object containing arbitrary data supplied by the drag source
18450 * @return {String} status The CSS class that communicates the drop status back to the source so that the
18451 * underlying {@link Roo.dd.StatusProxy} can be updated
18453 onNodeOver : function(n, dd, e, data){
18454 return this.dropAllowed;
18458 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dragged out of
18459 * the drop node without dropping. This method has no default implementation and should be overridden to provide
18460 * node-specific processing if necessary.
18461 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
18462 * {@link #getTargetFromEvent} for this node)
18463 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
18464 * @param {Event} e The event
18465 * @param {Object} data An object containing arbitrary data supplied by the drag source
18467 onNodeOut : function(n, dd, e, data){
18472 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped onto
18473 * the drop node. The default implementation returns false, so it should be overridden to provide the
18474 * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
18475 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
18476 * {@link #getTargetFromEvent} for this node)
18477 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
18478 * @param {Event} e The event
18479 * @param {Object} data An object containing arbitrary data supplied by the drag source
18480 * @return {Boolean} True if the drop was valid, else false
18482 onNodeDrop : function(n, dd, e, data){
18487 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is being dragged over it,
18488 * but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so
18489 * it should be overridden to provide the proper feedback if necessary.
18490 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
18491 * @param {Event} e The event
18492 * @param {Object} data An object containing arbitrary data supplied by the drag source
18493 * @return {String} status The CSS class that communicates the drop status back to the source so that the
18494 * underlying {@link Roo.dd.StatusProxy} can be updated
18496 onContainerOver : function(dd, e, data){
18497 return this.dropNotAllowed;
18501 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped on it,
18502 * but not on any of its registered drop nodes. The default implementation returns false, so it should be
18503 * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
18504 * be able to accept drops. It should return true when valid so that the drag source's repair action does not run.
18505 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
18506 * @param {Event} e The event
18507 * @param {Object} data An object containing arbitrary data supplied by the drag source
18508 * @return {Boolean} True if the drop was valid, else false
18510 onContainerDrop : function(dd, e, data){
18515 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source is now over
18516 * the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop
18517 * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
18518 * you should override this method and provide a custom implementation.
18519 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
18520 * @param {Event} e The event
18521 * @param {Object} data An object containing arbitrary data supplied by the drag source
18522 * @return {String} status The CSS class that communicates the drop status back to the source so that the
18523 * underlying {@link Roo.dd.StatusProxy} can be updated
18525 notifyEnter : function(dd, e, data){
18526 return this.dropNotAllowed;
18530 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the drop zone.
18531 * This method will be called on every mouse movement while the drag source is over the drop zone.
18532 * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
18533 * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
18534 * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
18535 * registered node, it will call {@link #onContainerOver}.
18536 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
18537 * @param {Event} e The event
18538 * @param {Object} data An object containing arbitrary data supplied by the drag source
18539 * @return {String} status The CSS class that communicates the drop status back to the source so that the
18540 * underlying {@link Roo.dd.StatusProxy} can be updated
18542 notifyOver : function(dd, e, data){
18543 var n = this.getTargetFromEvent(e);
18544 if(!n){ // not over valid drop target
18545 if(this.lastOverNode){
18546 this.onNodeOut(this.lastOverNode, dd, e, data);
18547 this.lastOverNode = null;
18549 return this.onContainerOver(dd, e, data);
18551 if(this.lastOverNode != n){
18552 if(this.lastOverNode){
18553 this.onNodeOut(this.lastOverNode, dd, e, data);
18555 this.onNodeEnter(n, dd, e, data);
18556 this.lastOverNode = n;
18558 return this.onNodeOver(n, dd, e, data);
18562 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source has been dragged
18563 * out of the zone without dropping. If the drag source is currently over a registered node, the notification
18564 * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
18565 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
18566 * @param {Event} e The event
18567 * @param {Object} data An object containing arbitrary data supplied by the drag zone
18569 notifyOut : function(dd, e, data){
18570 if(this.lastOverNode){
18571 this.onNodeOut(this.lastOverNode, dd, e, data);
18572 this.lastOverNode = null;
18577 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the dragged item has
18578 * been dropped on it. The drag zone will look up the target node based on the event passed in, and if there
18579 * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
18580 * otherwise it will call {@link #onContainerDrop}.
18581 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
18582 * @param {Event} e The event
18583 * @param {Object} data An object containing arbitrary data supplied by the drag source
18584 * @return {Boolean} True if the drop was valid, else false
18586 notifyDrop : function(dd, e, data){
18587 if(this.lastOverNode){
18588 this.onNodeOut(this.lastOverNode, dd, e, data);
18589 this.lastOverNode = null;
18591 var n = this.getTargetFromEvent(e);
18593 this.onNodeDrop(n, dd, e, data) :
18594 this.onContainerDrop(dd, e, data);
18598 triggerCacheRefresh : function(){
18599 Roo.dd.DDM.refreshCache(this.groups);
18603 * Ext JS Library 1.1.1
18604 * Copyright(c) 2006-2007, Ext JS, LLC.
18606 * Originally Released Under LGPL - original licence link has changed is not relivant.
18609 * <script type="text/javascript">
18614 * @class Roo.data.SortTypes
18616 * Defines the default sorting (casting?) comparison functions used when sorting data.
18618 Roo.data.SortTypes = {
18620 * Default sort that does nothing
18621 * @param {Mixed} s The value being converted
18622 * @return {Mixed} The comparison value
18624 none : function(s){
18629 * The regular expression used to strip tags
18633 stripTagsRE : /<\/?[^>]+>/gi,
18636 * Strips all HTML tags to sort on text only
18637 * @param {Mixed} s The value being converted
18638 * @return {String} The comparison value
18640 asText : function(s){
18641 return String(s).replace(this.stripTagsRE, "");
18645 * Strips all HTML tags to sort on text only - Case insensitive
18646 * @param {Mixed} s The value being converted
18647 * @return {String} The comparison value
18649 asUCText : function(s){
18650 return String(s).toUpperCase().replace(this.stripTagsRE, "");
18654 * Case insensitive string
18655 * @param {Mixed} s The value being converted
18656 * @return {String} The comparison value
18658 asUCString : function(s) {
18659 return String(s).toUpperCase();
18664 * @param {Mixed} s The value being converted
18665 * @return {Number} The comparison value
18667 asDate : function(s) {
18671 if(s instanceof Date){
18672 return s.getTime();
18674 return Date.parse(String(s));
18679 * @param {Mixed} s The value being converted
18680 * @return {Float} The comparison value
18682 asFloat : function(s) {
18683 var val = parseFloat(String(s).replace(/,/g, ""));
18684 if(isNaN(val)) val = 0;
18690 * @param {Mixed} s The value being converted
18691 * @return {Number} The comparison value
18693 asInt : function(s) {
18694 var val = parseInt(String(s).replace(/,/g, ""));
18695 if(isNaN(val)) val = 0;
18700 * Ext JS Library 1.1.1
18701 * Copyright(c) 2006-2007, Ext JS, LLC.
18703 * Originally Released Under LGPL - original licence link has changed is not relivant.
18706 * <script type="text/javascript">
18710 * @class Roo.data.Record
18711 * Instances of this class encapsulate both record <em>definition</em> information, and record
18712 * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
18713 * to access Records cached in an {@link Roo.data.Store} object.<br>
18715 * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
18716 * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
18719 * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
18721 * This constructor should not be used to create Record objects. Instead, use the constructor generated by
18722 * {@link #create}. The parameters are the same.
18723 * @param {Array} data An associative Array of data values keyed by the field name.
18724 * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
18725 * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
18726 * not specified an integer id is generated.
18728 Roo.data.Record = function(data, id){
18729 this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
18734 * Generate a constructor for a specific record layout.
18735 * @param {Array} o An Array of field definition objects which specify field names, and optionally,
18736 * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
18737 * Each field definition object may contain the following properties: <ul>
18738 * <li><b>name</b> : String<p style="margin-left:1em">The name by which the field is referenced within the Record. This is referenced by,
18739 * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
18740 * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
18741 * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
18742 * is being used, then this is a string containing the javascript expression to reference the data relative to
18743 * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
18744 * to the data item relative to the record element. If the mapping expression is the same as the field name,
18745 * this may be omitted.</p></li>
18746 * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
18747 * <ul><li>auto (Default, implies no conversion)</li>
18752 * <li>date</li></ul></p></li>
18753 * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
18754 * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
18755 * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
18756 * by the Reader into an object that will be stored in the Record. It is passed the
18757 * following parameters:<ul>
18758 * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
18760 * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
18762 * <br>usage:<br><pre><code>
18763 var TopicRecord = Roo.data.Record.create(
18764 {name: 'title', mapping: 'topic_title'},
18765 {name: 'author', mapping: 'username'},
18766 {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
18767 {name: 'lastPost', mapping: 'post_time', type: 'date'},
18768 {name: 'lastPoster', mapping: 'user2'},
18769 {name: 'excerpt', mapping: 'post_text'}
18772 var myNewRecord = new TopicRecord({
18773 title: 'Do my job please',
18776 lastPost: new Date(),
18777 lastPoster: 'Animal',
18778 excerpt: 'No way dude!'
18780 myStore.add(myNewRecord);
18785 Roo.data.Record.create = function(o){
18786 var f = function(){
18787 f.superclass.constructor.apply(this, arguments);
18789 Roo.extend(f, Roo.data.Record);
18790 var p = f.prototype;
18791 p.fields = new Roo.util.MixedCollection(false, function(field){
18794 for(var i = 0, len = o.length; i < len; i++){
18795 p.fields.add(new Roo.data.Field(o[i]));
18797 f.getField = function(name){
18798 return p.fields.get(name);
18803 Roo.data.Record.AUTO_ID = 1000;
18804 Roo.data.Record.EDIT = 'edit';
18805 Roo.data.Record.REJECT = 'reject';
18806 Roo.data.Record.COMMIT = 'commit';
18808 Roo.data.Record.prototype = {
18810 * Readonly flag - true if this record has been modified.
18819 join : function(store){
18820 this.store = store;
18824 * Set the named field to the specified value.
18825 * @param {String} name The name of the field to set.
18826 * @param {Object} value The value to set the field to.
18828 set : function(name, value){
18829 if(this.data[name] == value){
18833 if(!this.modified){
18834 this.modified = {};
18836 if(typeof this.modified[name] == 'undefined'){
18837 this.modified[name] = this.data[name];
18839 this.data[name] = value;
18841 this.store.afterEdit(this);
18846 * Get the value of the named field.
18847 * @param {String} name The name of the field to get the value of.
18848 * @return {Object} The value of the field.
18850 get : function(name){
18851 return this.data[name];
18855 beginEdit : function(){
18856 this.editing = true;
18857 this.modified = {};
18861 cancelEdit : function(){
18862 this.editing = false;
18863 delete this.modified;
18867 endEdit : function(){
18868 this.editing = false;
18869 if(this.dirty && this.store){
18870 this.store.afterEdit(this);
18875 * Usually called by the {@link Roo.data.Store} which owns the Record.
18876 * Rejects all changes made to the Record since either creation, or the last commit operation.
18877 * Modified fields are reverted to their original values.
18879 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
18880 * of reject operations.
18882 reject : function(){
18883 var m = this.modified;
18885 if(typeof m[n] != "function"){
18886 this.data[n] = m[n];
18889 this.dirty = false;
18890 delete this.modified;
18891 this.editing = false;
18893 this.store.afterReject(this);
18898 * Usually called by the {@link Roo.data.Store} which owns the Record.
18899 * Commits all changes made to the Record since either creation, or the last commit operation.
18901 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
18902 * of commit operations.
18904 commit : function(){
18905 this.dirty = false;
18906 delete this.modified;
18907 this.editing = false;
18909 this.store.afterCommit(this);
18914 hasError : function(){
18915 return this.error != null;
18919 clearError : function(){
18924 * Creates a copy of this record.
18925 * @param {String} id (optional) A new record id if you don't want to use this record's id
18928 copy : function(newId) {
18929 return new this.constructor(Roo.apply({}, this.data), newId || this.id);
18933 * Ext JS Library 1.1.1
18934 * Copyright(c) 2006-2007, Ext JS, LLC.
18936 * Originally Released Under LGPL - original licence link has changed is not relivant.
18939 * <script type="text/javascript">
18945 * @class Roo.data.Store
18946 * @extends Roo.util.Observable
18947 * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
18948 * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
18950 * A Store object uses an implementation of {@link Roo.data.DataProxy} to access a data object unless you call loadData() directly and pass in your data. The Store object
18951 * has no knowledge of the format of the data returned by the Proxy.<br>
18953 * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
18954 * instances from the data object. These records are cached and made available through accessor functions.
18956 * Creates a new Store.
18957 * @param {Object} config A config object containing the objects needed for the Store to access data,
18958 * and read the data into Records.
18960 Roo.data.Store = function(config){
18961 this.data = new Roo.util.MixedCollection(false);
18962 this.data.getKey = function(o){
18965 this.baseParams = {};
18967 this.paramNames = {
18974 if(config && config.data){
18975 this.inlineData = config.data;
18976 delete config.data;
18979 Roo.apply(this, config);
18981 if(this.reader){ // reader passed
18982 this.reader = Roo.factory(this.reader, Roo.data);
18983 this.reader.xmodule = this.xmodule || false;
18984 if(!this.recordType){
18985 this.recordType = this.reader.recordType;
18987 if(this.reader.onMetaChange){
18988 this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
18992 if(this.recordType){
18993 this.fields = this.recordType.prototype.fields;
18995 this.modified = [];
18999 * @event datachanged
19000 * Fires when the data cache has changed, and a widget which is using this Store
19001 * as a Record cache should refresh its view.
19002 * @param {Store} this
19004 datachanged : true,
19006 * @event metachange
19007 * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
19008 * @param {Store} this
19009 * @param {Object} meta The JSON metadata
19014 * Fires when Records have been added to the Store
19015 * @param {Store} this
19016 * @param {Roo.data.Record[]} records The array of Records added
19017 * @param {Number} index The index at which the record(s) were added
19022 * Fires when a Record has been removed from the Store
19023 * @param {Store} this
19024 * @param {Roo.data.Record} record The Record that was removed
19025 * @param {Number} index The index at which the record was removed
19030 * Fires when a Record has been updated
19031 * @param {Store} this
19032 * @param {Roo.data.Record} record The Record that was updated
19033 * @param {String} operation The update operation being performed. Value may be one of:
19035 Roo.data.Record.EDIT
19036 Roo.data.Record.REJECT
19037 Roo.data.Record.COMMIT
19043 * Fires when the data cache has been cleared.
19044 * @param {Store} this
19048 * @event beforeload
19049 * Fires before a request is made for a new data object. If the beforeload handler returns false
19050 * the load action will be canceled.
19051 * @param {Store} this
19052 * @param {Object} options The loading options that were specified (see {@link #load} for details)
19057 * Fires after a new set of Records has been loaded.
19058 * @param {Store} this
19059 * @param {Roo.data.Record[]} records The Records that were loaded
19060 * @param {Object} options The loading options that were specified (see {@link #load} for details)
19064 * @event loadexception
19065 * Fires if an exception occurs in the Proxy during loading.
19066 * Called with the signature of the Proxy's "loadexception" event.
19067 * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
19070 * @param {Object} return from JsonData.reader() - success, totalRecords, records
19071 * @param {Object} load options
19072 * @param {Object} jsonData from your request (normally this contains the Exception)
19074 loadexception : true
19078 this.proxy = Roo.factory(this.proxy, Roo.data);
19079 this.proxy.xmodule = this.xmodule || false;
19080 this.relayEvents(this.proxy, ["loadexception"]);
19082 this.sortToggle = {};
19084 Roo.data.Store.superclass.constructor.call(this);
19086 if(this.inlineData){
19087 this.loadData(this.inlineData);
19088 delete this.inlineData;
19091 Roo.extend(Roo.data.Store, Roo.util.Observable, {
19093 * @cfg {boolean} isLocal flag if data is locally available (and can be always looked up
19094 * without a remote query - used by combo/forms at present.
19098 * @cfg {Roo.data.DataProxy} proxy The Proxy object which provides access to a data object.
19101 * @cfg {Array} data Inline data to be loaded when the store is initialized.
19104 * @cfg {Roo.data.Reader} reader The Reader object which processes the data object and returns
19105 * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
19108 * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
19109 * on any HTTP request
19112 * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
19115 * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
19116 * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
19118 remoteSort : false,
19121 * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
19122 * loaded or when a record is removed. (defaults to false).
19124 pruneModifiedRecords : false,
19127 lastOptions : null,
19130 * Add Records to the Store and fires the add event.
19131 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
19133 add : function(records){
19134 records = [].concat(records);
19135 for(var i = 0, len = records.length; i < len; i++){
19136 records[i].join(this);
19138 var index = this.data.length;
19139 this.data.addAll(records);
19140 this.fireEvent("add", this, records, index);
19144 * Remove a Record from the Store and fires the remove event.
19145 * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
19147 remove : function(record){
19148 var index = this.data.indexOf(record);
19149 this.data.removeAt(index);
19150 if(this.pruneModifiedRecords){
19151 this.modified.remove(record);
19153 this.fireEvent("remove", this, record, index);
19157 * Remove all Records from the Store and fires the clear event.
19159 removeAll : function(){
19161 if(this.pruneModifiedRecords){
19162 this.modified = [];
19164 this.fireEvent("clear", this);
19168 * Inserts Records to the Store at the given index and fires the add event.
19169 * @param {Number} index The start index at which to insert the passed Records.
19170 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
19172 insert : function(index, records){
19173 records = [].concat(records);
19174 for(var i = 0, len = records.length; i < len; i++){
19175 this.data.insert(index, records[i]);
19176 records[i].join(this);
19178 this.fireEvent("add", this, records, index);
19182 * Get the index within the cache of the passed Record.
19183 * @param {Roo.data.Record} record The Roo.data.Record object to to find.
19184 * @return {Number} The index of the passed Record. Returns -1 if not found.
19186 indexOf : function(record){
19187 return this.data.indexOf(record);
19191 * Get the index within the cache of the Record with the passed id.
19192 * @param {String} id The id of the Record to find.
19193 * @return {Number} The index of the Record. Returns -1 if not found.
19195 indexOfId : function(id){
19196 return this.data.indexOfKey(id);
19200 * Get the Record with the specified id.
19201 * @param {String} id The id of the Record to find.
19202 * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
19204 getById : function(id){
19205 return this.data.key(id);
19209 * Get the Record at the specified index.
19210 * @param {Number} index The index of the Record to find.
19211 * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
19213 getAt : function(index){
19214 return this.data.itemAt(index);
19218 * Returns a range of Records between specified indices.
19219 * @param {Number} startIndex (optional) The starting index (defaults to 0)
19220 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
19221 * @return {Roo.data.Record[]} An array of Records
19223 getRange : function(start, end){
19224 return this.data.getRange(start, end);
19228 storeOptions : function(o){
19229 o = Roo.apply({}, o);
19232 this.lastOptions = o;
19236 * Loads the Record cache from the configured Proxy using the configured Reader.
19238 * If using remote paging, then the first load call must specify the <em>start</em>
19239 * and <em>limit</em> properties in the options.params property to establish the initial
19240 * position within the dataset, and the number of Records to cache on each read from the Proxy.
19242 * <strong>It is important to note that for remote data sources, loading is asynchronous,
19243 * and this call will return before the new data has been loaded. Perform any post-processing
19244 * in a callback function, or in a "load" event handler.</strong>
19246 * @param {Object} options An object containing properties which control loading options:<ul>
19247 * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
19248 * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
19249 * passed the following arguments:<ul>
19250 * <li>r : Roo.data.Record[]</li>
19251 * <li>options: Options object from the load call</li>
19252 * <li>success: Boolean success indicator</li></ul></li>
19253 * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
19254 * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
19257 load : function(options){
19258 options = options || {};
19259 if(this.fireEvent("beforeload", this, options) !== false){
19260 this.storeOptions(options);
19261 var p = Roo.apply(options.params || {}, this.baseParams);
19262 if(this.sortInfo && this.remoteSort){
19263 var pn = this.paramNames;
19264 p[pn["sort"]] = this.sortInfo.field;
19265 p[pn["dir"]] = this.sortInfo.direction;
19267 this.proxy.load(p, this.reader, this.loadRecords, this, options);
19272 * Reloads the Record cache from the configured Proxy using the configured Reader and
19273 * the options from the last load operation performed.
19274 * @param {Object} options (optional) An object containing properties which may override the options
19275 * used in the last load operation. See {@link #load} for details (defaults to null, in which case
19276 * the most recently used options are reused).
19278 reload : function(options){
19279 this.load(Roo.applyIf(options||{}, this.lastOptions));
19283 // Called as a callback by the Reader during a load operation.
19284 loadRecords : function(o, options, success){
19285 if(!o || success === false){
19286 if(success !== false){
19287 this.fireEvent("load", this, [], options);
19289 if(options.callback){
19290 options.callback.call(options.scope || this, [], options, false);
19294 // if data returned failure - throw an exception.
19295 if (o.success === false) {
19296 this.fireEvent("loadexception", this, o, options, this.reader.jsonData);
19299 var r = o.records, t = o.totalRecords || r.length;
19300 if(!options || options.add !== true){
19301 if(this.pruneModifiedRecords){
19302 this.modified = [];
19304 for(var i = 0, len = r.length; i < len; i++){
19308 this.data = this.snapshot;
19309 delete this.snapshot;
19312 this.data.addAll(r);
19313 this.totalLength = t;
19315 this.fireEvent("datachanged", this);
19317 this.totalLength = Math.max(t, this.data.length+r.length);
19320 this.fireEvent("load", this, r, options);
19321 if(options.callback){
19322 options.callback.call(options.scope || this, r, options, true);
19327 * Loads data from a passed data block. A Reader which understands the format of the data
19328 * must have been configured in the constructor.
19329 * @param {Object} data The data block from which to read the Records. The format of the data expected
19330 * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
19331 * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
19333 loadData : function(o, append){
19334 var r = this.reader.readRecords(o);
19335 this.loadRecords(r, {add: append}, true);
19339 * Gets the number of cached records.
19341 * <em>If using paging, this may not be the total size of the dataset. If the data object
19342 * used by the Reader contains the dataset size, then the getTotalCount() function returns
19343 * the data set size</em>
19345 getCount : function(){
19346 return this.data.length || 0;
19350 * Gets the total number of records in the dataset as returned by the server.
19352 * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
19353 * the dataset size</em>
19355 getTotalCount : function(){
19356 return this.totalLength || 0;
19360 * Returns the sort state of the Store as an object with two properties:
19362 field {String} The name of the field by which the Records are sorted
19363 direction {String} The sort order, "ASC" or "DESC"
19366 getSortState : function(){
19367 return this.sortInfo;
19371 applySort : function(){
19372 if(this.sortInfo && !this.remoteSort){
19373 var s = this.sortInfo, f = s.field;
19374 var st = this.fields.get(f).sortType;
19375 var fn = function(r1, r2){
19376 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
19377 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
19379 this.data.sort(s.direction, fn);
19380 if(this.snapshot && this.snapshot != this.data){
19381 this.snapshot.sort(s.direction, fn);
19387 * Sets the default sort column and order to be used by the next load operation.
19388 * @param {String} fieldName The name of the field to sort by.
19389 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
19391 setDefaultSort : function(field, dir){
19392 this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
19396 * Sort the Records.
19397 * If remote sorting is used, the sort is performed on the server, and the cache is
19398 * reloaded. If local sorting is used, the cache is sorted internally.
19399 * @param {String} fieldName The name of the field to sort by.
19400 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
19402 sort : function(fieldName, dir){
19403 var f = this.fields.get(fieldName);
19405 if(this.sortInfo && this.sortInfo.field == f.name){ // toggle sort dir
19406 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
19411 this.sortToggle[f.name] = dir;
19412 this.sortInfo = {field: f.name, direction: dir};
19413 if(!this.remoteSort){
19415 this.fireEvent("datachanged", this);
19417 this.load(this.lastOptions);
19422 * Calls the specified function for each of the Records in the cache.
19423 * @param {Function} fn The function to call. The Record is passed as the first parameter.
19424 * Returning <em>false</em> aborts and exits the iteration.
19425 * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
19427 each : function(fn, scope){
19428 this.data.each(fn, scope);
19432 * Gets all records modified since the last commit. Modified records are persisted across load operations
19433 * (e.g., during paging).
19434 * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
19436 getModifiedRecords : function(){
19437 return this.modified;
19441 createFilterFn : function(property, value, anyMatch){
19442 if(!value.exec){ // not a regex
19443 value = String(value);
19444 if(value.length == 0){
19447 value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
19449 return function(r){
19450 return value.test(r.data[property]);
19455 * Sums the value of <i>property</i> for each record between start and end and returns the result.
19456 * @param {String} property A field on your records
19457 * @param {Number} start The record index to start at (defaults to 0)
19458 * @param {Number} end The last record index to include (defaults to length - 1)
19459 * @return {Number} The sum
19461 sum : function(property, start, end){
19462 var rs = this.data.items, v = 0;
19463 start = start || 0;
19464 end = (end || end === 0) ? end : rs.length-1;
19466 for(var i = start; i <= end; i++){
19467 v += (rs[i].data[property] || 0);
19473 * Filter the records by a specified property.
19474 * @param {String} field A field on your records
19475 * @param {String/RegExp} value Either a string that the field
19476 * should start with or a RegExp to test against the field
19477 * @param {Boolean} anyMatch True to match any part not just the beginning
19479 filter : function(property, value, anyMatch){
19480 var fn = this.createFilterFn(property, value, anyMatch);
19481 return fn ? this.filterBy(fn) : this.clearFilter();
19485 * Filter by a function. The specified function will be called with each
19486 * record in this data source. If the function returns true the record is included,
19487 * otherwise it is filtered.
19488 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
19489 * @param {Object} scope (optional) The scope of the function (defaults to this)
19491 filterBy : function(fn, scope){
19492 this.snapshot = this.snapshot || this.data;
19493 this.data = this.queryBy(fn, scope||this);
19494 this.fireEvent("datachanged", this);
19498 * Query the records by a specified property.
19499 * @param {String} field A field on your records
19500 * @param {String/RegExp} value Either a string that the field
19501 * should start with or a RegExp to test against the field
19502 * @param {Boolean} anyMatch True to match any part not just the beginning
19503 * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
19505 query : function(property, value, anyMatch){
19506 var fn = this.createFilterFn(property, value, anyMatch);
19507 return fn ? this.queryBy(fn) : this.data.clone();
19511 * Query by a function. The specified function will be called with each
19512 * record in this data source. If the function returns true the record is included
19514 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
19515 * @param {Object} scope (optional) The scope of the function (defaults to this)
19516 @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
19518 queryBy : function(fn, scope){
19519 var data = this.snapshot || this.data;
19520 return data.filterBy(fn, scope||this);
19524 * Collects unique values for a particular dataIndex from this store.
19525 * @param {String} dataIndex The property to collect
19526 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
19527 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
19528 * @return {Array} An array of the unique values
19530 collect : function(dataIndex, allowNull, bypassFilter){
19531 var d = (bypassFilter === true && this.snapshot) ?
19532 this.snapshot.items : this.data.items;
19533 var v, sv, r = [], l = {};
19534 for(var i = 0, len = d.length; i < len; i++){
19535 v = d[i].data[dataIndex];
19537 if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
19546 * Revert to a view of the Record cache with no filtering applied.
19547 * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
19549 clearFilter : function(suppressEvent){
19550 if(this.snapshot && this.snapshot != this.data){
19551 this.data = this.snapshot;
19552 delete this.snapshot;
19553 if(suppressEvent !== true){
19554 this.fireEvent("datachanged", this);
19560 afterEdit : function(record){
19561 if(this.modified.indexOf(record) == -1){
19562 this.modified.push(record);
19564 this.fireEvent("update", this, record, Roo.data.Record.EDIT);
19568 afterReject : function(record){
19569 this.modified.remove(record);
19570 this.fireEvent("update", this, record, Roo.data.Record.REJECT);
19574 afterCommit : function(record){
19575 this.modified.remove(record);
19576 this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
19580 * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
19581 * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
19583 commitChanges : function(){
19584 var m = this.modified.slice(0);
19585 this.modified = [];
19586 for(var i = 0, len = m.length; i < len; i++){
19592 * Cancel outstanding changes on all changed records.
19594 rejectChanges : function(){
19595 var m = this.modified.slice(0);
19596 this.modified = [];
19597 for(var i = 0, len = m.length; i < len; i++){
19602 onMetaChange : function(meta, rtype, o){
19603 this.recordType = rtype;
19604 this.fields = rtype.prototype.fields;
19605 delete this.snapshot;
19606 this.sortInfo = meta.sortInfo;
19607 this.modified = [];
19608 this.fireEvent('metachange', this, this.reader.meta);
19612 * Ext JS Library 1.1.1
19613 * Copyright(c) 2006-2007, Ext JS, LLC.
19615 * Originally Released Under LGPL - original licence link has changed is not relivant.
19618 * <script type="text/javascript">
19622 * @class Roo.data.SimpleStore
19623 * @extends Roo.data.Store
19624 * Small helper class to make creating Stores from Array data easier.
19625 * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
19626 * @cfg {Array} fields An array of field definition objects, or field name strings.
19627 * @cfg {Array} data The multi-dimensional array of data
19629 * @param {Object} config
19631 Roo.data.SimpleStore = function(config){
19632 Roo.data.SimpleStore.superclass.constructor.call(this, {
19634 reader: new Roo.data.ArrayReader({
19637 Roo.data.Record.create(config.fields)
19639 proxy : new Roo.data.MemoryProxy(config.data)
19643 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
19645 * Ext JS Library 1.1.1
19646 * Copyright(c) 2006-2007, Ext JS, LLC.
19648 * Originally Released Under LGPL - original licence link has changed is not relivant.
19651 * <script type="text/javascript">
19656 * @extends Roo.data.Store
19657 * @class Roo.data.JsonStore
19658 * Small helper class to make creating Stores for JSON data easier. <br/>
19660 var store = new Roo.data.JsonStore({
19661 url: 'get-images.php',
19663 fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
19666 * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
19667 * JsonReader and HttpProxy (unless inline data is provided).</b>
19668 * @cfg {Array} fields An array of field definition objects, or field name strings.
19670 * @param {Object} config
19672 Roo.data.JsonStore = function(c){
19673 Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
19674 proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
19675 reader: new Roo.data.JsonReader(c, c.fields)
19678 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
19680 * Ext JS Library 1.1.1
19681 * Copyright(c) 2006-2007, Ext JS, LLC.
19683 * Originally Released Under LGPL - original licence link has changed is not relivant.
19686 * <script type="text/javascript">
19690 Roo.data.Field = function(config){
19691 if(typeof config == "string"){
19692 config = {name: config};
19694 Roo.apply(this, config);
19697 this.type = "auto";
19700 var st = Roo.data.SortTypes;
19701 // named sortTypes are supported, here we look them up
19702 if(typeof this.sortType == "string"){
19703 this.sortType = st[this.sortType];
19706 // set default sortType for strings and dates
19707 if(!this.sortType){
19710 this.sortType = st.asUCString;
19713 this.sortType = st.asDate;
19716 this.sortType = st.none;
19721 var stripRe = /[\$,%]/g;
19723 // prebuilt conversion function for this field, instead of
19724 // switching every time we're reading a value
19726 var cv, dateFormat = this.dateFormat;
19731 cv = function(v){ return v; };
19734 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
19738 return v !== undefined && v !== null && v !== '' ?
19739 parseInt(String(v).replace(stripRe, ""), 10) : '';
19744 return v !== undefined && v !== null && v !== '' ?
19745 parseFloat(String(v).replace(stripRe, ""), 10) : '';
19750 cv = function(v){ return v === true || v === "true" || v == 1; };
19757 if(v instanceof Date){
19761 if(dateFormat == "timestamp"){
19762 return new Date(v*1000);
19764 return Date.parseDate(v, dateFormat);
19766 var parsed = Date.parse(v);
19767 return parsed ? new Date(parsed) : null;
19776 Roo.data.Field.prototype = {
19784 * Ext JS Library 1.1.1
19785 * Copyright(c) 2006-2007, Ext JS, LLC.
19787 * Originally Released Under LGPL - original licence link has changed is not relivant.
19790 * <script type="text/javascript">
19793 // Base class for reading structured data from a data source. This class is intended to be
19794 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
19797 * @class Roo.data.DataReader
19798 * Base class for reading structured data from a data source. This class is intended to be
19799 * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
19802 Roo.data.DataReader = function(meta, recordType){
19806 this.recordType = recordType instanceof Array ?
19807 Roo.data.Record.create(recordType) : recordType;
19810 Roo.data.DataReader.prototype = {
19812 * Create an empty record
19813 * @param {Object} data (optional) - overlay some values
19814 * @return {Roo.data.Record} record created.
19816 newRow : function(d) {
19818 this.recordType.prototype.fields.each(function(c) {
19820 case 'int' : da[c.name] = 0; break;
19821 case 'date' : da[c.name] = new Date(); break;
19822 case 'float' : da[c.name] = 0.0; break;
19823 case 'boolean' : da[c.name] = false; break;
19824 default : da[c.name] = ""; break;
19828 return new this.recordType(Roo.apply(da, d));
19833 * Ext JS Library 1.1.1
19834 * Copyright(c) 2006-2007, Ext JS, LLC.
19836 * Originally Released Under LGPL - original licence link has changed is not relivant.
19839 * <script type="text/javascript">
19843 * @class Roo.data.DataProxy
19844 * @extends Roo.data.Observable
19845 * This class is an abstract base class for implementations which provide retrieval of
19846 * unformatted data objects.<br>
19848 * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
19849 * (of the appropriate type which knows how to parse the data object) to provide a block of
19850 * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
19852 * Custom implementations must implement the load method as described in
19853 * {@link Roo.data.HttpProxy#load}.
19855 Roo.data.DataProxy = function(){
19858 * @event beforeload
19859 * Fires before a network request is made to retrieve a data object.
19860 * @param {Object} This DataProxy object.
19861 * @param {Object} params The params parameter to the load function.
19866 * Fires before the load method's callback is called.
19867 * @param {Object} This DataProxy object.
19868 * @param {Object} o The data object.
19869 * @param {Object} arg The callback argument object passed to the load function.
19873 * @event loadexception
19874 * Fires if an Exception occurs during data retrieval.
19875 * @param {Object} This DataProxy object.
19876 * @param {Object} o The data object.
19877 * @param {Object} arg The callback argument object passed to the load function.
19878 * @param {Object} e The Exception.
19880 loadexception : true
19882 Roo.data.DataProxy.superclass.constructor.call(this);
19885 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
19888 * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
19892 * Ext JS Library 1.1.1
19893 * Copyright(c) 2006-2007, Ext JS, LLC.
19895 * Originally Released Under LGPL - original licence link has changed is not relivant.
19898 * <script type="text/javascript">
19901 * @class Roo.data.MemoryProxy
19902 * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
19903 * to the Reader when its load method is called.
19905 * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
19907 Roo.data.MemoryProxy = function(data){
19911 Roo.data.MemoryProxy.superclass.constructor.call(this);
19915 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
19917 * Load data from the requested source (in this case an in-memory
19918 * data object passed to the constructor), read the data object into
19919 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
19920 * process that block using the passed callback.
19921 * @param {Object} params This parameter is not used by the MemoryProxy class.
19922 * @param {Roo.data.DataReader} reader The Reader object which converts the data
19923 * object into a block of Roo.data.Records.
19924 * @param {Function} callback The function into which to pass the block of Roo.data.records.
19925 * The function must be passed <ul>
19926 * <li>The Record block object</li>
19927 * <li>The "arg" argument from the load function</li>
19928 * <li>A boolean success indicator</li>
19930 * @param {Object} scope The scope in which to call the callback
19931 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
19933 load : function(params, reader, callback, scope, arg){
19934 params = params || {};
19937 result = reader.readRecords(this.data);
19939 this.fireEvent("loadexception", this, arg, null, e);
19940 callback.call(scope, null, arg, false);
19943 callback.call(scope, result, arg, true);
19947 update : function(params, records){
19952 * Ext JS Library 1.1.1
19953 * Copyright(c) 2006-2007, Ext JS, LLC.
19955 * Originally Released Under LGPL - original licence link has changed is not relivant.
19958 * <script type="text/javascript">
19961 * @class Roo.data.HttpProxy
19962 * @extends Roo.data.DataProxy
19963 * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
19964 * configured to reference a certain URL.<br><br>
19966 * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
19967 * from which the running page was served.<br><br>
19969 * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
19971 * Be aware that to enable the browser to parse an XML document, the server must set
19972 * the Content-Type header in the HTTP response to "text/xml".
19974 * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
19975 * an {@link Roo.data.Connection} object. If a Connection config is passed, the singleton {@link Roo.Ajax} object
19976 * will be used to make the request.
19978 Roo.data.HttpProxy = function(conn){
19979 Roo.data.HttpProxy.superclass.constructor.call(this);
19980 // is conn a conn config or a real conn?
19982 this.useAjax = !conn || !conn.events;
19986 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
19987 // thse are take from connection...
19990 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
19993 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
19994 * extra parameters to each request made by this object. (defaults to undefined)
19997 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
19998 * to each request made by this object. (defaults to undefined)
20001 * @cfg {String} method (Optional) The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
20004 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
20007 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
20013 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
20017 * Return the {@link Roo.data.Connection} object being used by this Proxy.
20018 * @return {Connection} The Connection object. This object may be used to subscribe to events on
20019 * a finer-grained basis than the DataProxy events.
20021 getConnection : function(){
20022 return this.useAjax ? Roo.Ajax : this.conn;
20026 * Load data from the configured {@link Roo.data.Connection}, read the data object into
20027 * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
20028 * process that block using the passed callback.
20029 * @param {Object} params An object containing properties which are to be used as HTTP parameters
20030 * for the request to the remote server.
20031 * @param {Roo.data.DataReader} reader The Reader object which converts the data
20032 * object into a block of Roo.data.Records.
20033 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
20034 * The function must be passed <ul>
20035 * <li>The Record block object</li>
20036 * <li>The "arg" argument from the load function</li>
20037 * <li>A boolean success indicator</li>
20039 * @param {Object} scope The scope in which to call the callback
20040 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
20042 load : function(params, reader, callback, scope, arg){
20043 if(this.fireEvent("beforeload", this, params) !== false){
20045 params : params || {},
20047 callback : callback,
20052 callback : this.loadResponse,
20056 Roo.applyIf(o, this.conn);
20057 if(this.activeRequest){
20058 Roo.Ajax.abort(this.activeRequest);
20060 this.activeRequest = Roo.Ajax.request(o);
20062 this.conn.request(o);
20065 callback.call(scope||this, null, arg, false);
20070 loadResponse : function(o, success, response){
20071 delete this.activeRequest;
20073 this.fireEvent("loadexception", this, o, response);
20074 o.request.callback.call(o.request.scope, null, o.request.arg, false);
20079 result = o.reader.read(response);
20081 this.fireEvent("loadexception", this, o, response, e);
20082 o.request.callback.call(o.request.scope, null, o.request.arg, false);
20086 this.fireEvent("load", this, o, o.request.arg);
20087 o.request.callback.call(o.request.scope, result, o.request.arg, true);
20091 update : function(dataSet){
20096 updateResponse : function(dataSet){
20101 * Ext JS Library 1.1.1
20102 * Copyright(c) 2006-2007, Ext JS, LLC.
20104 * Originally Released Under LGPL - original licence link has changed is not relivant.
20107 * <script type="text/javascript">
20111 * @class Roo.data.ScriptTagProxy
20112 * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
20113 * other than the originating domain of the running page.<br><br>
20115 * <em>Note that if you are retrieving data from a page that is in a domain that is NOT the same as the originating domain
20116 * of the running page, you must use this class, rather than DataProxy.</em><br><br>
20118 * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
20119 * source code that is used as the source inside a <script> tag.<br><br>
20121 * In order for the browser to process the returned data, the server must wrap the data object
20122 * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
20123 * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
20124 * depending on whether the callback name was passed:
20127 boolean scriptTag = false;
20128 String cb = request.getParameter("callback");
20131 response.setContentType("text/javascript");
20133 response.setContentType("application/x-json");
20135 Writer out = response.getWriter();
20137 out.write(cb + "(");
20139 out.print(dataBlock.toJsonString());
20146 * @param {Object} config A configuration object.
20148 Roo.data.ScriptTagProxy = function(config){
20149 Roo.data.ScriptTagProxy.superclass.constructor.call(this);
20150 Roo.apply(this, config);
20151 this.head = document.getElementsByTagName("head")[0];
20154 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
20156 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
20158 * @cfg {String} url The URL from which to request the data object.
20161 * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
20165 * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
20166 * the server the name of the callback function set up by the load call to process the returned data object.
20167 * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
20168 * javascript output which calls this named function passing the data object as its only parameter.
20170 callbackParam : "callback",
20172 * @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
20173 * name to the request.
20178 * Load data from the configured URL, read the data object into
20179 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
20180 * process that block using the passed callback.
20181 * @param {Object} params An object containing properties which are to be used as HTTP parameters
20182 * for the request to the remote server.
20183 * @param {Roo.data.DataReader} reader The Reader object which converts the data
20184 * object into a block of Roo.data.Records.
20185 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
20186 * The function must be passed <ul>
20187 * <li>The Record block object</li>
20188 * <li>The "arg" argument from the load function</li>
20189 * <li>A boolean success indicator</li>
20191 * @param {Object} scope The scope in which to call the callback
20192 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
20194 load : function(params, reader, callback, scope, arg){
20195 if(this.fireEvent("beforeload", this, params) !== false){
20197 var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
20199 var url = this.url;
20200 url += (url.indexOf("?") != -1 ? "&" : "?") + p;
20202 url += "&_dc=" + (new Date().getTime());
20204 var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
20207 cb : "stcCallback"+transId,
20208 scriptId : "stcScript"+transId,
20212 callback : callback,
20218 window[trans.cb] = function(o){
20219 conn.handleResponse(o, trans);
20222 url += String.format("&{0}={1}", this.callbackParam, trans.cb);
20224 if(this.autoAbort !== false){
20228 trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
20230 var script = document.createElement("script");
20231 script.setAttribute("src", url);
20232 script.setAttribute("type", "text/javascript");
20233 script.setAttribute("id", trans.scriptId);
20234 this.head.appendChild(script);
20236 this.trans = trans;
20238 callback.call(scope||this, null, arg, false);
20243 isLoading : function(){
20244 return this.trans ? true : false;
20248 * Abort the current server request.
20250 abort : function(){
20251 if(this.isLoading()){
20252 this.destroyTrans(this.trans);
20257 destroyTrans : function(trans, isLoaded){
20258 this.head.removeChild(document.getElementById(trans.scriptId));
20259 clearTimeout(trans.timeoutId);
20261 window[trans.cb] = undefined;
20263 delete window[trans.cb];
20266 // if hasn't been loaded, wait for load to remove it to prevent script error
20267 window[trans.cb] = function(){
20268 window[trans.cb] = undefined;
20270 delete window[trans.cb];
20277 handleResponse : function(o, trans){
20278 this.trans = false;
20279 this.destroyTrans(trans, true);
20282 result = trans.reader.readRecords(o);
20284 this.fireEvent("loadexception", this, o, trans.arg, e);
20285 trans.callback.call(trans.scope||window, null, trans.arg, false);
20288 this.fireEvent("load", this, o, trans.arg);
20289 trans.callback.call(trans.scope||window, result, trans.arg, true);
20293 handleFailure : function(trans){
20294 this.trans = false;
20295 this.destroyTrans(trans, false);
20296 this.fireEvent("loadexception", this, null, trans.arg);
20297 trans.callback.call(trans.scope||window, null, trans.arg, false);
20301 * Ext JS Library 1.1.1
20302 * Copyright(c) 2006-2007, Ext JS, LLC.
20304 * Originally Released Under LGPL - original licence link has changed is not relivant.
20307 * <script type="text/javascript">
20311 * @class Roo.data.JsonReader
20312 * @extends Roo.data.DataReader
20313 * Data reader class to create an Array of Roo.data.Record objects from a JSON response
20314 * based on mappings in a provided Roo.data.Record constructor.
20318 var RecordDef = Roo.data.Record.create([
20319 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
20320 {name: 'occupation'} // This field will use "occupation" as the mapping.
20322 var myReader = new Roo.data.JsonReader({
20323 totalProperty: "results", // The property which contains the total dataset size (optional)
20324 root: "rows", // The property which contains an Array of row objects
20325 id: "id" // The property within each row object that provides an ID for the record (optional)
20329 * This would consume a JSON file like this:
20331 { 'results': 2, 'rows': [
20332 { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
20333 { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
20336 * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
20337 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
20338 * paged from the remote server.
20339 * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
20340 * @cfg {String} root name of the property which contains the Array of row objects.
20341 * @cfg {String} id Name of the property within a row object that contains a record identifier value.
20343 * Create a new JsonReader
20344 * @param {Object} meta Metadata configuration options
20345 * @param {Object} recordType Either an Array of field definition objects,
20346 * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
20348 Roo.data.JsonReader = function(meta, recordType){
20351 // set some defaults:
20352 Roo.applyIf(meta, {
20353 totalProperty: 'total',
20354 successProperty : 'success',
20359 Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
20361 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
20363 * This method is only used by a DataProxy which has retrieved data from a remote server.
20364 * @param {Object} response The XHR object which contains the JSON data in its responseText.
20365 * @return {Object} data A data block which is used by an Roo.data.Store object as
20366 * a cache of Roo.data.Records.
20368 read : function(response){
20369 var json = response.responseText;
20371 var o = eval("("+json+")");
20373 throw {message: "JsonReader.read: Json object not found"};
20378 this.meta = o.metaData;
20379 this.recordType = Roo.data.Record.create(o.metaData.fields);
20380 this.onMetaChange(this.meta, this.recordType, o);
20382 return this.readRecords(o);
20385 // private function a store will implement
20386 onMetaChange : function(meta, recordType, o){
20393 simpleAccess: function(obj, subsc) {
20400 getJsonAccessor: function(){
20402 return function(expr) {
20404 return(re.test(expr))
20405 ? new Function("obj", "return obj." + expr)
20410 return Roo.emptyFn;
20415 * Create a data block containing Roo.data.Records from an XML document.
20416 * @param {Object} o An object which contains an Array of row objects in the property specified
20417 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
20418 * which contains the total size of the dataset.
20419 * @return {Object} data A data block which is used by an Roo.data.Store object as
20420 * a cache of Roo.data.Records.
20422 readRecords : function(o){
20424 * After any data loads, the raw JSON data is available for further custom processing.
20428 var s = this.meta, Record = this.recordType,
20429 f = Record.prototype.fields, fi = f.items, fl = f.length;
20431 // Generate extraction functions for the totalProperty, the root, the id, and for each field
20433 if(s.totalProperty) {
20434 this.getTotal = this.getJsonAccessor(s.totalProperty);
20436 if(s.successProperty) {
20437 this.getSuccess = this.getJsonAccessor(s.successProperty);
20439 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
20441 var g = this.getJsonAccessor(s.id);
20442 this.getId = function(rec) {
20444 return (r === undefined || r === "") ? null : r;
20447 this.getId = function(){return null;};
20450 for(var i = 0; i < fl; i++){
20452 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
20453 this.ef[i] = this.getJsonAccessor(map);
20457 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
20458 if(s.totalProperty){
20459 var v = parseInt(this.getTotal(o), 10);
20464 if(s.successProperty){
20465 var v = this.getSuccess(o);
20466 if(v === false || v === 'false'){
20471 for(var i = 0; i < c; i++){
20474 var id = this.getId(n);
20475 for(var j = 0; j < fl; j++){
20477 var v = this.ef[j](n);
20478 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
20480 var record = new Record(values, id);
20482 records[i] = record;
20487 totalRecords : totalRecords
20492 * Ext JS Library 1.1.1
20493 * Copyright(c) 2006-2007, Ext JS, LLC.
20495 * Originally Released Under LGPL - original licence link has changed is not relivant.
20498 * <script type="text/javascript">
20502 * @class Roo.data.XmlReader
20503 * @extends Roo.data.DataReader
20504 * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
20505 * based on mappings in a provided Roo.data.Record constructor.<br><br>
20507 * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
20508 * header in the HTTP response must be set to "text/xml".</em>
20512 var RecordDef = Roo.data.Record.create([
20513 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
20514 {name: 'occupation'} // This field will use "occupation" as the mapping.
20516 var myReader = new Roo.data.XmlReader({
20517 totalRecords: "results", // The element which contains the total dataset size (optional)
20518 record: "row", // The repeated element which contains row information
20519 id: "id" // The element within the row that provides an ID for the record (optional)
20523 * This would consume an XML file like this:
20527 <results>2</results>
20530 <name>Bill</name>
20531 <occupation>Gardener</occupation>
20535 <name>Ben</name>
20536 <occupation>Horticulturalist</occupation>
20540 * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
20541 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
20542 * paged from the remote server.
20543 * @cfg {String} record The DomQuery path to the repeated element which contains record information.
20544 * @cfg {String} success The DomQuery path to the success attribute used by forms.
20545 * @cfg {String} id The DomQuery path relative from the record element to the element that contains
20546 * a record identifier value.
20548 * Create a new XmlReader
20549 * @param {Object} meta Metadata configuration options
20550 * @param {Mixed} recordType The definition of the data record type to produce. This can be either a valid
20551 * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
20552 * Roo.data.Record.create. See the {@link Roo.data.Record} class for more details.
20554 Roo.data.XmlReader = function(meta, recordType){
20556 Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
20558 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
20560 * This method is only used by a DataProxy which has retrieved data from a remote server.
20561 * @param {Object} response The XHR object which contains the parsed XML document. The response is expected
20562 * to contain a method called 'responseXML' that returns an XML document object.
20563 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
20564 * a cache of Roo.data.Records.
20566 read : function(response){
20567 var doc = response.responseXML;
20569 throw {message: "XmlReader.read: XML Document not available"};
20571 return this.readRecords(doc);
20575 * Create a data block containing Roo.data.Records from an XML document.
20576 * @param {Object} doc A parsed XML document.
20577 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
20578 * a cache of Roo.data.Records.
20580 readRecords : function(doc){
20582 * After any data loads/reads, the raw XML Document is available for further custom processing.
20583 * @type XMLDocument
20585 this.xmlData = doc;
20586 var root = doc.documentElement || doc;
20587 var q = Roo.DomQuery;
20588 var recordType = this.recordType, fields = recordType.prototype.fields;
20589 var sid = this.meta.id;
20590 var totalRecords = 0, success = true;
20591 if(this.meta.totalRecords){
20592 totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
20595 if(this.meta.success){
20596 var sv = q.selectValue(this.meta.success, root, true);
20597 success = sv !== false && sv !== 'false';
20600 var ns = q.select(this.meta.record, root);
20601 for(var i = 0, len = ns.length; i < len; i++) {
20604 var id = sid ? q.selectValue(sid, n) : undefined;
20605 for(var j = 0, jlen = fields.length; j < jlen; j++){
20606 var f = fields.items[j];
20607 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
20609 values[f.name] = v;
20611 var record = new recordType(values, id);
20613 records[records.length] = record;
20619 totalRecords : totalRecords || records.length
20624 * Ext JS Library 1.1.1
20625 * Copyright(c) 2006-2007, Ext JS, LLC.
20627 * Originally Released Under LGPL - original licence link has changed is not relivant.
20630 * <script type="text/javascript">
20634 * @class Roo.data.ArrayReader
20635 * @extends Roo.data.DataReader
20636 * Data reader class to create an Array of Roo.data.Record objects from an Array.
20637 * Each element of that Array represents a row of data fields. The
20638 * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
20639 * of the field definition if it exists, or the field's ordinal position in the definition.<br>
20643 var RecordDef = Roo.data.Record.create([
20644 {name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
20645 {name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
20647 var myReader = new Roo.data.ArrayReader({
20648 id: 0 // The subscript within row Array that provides an ID for the Record (optional)
20652 * This would consume an Array like this:
20654 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
20656 * @cfg {String} id (optional) The subscript within row Array that provides an ID for the Record
20658 * Create a new JsonReader
20659 * @param {Object} meta Metadata configuration options.
20660 * @param {Object} recordType Either an Array of field definition objects
20661 * as specified to {@link Roo.data.Record#create},
20662 * or an {@link Roo.data.Record} object
20663 * created using {@link Roo.data.Record#create}.
20665 Roo.data.ArrayReader = function(meta, recordType){
20666 Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType);
20669 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
20671 * Create a data block containing Roo.data.Records from an XML document.
20672 * @param {Object} o An Array of row objects which represents the dataset.
20673 * @return {Object} data A data block which is used by an Roo.data.Store object as
20674 * a cache of Roo.data.Records.
20676 readRecords : function(o){
20677 var sid = this.meta ? this.meta.id : null;
20678 var recordType = this.recordType, fields = recordType.prototype.fields;
20681 for(var i = 0; i < root.length; i++){
20684 var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
20685 for(var j = 0, jlen = fields.length; j < jlen; j++){
20686 var f = fields.items[j];
20687 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
20688 var v = n[k] !== undefined ? n[k] : f.defaultValue;
20690 values[f.name] = v;
20692 var record = new recordType(values, id);
20694 records[records.length] = record;
20698 totalRecords : records.length
20703 * Ext JS Library 1.1.1
20704 * Copyright(c) 2006-2007, Ext JS, LLC.
20706 * Originally Released Under LGPL - original licence link has changed is not relivant.
20709 * <script type="text/javascript">
20714 * @class Roo.data.Tree
20715 * @extends Roo.util.Observable
20716 * Represents a tree data structure and bubbles all the events for its nodes. The nodes
20717 * in the tree have most standard DOM functionality.
20719 * @param {Node} root (optional) The root node
20721 Roo.data.Tree = function(root){
20722 this.nodeHash = {};
20724 * The root node for this tree
20729 this.setRootNode(root);
20734 * Fires when a new child node is appended to a node in this tree.
20735 * @param {Tree} tree The owner tree
20736 * @param {Node} parent The parent node
20737 * @param {Node} node The newly appended node
20738 * @param {Number} index The index of the newly appended node
20743 * Fires when a child node is removed from a node in this tree.
20744 * @param {Tree} tree The owner tree
20745 * @param {Node} parent The parent node
20746 * @param {Node} node The child node removed
20751 * Fires when a node is moved to a new location in the tree
20752 * @param {Tree} tree The owner tree
20753 * @param {Node} node The node moved
20754 * @param {Node} oldParent The old parent of this node
20755 * @param {Node} newParent The new parent of this node
20756 * @param {Number} index The index it was moved to
20761 * Fires when a new child node is inserted in a node in this tree.
20762 * @param {Tree} tree The owner tree
20763 * @param {Node} parent The parent node
20764 * @param {Node} node The child node inserted
20765 * @param {Node} refNode The child node the node was inserted before
20769 * @event beforeappend
20770 * Fires before a new child is appended to a node in this tree, return false to cancel the append.
20771 * @param {Tree} tree The owner tree
20772 * @param {Node} parent The parent node
20773 * @param {Node} node The child node to be appended
20775 "beforeappend" : true,
20777 * @event beforeremove
20778 * Fires before a child is removed from a node in this tree, return false to cancel the remove.
20779 * @param {Tree} tree The owner tree
20780 * @param {Node} parent The parent node
20781 * @param {Node} node The child node to be removed
20783 "beforeremove" : true,
20785 * @event beforemove
20786 * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
20787 * @param {Tree} tree The owner tree
20788 * @param {Node} node The node being moved
20789 * @param {Node} oldParent The parent of the node
20790 * @param {Node} newParent The new parent the node is moving to
20791 * @param {Number} index The index it is being moved to
20793 "beforemove" : true,
20795 * @event beforeinsert
20796 * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
20797 * @param {Tree} tree The owner tree
20798 * @param {Node} parent The parent node
20799 * @param {Node} node The child node to be inserted
20800 * @param {Node} refNode The child node the node is being inserted before
20802 "beforeinsert" : true
20805 Roo.data.Tree.superclass.constructor.call(this);
20808 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
20809 pathSeparator: "/",
20811 proxyNodeEvent : function(){
20812 return this.fireEvent.apply(this, arguments);
20816 * Returns the root node for this tree.
20819 getRootNode : function(){
20824 * Sets the root node for this tree.
20825 * @param {Node} node
20828 setRootNode : function(node){
20830 node.ownerTree = this;
20831 node.isRoot = true;
20832 this.registerNode(node);
20837 * Gets a node in this tree by its id.
20838 * @param {String} id
20841 getNodeById : function(id){
20842 return this.nodeHash[id];
20845 registerNode : function(node){
20846 this.nodeHash[node.id] = node;
20849 unregisterNode : function(node){
20850 delete this.nodeHash[node.id];
20853 toString : function(){
20854 return "[Tree"+(this.id?" "+this.id:"")+"]";
20859 * @class Roo.data.Node
20860 * @extends Roo.util.Observable
20861 * @cfg {Boolean} leaf true if this node is a leaf and does not have children
20862 * @cfg {String} id The id for this node. If one is not specified, one is generated.
20864 * @param {Object} attributes The attributes/config for the node
20866 Roo.data.Node = function(attributes){
20868 * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
20871 this.attributes = attributes || {};
20872 this.leaf = this.attributes.leaf;
20874 * The node id. @type String
20876 this.id = this.attributes.id;
20878 this.id = Roo.id(null, "ynode-");
20879 this.attributes.id = this.id;
20882 * All child nodes of this node. @type Array
20884 this.childNodes = [];
20885 if(!this.childNodes.indexOf){ // indexOf is a must
20886 this.childNodes.indexOf = function(o){
20887 for(var i = 0, len = this.length; i < len; i++){
20888 if(this[i] == o) return i;
20894 * The parent node for this node. @type Node
20896 this.parentNode = null;
20898 * The first direct child node of this node, or null if this node has no child nodes. @type Node
20900 this.firstChild = null;
20902 * The last direct child node of this node, or null if this node has no child nodes. @type Node
20904 this.lastChild = null;
20906 * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
20908 this.previousSibling = null;
20910 * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
20912 this.nextSibling = null;
20917 * Fires when a new child node is appended
20918 * @param {Tree} tree The owner tree
20919 * @param {Node} this This node
20920 * @param {Node} node The newly appended node
20921 * @param {Number} index The index of the newly appended node
20926 * Fires when a child node is removed
20927 * @param {Tree} tree The owner tree
20928 * @param {Node} this This node
20929 * @param {Node} node The removed node
20934 * Fires when this node is moved to a new location in the tree
20935 * @param {Tree} tree The owner tree
20936 * @param {Node} this This node
20937 * @param {Node} oldParent The old parent of this node
20938 * @param {Node} newParent The new parent of this node
20939 * @param {Number} index The index it was moved to
20944 * Fires when a new child node is inserted.
20945 * @param {Tree} tree The owner tree
20946 * @param {Node} this This node
20947 * @param {Node} node The child node inserted
20948 * @param {Node} refNode The child node the node was inserted before
20952 * @event beforeappend
20953 * Fires before a new child is appended, return false to cancel the append.
20954 * @param {Tree} tree The owner tree
20955 * @param {Node} this This node
20956 * @param {Node} node The child node to be appended
20958 "beforeappend" : true,
20960 * @event beforeremove
20961 * Fires before a child is removed, return false to cancel the remove.
20962 * @param {Tree} tree The owner tree
20963 * @param {Node} this This node
20964 * @param {Node} node The child node to be removed
20966 "beforeremove" : true,
20968 * @event beforemove
20969 * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
20970 * @param {Tree} tree The owner tree
20971 * @param {Node} this This node
20972 * @param {Node} oldParent The parent of this node
20973 * @param {Node} newParent The new parent this node is moving to
20974 * @param {Number} index The index it is being moved to
20976 "beforemove" : true,
20978 * @event beforeinsert
20979 * Fires before a new child is inserted, return false to cancel the insert.
20980 * @param {Tree} tree The owner tree
20981 * @param {Node} this This node
20982 * @param {Node} node The child node to be inserted
20983 * @param {Node} refNode The child node the node is being inserted before
20985 "beforeinsert" : true
20987 this.listeners = this.attributes.listeners;
20988 Roo.data.Node.superclass.constructor.call(this);
20991 Roo.extend(Roo.data.Node, Roo.util.Observable, {
20992 fireEvent : function(evtName){
20993 // first do standard event for this node
20994 if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
20997 // then bubble it up to the tree if the event wasn't cancelled
20998 var ot = this.getOwnerTree();
21000 if(ot.proxyNodeEvent.apply(ot, arguments) === false){
21008 * Returns true if this node is a leaf
21009 * @return {Boolean}
21011 isLeaf : function(){
21012 return this.leaf === true;
21016 setFirstChild : function(node){
21017 this.firstChild = node;
21021 setLastChild : function(node){
21022 this.lastChild = node;
21027 * Returns true if this node is the last child of its parent
21028 * @return {Boolean}
21030 isLast : function(){
21031 return (!this.parentNode ? true : this.parentNode.lastChild == this);
21035 * Returns true if this node is the first child of its parent
21036 * @return {Boolean}
21038 isFirst : function(){
21039 return (!this.parentNode ? true : this.parentNode.firstChild == this);
21042 hasChildNodes : function(){
21043 return !this.isLeaf() && this.childNodes.length > 0;
21047 * Insert node(s) as the last child node of this node.
21048 * @param {Node/Array} node The node or Array of nodes to append
21049 * @return {Node} The appended node if single append, or null if an array was passed
21051 appendChild : function(node){
21053 if(node instanceof Array){
21055 }else if(arguments.length > 1){
21058 // if passed an array or multiple args do them one by one
21060 for(var i = 0, len = multi.length; i < len; i++) {
21061 this.appendChild(multi[i]);
21064 if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
21067 var index = this.childNodes.length;
21068 var oldParent = node.parentNode;
21069 // it's a move, make sure we move it cleanly
21071 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
21074 oldParent.removeChild(node);
21076 index = this.childNodes.length;
21078 this.setFirstChild(node);
21080 this.childNodes.push(node);
21081 node.parentNode = this;
21082 var ps = this.childNodes[index-1];
21084 node.previousSibling = ps;
21085 ps.nextSibling = node;
21087 node.previousSibling = null;
21089 node.nextSibling = null;
21090 this.setLastChild(node);
21091 node.setOwnerTree(this.getOwnerTree());
21092 this.fireEvent("append", this.ownerTree, this, node, index);
21094 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
21101 * Removes a child node from this node.
21102 * @param {Node} node The node to remove
21103 * @return {Node} The removed node
21105 removeChild : function(node){
21106 var index = this.childNodes.indexOf(node);
21110 if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
21114 // remove it from childNodes collection
21115 this.childNodes.splice(index, 1);
21118 if(node.previousSibling){
21119 node.previousSibling.nextSibling = node.nextSibling;
21121 if(node.nextSibling){
21122 node.nextSibling.previousSibling = node.previousSibling;
21125 // update child refs
21126 if(this.firstChild == node){
21127 this.setFirstChild(node.nextSibling);
21129 if(this.lastChild == node){
21130 this.setLastChild(node.previousSibling);
21133 node.setOwnerTree(null);
21134 // clear any references from the node
21135 node.parentNode = null;
21136 node.previousSibling = null;
21137 node.nextSibling = null;
21138 this.fireEvent("remove", this.ownerTree, this, node);
21143 * Inserts the first node before the second node in this nodes childNodes collection.
21144 * @param {Node} node The node to insert
21145 * @param {Node} refNode The node to insert before (if null the node is appended)
21146 * @return {Node} The inserted node
21148 insertBefore : function(node, refNode){
21149 if(!refNode){ // like standard Dom, refNode can be null for append
21150 return this.appendChild(node);
21153 if(node == refNode){
21157 if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
21160 var index = this.childNodes.indexOf(refNode);
21161 var oldParent = node.parentNode;
21162 var refIndex = index;
21164 // when moving internally, indexes will change after remove
21165 if(oldParent == this && this.childNodes.indexOf(node) < index){
21169 // it's a move, make sure we move it cleanly
21171 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
21174 oldParent.removeChild(node);
21177 this.setFirstChild(node);
21179 this.childNodes.splice(refIndex, 0, node);
21180 node.parentNode = this;
21181 var ps = this.childNodes[refIndex-1];
21183 node.previousSibling = ps;
21184 ps.nextSibling = node;
21186 node.previousSibling = null;
21188 node.nextSibling = refNode;
21189 refNode.previousSibling = node;
21190 node.setOwnerTree(this.getOwnerTree());
21191 this.fireEvent("insert", this.ownerTree, this, node, refNode);
21193 node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
21199 * Returns the child node at the specified index.
21200 * @param {Number} index
21203 item : function(index){
21204 return this.childNodes[index];
21208 * Replaces one child node in this node with another.
21209 * @param {Node} newChild The replacement node
21210 * @param {Node} oldChild The node to replace
21211 * @return {Node} The replaced node
21213 replaceChild : function(newChild, oldChild){
21214 this.insertBefore(newChild, oldChild);
21215 this.removeChild(oldChild);
21220 * Returns the index of a child node
21221 * @param {Node} node
21222 * @return {Number} The index of the node or -1 if it was not found
21224 indexOf : function(child){
21225 return this.childNodes.indexOf(child);
21229 * Returns the tree this node is in.
21232 getOwnerTree : function(){
21233 // if it doesn't have one, look for one
21234 if(!this.ownerTree){
21238 this.ownerTree = p.ownerTree;
21244 return this.ownerTree;
21248 * Returns depth of this node (the root node has a depth of 0)
21251 getDepth : function(){
21254 while(p.parentNode){
21262 setOwnerTree : function(tree){
21263 // if it's move, we need to update everyone
21264 if(tree != this.ownerTree){
21265 if(this.ownerTree){
21266 this.ownerTree.unregisterNode(this);
21268 this.ownerTree = tree;
21269 var cs = this.childNodes;
21270 for(var i = 0, len = cs.length; i < len; i++) {
21271 cs[i].setOwnerTree(tree);
21274 tree.registerNode(this);
21280 * Returns the path for this node. The path can be used to expand or select this node programmatically.
21281 * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
21282 * @return {String} The path
21284 getPath : function(attr){
21285 attr = attr || "id";
21286 var p = this.parentNode;
21287 var b = [this.attributes[attr]];
21289 b.unshift(p.attributes[attr]);
21292 var sep = this.getOwnerTree().pathSeparator;
21293 return sep + b.join(sep);
21297 * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
21298 * function call will be the scope provided or the current node. The arguments to the function
21299 * will be the args provided or the current node. If the function returns false at any point,
21300 * the bubble is stopped.
21301 * @param {Function} fn The function to call
21302 * @param {Object} scope (optional) The scope of the function (defaults to current node)
21303 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
21305 bubble : function(fn, scope, args){
21308 if(fn.call(scope || p, args || p) === false){
21316 * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
21317 * function call will be the scope provided or the current node. The arguments to the function
21318 * will be the args provided or the current node. If the function returns false at any point,
21319 * the cascade is stopped on that branch.
21320 * @param {Function} fn The function to call
21321 * @param {Object} scope (optional) The scope of the function (defaults to current node)
21322 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
21324 cascade : function(fn, scope, args){
21325 if(fn.call(scope || this, args || this) !== false){
21326 var cs = this.childNodes;
21327 for(var i = 0, len = cs.length; i < len; i++) {
21328 cs[i].cascade(fn, scope, args);
21334 * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
21335 * function call will be the scope provided or the current node. The arguments to the function
21336 * will be the args provided or the current node. If the function returns false at any point,
21337 * the iteration stops.
21338 * @param {Function} fn The function to call
21339 * @param {Object} scope (optional) The scope of the function (defaults to current node)
21340 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
21342 eachChild : function(fn, scope, args){
21343 var cs = this.childNodes;
21344 for(var i = 0, len = cs.length; i < len; i++) {
21345 if(fn.call(scope || this, args || cs[i]) === false){
21352 * Finds the first child that has the attribute with the specified value.
21353 * @param {String} attribute The attribute name
21354 * @param {Mixed} value The value to search for
21355 * @return {Node} The found child or null if none was found
21357 findChild : function(attribute, value){
21358 var cs = this.childNodes;
21359 for(var i = 0, len = cs.length; i < len; i++) {
21360 if(cs[i].attributes[attribute] == value){
21368 * Finds the first child by a custom function. The child matches if the function passed
21370 * @param {Function} fn
21371 * @param {Object} scope (optional)
21372 * @return {Node} The found child or null if none was found
21374 findChildBy : function(fn, scope){
21375 var cs = this.childNodes;
21376 for(var i = 0, len = cs.length; i < len; i++) {
21377 if(fn.call(scope||cs[i], cs[i]) === true){
21385 * Sorts this nodes children using the supplied sort function
21386 * @param {Function} fn
21387 * @param {Object} scope (optional)
21389 sort : function(fn, scope){
21390 var cs = this.childNodes;
21391 var len = cs.length;
21393 var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
21395 for(var i = 0; i < len; i++){
21397 n.previousSibling = cs[i-1];
21398 n.nextSibling = cs[i+1];
21400 this.setFirstChild(n);
21403 this.setLastChild(n);
21410 * Returns true if this node is an ancestor (at any point) of the passed node.
21411 * @param {Node} node
21412 * @return {Boolean}
21414 contains : function(node){
21415 return node.isAncestor(this);
21419 * Returns true if the passed node is an ancestor (at any point) of this node.
21420 * @param {Node} node
21421 * @return {Boolean}
21423 isAncestor : function(node){
21424 var p = this.parentNode;
21434 toString : function(){
21435 return "[Node"+(this.id?" "+this.id:"")+"]";
21439 * Ext JS Library 1.1.1
21440 * Copyright(c) 2006-2007, Ext JS, LLC.
21442 * Originally Released Under LGPL - original licence link has changed is not relivant.
21445 * <script type="text/javascript">
21450 * @class Roo.ComponentMgr
21451 * Provides a common registry of all components on a page so that they can be easily accessed by component id (see {@link Roo.getCmp}).
21454 Roo.ComponentMgr = function(){
21455 var all = new Roo.util.MixedCollection();
21459 * Registers a component.
21460 * @param {Roo.Component} c The component
21462 register : function(c){
21467 * Unregisters a component.
21468 * @param {Roo.Component} c The component
21470 unregister : function(c){
21475 * Returns a component by id
21476 * @param {String} id The component id
21478 get : function(id){
21479 return all.get(id);
21483 * Registers a function that will be called when a specified component is added to ComponentMgr
21484 * @param {String} id The component id
21485 * @param {Funtction} fn The callback function
21486 * @param {Object} scope The scope of the callback
21488 onAvailable : function(id, fn, scope){
21489 all.on("add", function(index, o){
21491 fn.call(scope || o, o);
21492 all.un("add", fn, scope);
21499 * Ext JS Library 1.1.1
21500 * Copyright(c) 2006-2007, Ext JS, LLC.
21502 * Originally Released Under LGPL - original licence link has changed is not relivant.
21505 * <script type="text/javascript">
21509 * @class Roo.Component
21510 * @extends Roo.util.Observable
21511 * Base class for all major Roo components. All subclasses of Component can automatically participate in the standard
21512 * Roo component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show
21513 * and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Roo.Container} and
21514 * to be automatically registered with the {@link Roo.ComponentMgr} so that it can be referenced at any time via {@link Roo.getCmp}.
21515 * All visual components (widgets) that require rendering into a layout should subclass Component.
21517 * @param {Roo.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
21518 * element and its id used as the component id. If a string is passed, it is assumed to be the id of an existing element
21519 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
21521 Roo.Component = function(config){
21522 config = config || {};
21523 if(config.tagName || config.dom || typeof config == "string"){ // element object
21524 config = {el: config, id: config.id || config};
21526 this.initialConfig = config;
21528 Roo.apply(this, config);
21532 * Fires after the component is disabled.
21533 * @param {Roo.Component} this
21538 * Fires after the component is enabled.
21539 * @param {Roo.Component} this
21543 * @event beforeshow
21544 * Fires before the component is shown. Return false to stop the show.
21545 * @param {Roo.Component} this
21550 * Fires after the component is shown.
21551 * @param {Roo.Component} this
21555 * @event beforehide
21556 * Fires before the component is hidden. Return false to stop the hide.
21557 * @param {Roo.Component} this
21562 * Fires after the component is hidden.
21563 * @param {Roo.Component} this
21567 * @event beforerender
21568 * Fires before the component is rendered. Return false to stop the render.
21569 * @param {Roo.Component} this
21571 beforerender : true,
21574 * Fires after the component is rendered.
21575 * @param {Roo.Component} this
21579 * @event beforedestroy
21580 * Fires before the component is destroyed. Return false to stop the destroy.
21581 * @param {Roo.Component} this
21583 beforedestroy : true,
21586 * Fires after the component is destroyed.
21587 * @param {Roo.Component} this
21592 this.id = "ext-comp-" + (++Roo.Component.AUTO_ID);
21594 Roo.ComponentMgr.register(this);
21595 Roo.Component.superclass.constructor.call(this);
21596 this.initComponent();
21597 if(this.renderTo){ // not supported by all components yet. use at your own risk!
21598 this.render(this.renderTo);
21599 delete this.renderTo;
21604 Roo.Component.AUTO_ID = 1000;
21606 Roo.extend(Roo.Component, Roo.util.Observable, {
21608 * @property {Boolean} hidden
21609 * true if this component is hidden. Read-only.
21613 * true if this component is disabled. Read-only.
21617 * true if this component has been rendered. Read-only.
21621 /** @cfg {String} disableClass
21622 * CSS class added to the component when it is disabled (defaults to "x-item-disabled").
21624 disabledClass : "x-item-disabled",
21625 /** @cfg {Boolean} allowDomMove
21626 * Whether the component can move the Dom node when rendering (defaults to true).
21628 allowDomMove : true,
21629 /** @cfg {String} hideMode
21630 * How this component should hidden. Supported values are
21631 * "visibility" (css visibility), "offsets" (negative offset position) and
21632 * "display" (css display) - defaults to "display".
21634 hideMode: 'display',
21637 ctype : "Roo.Component",
21639 /** @cfg {String} actionMode
21640 * which property holds the element that used for hide() / show() / disable() / enable()
21646 getActionEl : function(){
21647 return this[this.actionMode];
21650 initComponent : Roo.emptyFn,
21652 * If this is a lazy rendering component, render it to its container element.
21653 * @param {String/HTMLElement/Element} container (optional) The element this component should be rendered into. If it is being applied to existing markup, this should be left off.
21655 render : function(container, position){
21656 if(!this.rendered && this.fireEvent("beforerender", this) !== false){
21657 if(!container && this.el){
21658 this.el = Roo.get(this.el);
21659 container = this.el.dom.parentNode;
21660 this.allowDomMove = false;
21662 this.container = Roo.get(container);
21663 this.rendered = true;
21664 if(position !== undefined){
21665 if(typeof position == 'number'){
21666 position = this.container.dom.childNodes[position];
21668 position = Roo.getDom(position);
21671 this.onRender(this.container, position || null);
21673 this.el.addClass(this.cls);
21677 this.el.applyStyles(this.style);
21680 this.fireEvent("render", this);
21681 this.afterRender(this.container);
21693 // default function is not really useful
21694 onRender : function(ct, position){
21696 this.el = Roo.get(this.el);
21697 if(this.allowDomMove !== false){
21698 ct.dom.insertBefore(this.el.dom, position);
21704 getAutoCreate : function(){
21705 var cfg = typeof this.autoCreate == "object" ?
21706 this.autoCreate : Roo.apply({}, this.defaultAutoCreate);
21707 if(this.id && !cfg.id){
21714 afterRender : Roo.emptyFn,
21717 * Destroys this component by purging any event listeners, removing the component's element from the DOM,
21718 * removing the component from its {@link Roo.Container} (if applicable) and unregistering it from {@link Roo.ComponentMgr}.
21720 destroy : function(){
21721 if(this.fireEvent("beforedestroy", this) !== false){
21722 this.purgeListeners();
21723 this.beforeDestroy();
21725 this.el.removeAllListeners();
21727 if(this.actionMode == "container"){
21728 this.container.remove();
21732 Roo.ComponentMgr.unregister(this);
21733 this.fireEvent("destroy", this);
21738 beforeDestroy : function(){
21743 onDestroy : function(){
21748 * Returns the underlying {@link Roo.Element}.
21749 * @return {Roo.Element} The element
21751 getEl : function(){
21756 * Returns the id of this component.
21759 getId : function(){
21764 * Try to focus this component.
21765 * @param {Boolean} selectText True to also select the text in this component (if applicable)
21766 * @return {Roo.Component} this
21768 focus : function(selectText){
21771 if(selectText === true){
21772 this.el.dom.select();
21787 * Disable this component.
21788 * @return {Roo.Component} this
21790 disable : function(){
21794 this.disabled = true;
21795 this.fireEvent("disable", this);
21800 onDisable : function(){
21801 this.getActionEl().addClass(this.disabledClass);
21802 this.el.dom.disabled = true;
21806 * Enable this component.
21807 * @return {Roo.Component} this
21809 enable : function(){
21813 this.disabled = false;
21814 this.fireEvent("enable", this);
21819 onEnable : function(){
21820 this.getActionEl().removeClass(this.disabledClass);
21821 this.el.dom.disabled = false;
21825 * Convenience function for setting disabled/enabled by boolean.
21826 * @param {Boolean} disabled
21828 setDisabled : function(disabled){
21829 this[disabled ? "disable" : "enable"]();
21833 * Show this component.
21834 * @return {Roo.Component} this
21837 if(this.fireEvent("beforeshow", this) !== false){
21838 this.hidden = false;
21842 this.fireEvent("show", this);
21848 onShow : function(){
21849 var ae = this.getActionEl();
21850 if(this.hideMode == 'visibility'){
21851 ae.dom.style.visibility = "visible";
21852 }else if(this.hideMode == 'offsets'){
21853 ae.removeClass('x-hidden');
21855 ae.dom.style.display = "";
21860 * Hide this component.
21861 * @return {Roo.Component} this
21864 if(this.fireEvent("beforehide", this) !== false){
21865 this.hidden = true;
21869 this.fireEvent("hide", this);
21875 onHide : function(){
21876 var ae = this.getActionEl();
21877 if(this.hideMode == 'visibility'){
21878 ae.dom.style.visibility = "hidden";
21879 }else if(this.hideMode == 'offsets'){
21880 ae.addClass('x-hidden');
21882 ae.dom.style.display = "none";
21887 * Convenience function to hide or show this component by boolean.
21888 * @param {Boolean} visible True to show, false to hide
21889 * @return {Roo.Component} this
21891 setVisible: function(visible){
21901 * Returns true if this component is visible.
21903 isVisible : function(){
21904 return this.getActionEl().isVisible();
21907 cloneConfig : function(overrides){
21908 overrides = overrides || {};
21909 var id = overrides.id || Roo.id();
21910 var cfg = Roo.applyIf(overrides, this.initialConfig);
21911 cfg.id = id; // prevent dup id
21912 return new this.constructor(cfg);
21916 * Ext JS Library 1.1.1
21917 * Copyright(c) 2006-2007, Ext JS, LLC.
21919 * Originally Released Under LGPL - original licence link has changed is not relivant.
21922 * <script type="text/javascript">
21927 * @extends Roo.Element
21928 * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
21929 * automatic maintaining of shadow/shim positions.
21930 * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
21931 * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
21932 * you can pass a string with a CSS class name. False turns off the shadow.
21933 * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
21934 * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
21935 * @cfg {String} cls CSS class to add to the element
21936 * @cfg {Number} zindex Starting z-index (defaults to 11000)
21937 * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
21939 * @param {Object} config An object with config options.
21940 * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
21943 Roo.Layer = function(config, existingEl){
21944 config = config || {};
21945 var dh = Roo.DomHelper;
21946 var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
21948 this.dom = Roo.getDom(existingEl);
21951 var o = config.dh || {tag: "div", cls: "x-layer"};
21952 this.dom = dh.append(pel, o);
21955 this.addClass(config.cls);
21957 this.constrain = config.constrain !== false;
21958 this.visibilityMode = Roo.Element.VISIBILITY;
21960 this.id = this.dom.id = config.id;
21962 this.id = Roo.id(this.dom);
21964 this.zindex = config.zindex || this.getZIndex();
21965 this.position("absolute", this.zindex);
21967 this.shadowOffset = config.shadowOffset || 4;
21968 this.shadow = new Roo.Shadow({
21969 offset : this.shadowOffset,
21970 mode : config.shadow
21973 this.shadowOffset = 0;
21975 this.useShim = config.shim !== false && Roo.useShims;
21976 this.useDisplay = config.useDisplay;
21980 var supr = Roo.Element.prototype;
21982 // shims are shared among layer to keep from having 100 iframes
21985 Roo.extend(Roo.Layer, Roo.Element, {
21987 getZIndex : function(){
21988 return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
21991 getShim : function(){
21998 var shim = shims.shift();
22000 shim = this.createShim();
22001 shim.enableDisplayMode('block');
22002 shim.dom.style.display = 'none';
22003 shim.dom.style.visibility = 'visible';
22005 var pn = this.dom.parentNode;
22006 if(shim.dom.parentNode != pn){
22007 pn.insertBefore(shim.dom, this.dom);
22009 shim.setStyle('z-index', this.getZIndex()-2);
22014 hideShim : function(){
22016 this.shim.setDisplayed(false);
22017 shims.push(this.shim);
22022 disableShadow : function(){
22024 this.shadowDisabled = true;
22025 this.shadow.hide();
22026 this.lastShadowOffset = this.shadowOffset;
22027 this.shadowOffset = 0;
22031 enableShadow : function(show){
22033 this.shadowDisabled = false;
22034 this.shadowOffset = this.lastShadowOffset;
22035 delete this.lastShadowOffset;
22043 // this code can execute repeatedly in milliseconds (i.e. during a drag) so
22044 // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
22045 sync : function(doShow){
22046 var sw = this.shadow;
22047 if(!this.updating && this.isVisible() && (sw || this.useShim)){
22048 var sh = this.getShim();
22050 var w = this.getWidth(),
22051 h = this.getHeight();
22053 var l = this.getLeft(true),
22054 t = this.getTop(true);
22056 if(sw && !this.shadowDisabled){
22057 if(doShow && !sw.isVisible()){
22060 sw.realign(l, t, w, h);
22066 // fit the shim behind the shadow, so it is shimmed too
22067 var a = sw.adjusts, s = sh.dom.style;
22068 s.left = (Math.min(l, l+a.l))+"px";
22069 s.top = (Math.min(t, t+a.t))+"px";
22070 s.width = (w+a.w)+"px";
22071 s.height = (h+a.h)+"px";
22078 sh.setLeftTop(l, t);
22085 destroy : function(){
22088 this.shadow.hide();
22090 this.removeAllListeners();
22091 var pn = this.dom.parentNode;
22093 pn.removeChild(this.dom);
22095 Roo.Element.uncache(this.id);
22098 remove : function(){
22103 beginUpdate : function(){
22104 this.updating = true;
22108 endUpdate : function(){
22109 this.updating = false;
22114 hideUnders : function(negOffset){
22116 this.shadow.hide();
22122 constrainXY : function(){
22123 if(this.constrain){
22124 var vw = Roo.lib.Dom.getViewWidth(),
22125 vh = Roo.lib.Dom.getViewHeight();
22126 var s = Roo.get(document).getScroll();
22128 var xy = this.getXY();
22129 var x = xy[0], y = xy[1];
22130 var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
22131 // only move it if it needs it
22133 // first validate right/bottom
22134 if((x + w) > vw+s.left){
22135 x = vw - w - this.shadowOffset;
22138 if((y + h) > vh+s.top){
22139 y = vh - h - this.shadowOffset;
22142 // then make sure top/left isn't negative
22153 var ay = this.avoidY;
22154 if(y <= ay && (y+h) >= ay){
22160 supr.setXY.call(this, xy);
22166 isVisible : function(){
22167 return this.visible;
22171 showAction : function(){
22172 this.visible = true; // track visibility to prevent getStyle calls
22173 if(this.useDisplay === true){
22174 this.setDisplayed("");
22175 }else if(this.lastXY){
22176 supr.setXY.call(this, this.lastXY);
22177 }else if(this.lastLT){
22178 supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
22183 hideAction : function(){
22184 this.visible = false;
22185 if(this.useDisplay === true){
22186 this.setDisplayed(false);
22188 this.setLeftTop(-10000,-10000);
22192 // overridden Element method
22193 setVisible : function(v, a, d, c, e){
22198 var cb = function(){
22203 }.createDelegate(this);
22204 supr.setVisible.call(this, true, true, d, cb, e);
22207 this.hideUnders(true);
22216 }.createDelegate(this);
22218 supr.setVisible.call(this, v, a, d, cb, e);
22227 storeXY : function(xy){
22228 delete this.lastLT;
22232 storeLeftTop : function(left, top){
22233 delete this.lastXY;
22234 this.lastLT = [left, top];
22238 beforeFx : function(){
22239 this.beforeAction();
22240 return Roo.Layer.superclass.beforeFx.apply(this, arguments);
22244 afterFx : function(){
22245 Roo.Layer.superclass.afterFx.apply(this, arguments);
22246 this.sync(this.isVisible());
22250 beforeAction : function(){
22251 if(!this.updating && this.shadow){
22252 this.shadow.hide();
22256 // overridden Element method
22257 setLeft : function(left){
22258 this.storeLeftTop(left, this.getTop(true));
22259 supr.setLeft.apply(this, arguments);
22263 setTop : function(top){
22264 this.storeLeftTop(this.getLeft(true), top);
22265 supr.setTop.apply(this, arguments);
22269 setLeftTop : function(left, top){
22270 this.storeLeftTop(left, top);
22271 supr.setLeftTop.apply(this, arguments);
22275 setXY : function(xy, a, d, c, e){
22277 this.beforeAction();
22279 var cb = this.createCB(c);
22280 supr.setXY.call(this, xy, a, d, cb, e);
22287 createCB : function(c){
22298 // overridden Element method
22299 setX : function(x, a, d, c, e){
22300 this.setXY([x, this.getY()], a, d, c, e);
22303 // overridden Element method
22304 setY : function(y, a, d, c, e){
22305 this.setXY([this.getX(), y], a, d, c, e);
22308 // overridden Element method
22309 setSize : function(w, h, a, d, c, e){
22310 this.beforeAction();
22311 var cb = this.createCB(c);
22312 supr.setSize.call(this, w, h, a, d, cb, e);
22318 // overridden Element method
22319 setWidth : function(w, a, d, c, e){
22320 this.beforeAction();
22321 var cb = this.createCB(c);
22322 supr.setWidth.call(this, w, a, d, cb, e);
22328 // overridden Element method
22329 setHeight : function(h, a, d, c, e){
22330 this.beforeAction();
22331 var cb = this.createCB(c);
22332 supr.setHeight.call(this, h, a, d, cb, e);
22338 // overridden Element method
22339 setBounds : function(x, y, w, h, a, d, c, e){
22340 this.beforeAction();
22341 var cb = this.createCB(c);
22343 this.storeXY([x, y]);
22344 supr.setXY.call(this, [x, y]);
22345 supr.setSize.call(this, w, h, a, d, cb, e);
22348 supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
22354 * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
22355 * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
22356 * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
22357 * @param {Number} zindex The new z-index to set
22358 * @return {this} The Layer
22360 setZIndex : function(zindex){
22361 this.zindex = zindex;
22362 this.setStyle("z-index", zindex + 2);
22364 this.shadow.setZIndex(zindex + 1);
22367 this.shim.setStyle("z-index", zindex);
22373 * Ext JS Library 1.1.1
22374 * Copyright(c) 2006-2007, Ext JS, LLC.
22376 * Originally Released Under LGPL - original licence link has changed is not relivant.
22379 * <script type="text/javascript">
22384 * @class Roo.Shadow
22385 * Simple class that can provide a shadow effect for any element. Note that the element MUST be absolutely positioned,
22386 * and the shadow does not provide any shimming. This should be used only in simple cases -- for more advanced
22387 * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
22389 * Create a new Shadow
22390 * @param {Object} config The config object
22392 Roo.Shadow = function(config){
22393 Roo.apply(this, config);
22394 if(typeof this.mode != "string"){
22395 this.mode = this.defaultMode;
22397 var o = this.offset, a = {h: 0};
22398 var rad = Math.floor(this.offset/2);
22399 switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
22405 a.l -= this.offset + rad;
22406 a.t -= this.offset + rad;
22417 a.l -= (this.offset - rad);
22418 a.t -= this.offset + rad;
22420 a.w -= (this.offset - rad)*2;
22431 a.l -= (this.offset - rad);
22432 a.t -= (this.offset - rad);
22434 a.w -= (this.offset + rad + 1);
22435 a.h -= (this.offset + rad);
22444 Roo.Shadow.prototype = {
22446 * @cfg {String} mode
22447 * The shadow display mode. Supports the following options:<br />
22448 * sides: Shadow displays on both sides and bottom only<br />
22449 * frame: Shadow displays equally on all four sides<br />
22450 * drop: Traditional bottom-right drop shadow (default)
22453 * @cfg {String} offset
22454 * The number of pixels to offset the shadow from the element (defaults to 4)
22459 defaultMode: "drop",
22462 * Displays the shadow under the target element
22463 * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
22465 show : function(target){
22466 target = Roo.get(target);
22468 this.el = Roo.Shadow.Pool.pull();
22469 if(this.el.dom.nextSibling != target.dom){
22470 this.el.insertBefore(target);
22473 this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
22475 this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
22478 target.getLeft(true),
22479 target.getTop(true),
22483 this.el.dom.style.display = "block";
22487 * Returns true if the shadow is visible, else false
22489 isVisible : function(){
22490 return this.el ? true : false;
22494 * Direct alignment when values are already available. Show must be called at least once before
22495 * calling this method to ensure it is initialized.
22496 * @param {Number} left The target element left position
22497 * @param {Number} top The target element top position
22498 * @param {Number} width The target element width
22499 * @param {Number} height The target element height
22501 realign : function(l, t, w, h){
22505 var a = this.adjusts, d = this.el.dom, s = d.style;
22507 s.left = (l+a.l)+"px";
22508 s.top = (t+a.t)+"px";
22509 var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
22510 if(s.width != sws || s.height != shs){
22514 var cn = d.childNodes;
22515 var sww = Math.max(0, (sw-12))+"px";
22516 cn[0].childNodes[1].style.width = sww;
22517 cn[1].childNodes[1].style.width = sww;
22518 cn[2].childNodes[1].style.width = sww;
22519 cn[1].style.height = Math.max(0, (sh-12))+"px";
22525 * Hides this shadow
22529 this.el.dom.style.display = "none";
22530 Roo.Shadow.Pool.push(this.el);
22536 * Adjust the z-index of this shadow
22537 * @param {Number} zindex The new z-index
22539 setZIndex : function(z){
22542 this.el.setStyle("z-index", z);
22547 // Private utility class that manages the internal Shadow cache
22548 Roo.Shadow.Pool = function(){
22550 var markup = Roo.isIE ?
22551 '<div class="x-ie-shadow"></div>' :
22552 '<div class="x-shadow"><div class="xst"><div class="xstl"></div><div class="xstc"></div><div class="xstr"></div></div><div class="xsc"><div class="xsml"></div><div class="xsmc"></div><div class="xsmr"></div></div><div class="xsb"><div class="xsbl"></div><div class="xsbc"></div><div class="xsbr"></div></div></div>';
22555 var sh = p.shift();
22557 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
22558 sh.autoBoxAdjust = false;
22563 push : function(sh){
22569 * Ext JS Library 1.1.1
22570 * Copyright(c) 2006-2007, Ext JS, LLC.
22572 * Originally Released Under LGPL - original licence link has changed is not relivant.
22575 * <script type="text/javascript">
22579 * @class Roo.BoxComponent
22580 * @extends Roo.Component
22581 * Base class for any visual {@link Roo.Component} that uses a box container. BoxComponent provides automatic box
22582 * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model. All
22583 * container classes should subclass BoxComponent so that they will work consistently when nested within other Ext
22584 * layout containers.
22586 * @param {Roo.Element/String/Object} config The configuration options.
22588 Roo.BoxComponent = function(config){
22589 Roo.Component.call(this, config);
22593 * Fires after the component is resized.
22594 * @param {Roo.Component} this
22595 * @param {Number} adjWidth The box-adjusted width that was set
22596 * @param {Number} adjHeight The box-adjusted height that was set
22597 * @param {Number} rawWidth The width that was originally specified
22598 * @param {Number} rawHeight The height that was originally specified
22603 * Fires after the component is moved.
22604 * @param {Roo.Component} this
22605 * @param {Number} x The new x position
22606 * @param {Number} y The new y position
22612 Roo.extend(Roo.BoxComponent, Roo.Component, {
22613 // private, set in afterRender to signify that the component has been rendered
22615 // private, used to defer height settings to subclasses
22616 deferHeight: false,
22617 /** @cfg {Number} width
22618 * width (optional) size of component
22620 /** @cfg {Number} height
22621 * height (optional) size of component
22625 * Sets the width and height of the component. This method fires the resize event. This method can accept
22626 * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
22627 * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
22628 * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
22629 * @return {Roo.BoxComponent} this
22631 setSize : function(w, h){
22632 // support for standard size objects
22633 if(typeof w == 'object'){
22638 if(!this.boxReady){
22644 // prevent recalcs when not needed
22645 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
22648 this.lastSize = {width: w, height: h};
22650 var adj = this.adjustSize(w, h);
22651 var aw = adj.width, ah = adj.height;
22652 if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
22653 var rz = this.getResizeEl();
22654 if(!this.deferHeight && aw !== undefined && ah !== undefined){
22655 rz.setSize(aw, ah);
22656 }else if(!this.deferHeight && ah !== undefined){
22658 }else if(aw !== undefined){
22661 this.onResize(aw, ah, w, h);
22662 this.fireEvent('resize', this, aw, ah, w, h);
22668 * Gets the current size of the component's underlying element.
22669 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
22671 getSize : function(){
22672 return this.el.getSize();
22676 * Gets the current XY position of the component's underlying element.
22677 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
22678 * @return {Array} The XY position of the element (e.g., [100, 200])
22680 getPosition : function(local){
22681 if(local === true){
22682 return [this.el.getLeft(true), this.el.getTop(true)];
22684 return this.xy || this.el.getXY();
22688 * Gets the current box measurements of the component's underlying element.
22689 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
22690 * @returns {Object} box An object in the format {x, y, width, height}
22692 getBox : function(local){
22693 var s = this.el.getSize();
22695 s.x = this.el.getLeft(true);
22696 s.y = this.el.getTop(true);
22698 var xy = this.xy || this.el.getXY();
22706 * Sets the current box measurements of the component's underlying element.
22707 * @param {Object} box An object in the format {x, y, width, height}
22708 * @returns {Roo.BoxComponent} this
22710 updateBox : function(box){
22711 this.setSize(box.width, box.height);
22712 this.setPagePosition(box.x, box.y);
22717 getResizeEl : function(){
22718 return this.resizeEl || this.el;
22722 getPositionEl : function(){
22723 return this.positionEl || this.el;
22727 * Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}.
22728 * This method fires the move event.
22729 * @param {Number} left The new left
22730 * @param {Number} top The new top
22731 * @returns {Roo.BoxComponent} this
22733 setPosition : function(x, y){
22736 if(!this.boxReady){
22739 var adj = this.adjustPosition(x, y);
22740 var ax = adj.x, ay = adj.y;
22742 var el = this.getPositionEl();
22743 if(ax !== undefined || ay !== undefined){
22744 if(ax !== undefined && ay !== undefined){
22745 el.setLeftTop(ax, ay);
22746 }else if(ax !== undefined){
22748 }else if(ay !== undefined){
22751 this.onPosition(ax, ay);
22752 this.fireEvent('move', this, ax, ay);
22758 * Sets the page XY position of the component. To set the left and top instead, use {@link #setPosition}.
22759 * This method fires the move event.
22760 * @param {Number} x The new x position
22761 * @param {Number} y The new y position
22762 * @returns {Roo.BoxComponent} this
22764 setPagePosition : function(x, y){
22767 if(!this.boxReady){
22770 if(x === undefined || y === undefined){ // cannot translate undefined points
22773 var p = this.el.translatePoints(x, y);
22774 this.setPosition(p.left, p.top);
22779 onRender : function(ct, position){
22780 Roo.BoxComponent.superclass.onRender.call(this, ct, position);
22782 this.resizeEl = Roo.get(this.resizeEl);
22784 if(this.positionEl){
22785 this.positionEl = Roo.get(this.positionEl);
22790 afterRender : function(){
22791 Roo.BoxComponent.superclass.afterRender.call(this);
22792 this.boxReady = true;
22793 this.setSize(this.width, this.height);
22794 if(this.x || this.y){
22795 this.setPosition(this.x, this.y);
22797 if(this.pageX || this.pageY){
22798 this.setPagePosition(this.pageX, this.pageY);
22803 * Force the component's size to recalculate based on the underlying element's current height and width.
22804 * @returns {Roo.BoxComponent} this
22806 syncSize : function(){
22807 delete this.lastSize;
22808 this.setSize(this.el.getWidth(), this.el.getHeight());
22813 * Called after the component is resized, this method is empty by default but can be implemented by any
22814 * subclass that needs to perform custom logic after a resize occurs.
22815 * @param {Number} adjWidth The box-adjusted width that was set
22816 * @param {Number} adjHeight The box-adjusted height that was set
22817 * @param {Number} rawWidth The width that was originally specified
22818 * @param {Number} rawHeight The height that was originally specified
22820 onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
22825 * Called after the component is moved, this method is empty by default but can be implemented by any
22826 * subclass that needs to perform custom logic after a move occurs.
22827 * @param {Number} x The new x position
22828 * @param {Number} y The new y position
22830 onPosition : function(x, y){
22835 adjustSize : function(w, h){
22836 if(this.autoWidth){
22839 if(this.autoHeight){
22842 return {width : w, height: h};
22846 adjustPosition : function(x, y){
22847 return {x : x, y: y};
22851 * Ext JS Library 1.1.1
22852 * Copyright(c) 2006-2007, Ext JS, LLC.
22854 * Originally Released Under LGPL - original licence link has changed is not relivant.
22857 * <script type="text/javascript">
22862 * @class Roo.SplitBar
22863 * @extends Roo.util.Observable
22864 * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
22868 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
22869 Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
22870 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
22871 split.minSize = 100;
22872 split.maxSize = 600;
22873 split.animate = true;
22874 split.on('moved', splitterMoved);
22877 * Create a new SplitBar
22878 * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar.
22879 * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged
22880 * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
22881 * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or
22882 Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
22883 position of the SplitBar).
22885 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
22888 this.el = Roo.get(dragElement, true);
22889 this.el.dom.unselectable = "on";
22891 this.resizingEl = Roo.get(resizingElement, true);
22895 * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
22896 * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
22899 this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
22902 * The minimum size of the resizing element. (Defaults to 0)
22908 * The maximum size of the resizing element. (Defaults to 2000)
22911 this.maxSize = 2000;
22914 * Whether to animate the transition to the new size
22917 this.animate = false;
22920 * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
22923 this.useShim = false;
22928 if(!existingProxy){
22930 this.proxy = Roo.SplitBar.createProxy(this.orientation);
22932 this.proxy = Roo.get(existingProxy).dom;
22935 this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
22938 this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
22941 this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
22944 this.dragSpecs = {};
22947 * @private The adapter to use to positon and resize elements
22949 this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
22950 this.adapter.init(this);
22952 if(this.orientation == Roo.SplitBar.HORIZONTAL){
22954 this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
22955 this.el.addClass("x-splitbar-h");
22958 this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
22959 this.el.addClass("x-splitbar-v");
22965 * Fires when the splitter is moved (alias for {@link #event-moved})
22966 * @param {Roo.SplitBar} this
22967 * @param {Number} newSize the new width or height
22972 * Fires when the splitter is moved
22973 * @param {Roo.SplitBar} this
22974 * @param {Number} newSize the new width or height
22978 * @event beforeresize
22979 * Fires before the splitter is dragged
22980 * @param {Roo.SplitBar} this
22982 "beforeresize" : true,
22984 "beforeapply" : true
22987 Roo.util.Observable.call(this);
22990 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
22991 onStartProxyDrag : function(x, y){
22992 this.fireEvent("beforeresize", this);
22994 var o = Roo.DomHelper.insertFirst(document.body, {cls: "x-drag-overlay", html: " "}, true);
22996 o.enableDisplayMode("block");
22997 // all splitbars share the same overlay
22998 Roo.SplitBar.prototype.overlay = o;
23000 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
23001 this.overlay.show();
23002 Roo.get(this.proxy).setDisplayed("block");
23003 var size = this.adapter.getElementSize(this);
23004 this.activeMinSize = this.getMinimumSize();;
23005 this.activeMaxSize = this.getMaximumSize();;
23006 var c1 = size - this.activeMinSize;
23007 var c2 = Math.max(this.activeMaxSize - size, 0);
23008 if(this.orientation == Roo.SplitBar.HORIZONTAL){
23009 this.dd.resetConstraints();
23010 this.dd.setXConstraint(
23011 this.placement == Roo.SplitBar.LEFT ? c1 : c2,
23012 this.placement == Roo.SplitBar.LEFT ? c2 : c1
23014 this.dd.setYConstraint(0, 0);
23016 this.dd.resetConstraints();
23017 this.dd.setXConstraint(0, 0);
23018 this.dd.setYConstraint(
23019 this.placement == Roo.SplitBar.TOP ? c1 : c2,
23020 this.placement == Roo.SplitBar.TOP ? c2 : c1
23023 this.dragSpecs.startSize = size;
23024 this.dragSpecs.startPoint = [x, y];
23025 Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
23029 * @private Called after the drag operation by the DDProxy
23031 onEndProxyDrag : function(e){
23032 Roo.get(this.proxy).setDisplayed(false);
23033 var endPoint = Roo.lib.Event.getXY(e);
23035 this.overlay.hide();
23038 if(this.orientation == Roo.SplitBar.HORIZONTAL){
23039 newSize = this.dragSpecs.startSize +
23040 (this.placement == Roo.SplitBar.LEFT ?
23041 endPoint[0] - this.dragSpecs.startPoint[0] :
23042 this.dragSpecs.startPoint[0] - endPoint[0]
23045 newSize = this.dragSpecs.startSize +
23046 (this.placement == Roo.SplitBar.TOP ?
23047 endPoint[1] - this.dragSpecs.startPoint[1] :
23048 this.dragSpecs.startPoint[1] - endPoint[1]
23051 newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
23052 if(newSize != this.dragSpecs.startSize){
23053 if(this.fireEvent('beforeapply', this, newSize) !== false){
23054 this.adapter.setElementSize(this, newSize);
23055 this.fireEvent("moved", this, newSize);
23056 this.fireEvent("resize", this, newSize);
23062 * Get the adapter this SplitBar uses
23063 * @return The adapter object
23065 getAdapter : function(){
23066 return this.adapter;
23070 * Set the adapter this SplitBar uses
23071 * @param {Object} adapter A SplitBar adapter object
23073 setAdapter : function(adapter){
23074 this.adapter = adapter;
23075 this.adapter.init(this);
23079 * Gets the minimum size for the resizing element
23080 * @return {Number} The minimum size
23082 getMinimumSize : function(){
23083 return this.minSize;
23087 * Sets the minimum size for the resizing element
23088 * @param {Number} minSize The minimum size
23090 setMinimumSize : function(minSize){
23091 this.minSize = minSize;
23095 * Gets the maximum size for the resizing element
23096 * @return {Number} The maximum size
23098 getMaximumSize : function(){
23099 return this.maxSize;
23103 * Sets the maximum size for the resizing element
23104 * @param {Number} maxSize The maximum size
23106 setMaximumSize : function(maxSize){
23107 this.maxSize = maxSize;
23111 * Sets the initialize size for the resizing element
23112 * @param {Number} size The initial size
23114 setCurrentSize : function(size){
23115 var oldAnimate = this.animate;
23116 this.animate = false;
23117 this.adapter.setElementSize(this, size);
23118 this.animate = oldAnimate;
23122 * Destroy this splitbar.
23123 * @param {Boolean} removeEl True to remove the element
23125 destroy : function(removeEl){
23127 this.shim.remove();
23130 this.proxy.parentNode.removeChild(this.proxy);
23138 * @private static Create our own proxy element element. So it will be the same same size on all browsers, we won't use borders. Instead we use a background color.
23140 Roo.SplitBar.createProxy = function(dir){
23141 var proxy = new Roo.Element(document.createElement("div"));
23142 proxy.unselectable();
23143 var cls = 'x-splitbar-proxy';
23144 proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
23145 document.body.appendChild(proxy.dom);
23150 * @class Roo.SplitBar.BasicLayoutAdapter
23151 * Default Adapter. It assumes the splitter and resizing element are not positioned
23152 * elements and only gets/sets the width of the element. Generally used for table based layouts.
23154 Roo.SplitBar.BasicLayoutAdapter = function(){
23157 Roo.SplitBar.BasicLayoutAdapter.prototype = {
23158 // do nothing for now
23159 init : function(s){
23163 * Called before drag operations to get the current size of the resizing element.
23164 * @param {Roo.SplitBar} s The SplitBar using this adapter
23166 getElementSize : function(s){
23167 if(s.orientation == Roo.SplitBar.HORIZONTAL){
23168 return s.resizingEl.getWidth();
23170 return s.resizingEl.getHeight();
23175 * Called after drag operations to set the size of the resizing element.
23176 * @param {Roo.SplitBar} s The SplitBar using this adapter
23177 * @param {Number} newSize The new size to set
23178 * @param {Function} onComplete A function to be invoked when resizing is complete
23180 setElementSize : function(s, newSize, onComplete){
23181 if(s.orientation == Roo.SplitBar.HORIZONTAL){
23183 s.resizingEl.setWidth(newSize);
23185 onComplete(s, newSize);
23188 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
23193 s.resizingEl.setHeight(newSize);
23195 onComplete(s, newSize);
23198 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
23205 *@class Roo.SplitBar.AbsoluteLayoutAdapter
23206 * @extends Roo.SplitBar.BasicLayoutAdapter
23207 * Adapter that moves the splitter element to align with the resized sizing element.
23208 * Used with an absolute positioned SplitBar.
23209 * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
23210 * document.body, make sure you assign an id to the body element.
23212 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
23213 this.basic = new Roo.SplitBar.BasicLayoutAdapter();
23214 this.container = Roo.get(container);
23217 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
23218 init : function(s){
23219 this.basic.init(s);
23222 getElementSize : function(s){
23223 return this.basic.getElementSize(s);
23226 setElementSize : function(s, newSize, onComplete){
23227 this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
23230 moveSplitter : function(s){
23231 var yes = Roo.SplitBar;
23232 switch(s.placement){
23234 s.el.setX(s.resizingEl.getRight());
23237 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
23240 s.el.setY(s.resizingEl.getBottom());
23243 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
23250 * Orientation constant - Create a vertical SplitBar
23254 Roo.SplitBar.VERTICAL = 1;
23257 * Orientation constant - Create a horizontal SplitBar
23261 Roo.SplitBar.HORIZONTAL = 2;
23264 * Placement constant - The resizing element is to the left of the splitter element
23268 Roo.SplitBar.LEFT = 1;
23271 * Placement constant - The resizing element is to the right of the splitter element
23275 Roo.SplitBar.RIGHT = 2;
23278 * Placement constant - The resizing element is positioned above the splitter element
23282 Roo.SplitBar.TOP = 3;
23285 * Placement constant - The resizing element is positioned under splitter element
23289 Roo.SplitBar.BOTTOM = 4;
23292 * Ext JS Library 1.1.1
23293 * Copyright(c) 2006-2007, Ext JS, LLC.
23295 * Originally Released Under LGPL - original licence link has changed is not relivant.
23298 * <script type="text/javascript">
23303 * @extends Roo.util.Observable
23304 * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template.
23305 * This class also supports single and multi selection modes. <br>
23306 * Create a data model bound view:
23308 var store = new Roo.data.Store(...);
23310 var view = new Roo.View({
23312 tpl : '<div id="{0}">{2} - {1}</div>', // auto create template
23314 singleSelect: true,
23315 selectedClass: "ydataview-selected",
23319 // listen for node click?
23320 view.on("click", function(vw, index, node, e){
23321 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
23325 dataModel.load("foobar.xml");
23327 For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
23329 * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
23330 * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
23332 * Note: old style constructor is still suported (container, template, config)
23335 * Create a new View
23336 * @param {Object} config The config object
23339 Roo.View = function(config, depreciated_tpl, depreciated_config){
23341 if (typeof(depreciated_tpl) == 'undefined') {
23342 // new way.. - universal constructor.
23343 Roo.apply(this, config);
23344 this.el = Roo.get(this.el);
23347 this.el = Roo.get(config);
23348 this.tpl = depreciated_tpl;
23349 Roo.apply(this, depreciated_config);
23353 if(typeof(this.tpl) == "string"){
23354 this.tpl = new Roo.Template(this.tpl);
23356 // support xtype ctors..
23357 this.tpl = new Roo.factory(this.tpl, Roo);
23361 this.tpl.compile();
23368 * @event beforeclick
23369 * Fires before a click is processed. Returns false to cancel the default action.
23370 * @param {Roo.View} this
23371 * @param {Number} index The index of the target node
23372 * @param {HTMLElement} node The target node
23373 * @param {Roo.EventObject} e The raw event object
23375 "beforeclick" : true,
23378 * Fires when a template node is clicked.
23379 * @param {Roo.View} this
23380 * @param {Number} index The index of the target node
23381 * @param {HTMLElement} node The target node
23382 * @param {Roo.EventObject} e The raw event object
23387 * Fires when a template node is double clicked.
23388 * @param {Roo.View} this
23389 * @param {Number} index The index of the target node
23390 * @param {HTMLElement} node The target node
23391 * @param {Roo.EventObject} e The raw event object
23395 * @event contextmenu
23396 * Fires when a template node is right clicked.
23397 * @param {Roo.View} this
23398 * @param {Number} index The index of the target node
23399 * @param {HTMLElement} node The target node
23400 * @param {Roo.EventObject} e The raw event object
23402 "contextmenu" : true,
23404 * @event selectionchange
23405 * Fires when the selected nodes change.
23406 * @param {Roo.View} this
23407 * @param {Array} selections Array of the selected nodes
23409 "selectionchange" : true,
23412 * @event beforeselect
23413 * Fires before a selection is made. If any handlers return false, the selection is cancelled.
23414 * @param {Roo.View} this
23415 * @param {HTMLElement} node The node to be selected
23416 * @param {Array} selections Array of currently selected nodes
23418 "beforeselect" : true
23422 "click": this.onClick,
23423 "dblclick": this.onDblClick,
23424 "contextmenu": this.onContextMenu,
23428 this.selections = [];
23430 this.cmp = new Roo.CompositeElementLite([]);
23432 this.store = Roo.factory(this.store, Roo.data);
23433 this.setStore(this.store, true);
23435 Roo.View.superclass.constructor.call(this);
23438 Roo.extend(Roo.View, Roo.util.Observable, {
23441 * @cfg {Roo.data.Store} store Data store to load data from.
23446 * @cfg {String|Roo.Element} el The container element.
23451 * @cfg {String|Roo.Template} tpl The template used by this View
23456 * @cfg {String} selectedClass The css class to add to selected nodes
23458 selectedClass : "x-view-selected",
23460 * @cfg {String} emptyText The empty text to show when nothing is loaded.
23464 * @cfg {Boolean} multiSelect Allow multiple selection
23467 multiSelect : false,
23469 * @cfg {Boolean} singleSelect Allow single selection
23471 singleSelect: false,
23474 * Returns the element this view is bound to.
23475 * @return {Roo.Element}
23477 getEl : function(){
23482 * Refreshes the view.
23484 refresh : function(){
23486 this.clearSelections();
23487 this.el.update("");
23489 var records = this.store.getRange();
23490 if(records.length < 1){
23491 this.el.update(this.emptyText);
23494 for(var i = 0, len = records.length; i < len; i++){
23495 var data = this.prepareData(records[i].data, i, records[i]);
23496 html[html.length] = t.apply(data);
23498 this.el.update(html.join(""));
23499 this.nodes = this.el.dom.childNodes;
23500 this.updateIndexes(0);
23504 * Function to override to reformat the data that is sent to
23505 * the template for each node.
23506 * @param {Array/Object} data The raw data (array of colData for a data model bound view or
23507 * a JSON object for an UpdateManager bound view).
23509 prepareData : function(data){
23513 onUpdate : function(ds, record){
23514 this.clearSelections();
23515 var index = this.store.indexOf(record);
23516 var n = this.nodes[index];
23517 this.tpl.insertBefore(n, this.prepareData(record.data));
23518 n.parentNode.removeChild(n);
23519 this.updateIndexes(index, index);
23522 onAdd : function(ds, records, index){
23523 this.clearSelections();
23524 if(this.nodes.length == 0){
23528 var n = this.nodes[index];
23529 for(var i = 0, len = records.length; i < len; i++){
23530 var d = this.prepareData(records[i].data);
23532 this.tpl.insertBefore(n, d);
23534 this.tpl.append(this.el, d);
23537 this.updateIndexes(index);
23540 onRemove : function(ds, record, index){
23541 this.clearSelections();
23542 this.el.dom.removeChild(this.nodes[index]);
23543 this.updateIndexes(index);
23547 * Refresh an individual node.
23548 * @param {Number} index
23550 refreshNode : function(index){
23551 this.onUpdate(this.store, this.store.getAt(index));
23554 updateIndexes : function(startIndex, endIndex){
23555 var ns = this.nodes;
23556 startIndex = startIndex || 0;
23557 endIndex = endIndex || ns.length - 1;
23558 for(var i = startIndex; i <= endIndex; i++){
23559 ns[i].nodeIndex = i;
23564 * Changes the data store this view uses and refresh the view.
23565 * @param {Store} store
23567 setStore : function(store, initial){
23568 if(!initial && this.store){
23569 this.store.un("datachanged", this.refresh);
23570 this.store.un("add", this.onAdd);
23571 this.store.un("remove", this.onRemove);
23572 this.store.un("update", this.onUpdate);
23573 this.store.un("clear", this.refresh);
23577 store.on("datachanged", this.refresh, this);
23578 store.on("add", this.onAdd, this);
23579 store.on("remove", this.onRemove, this);
23580 store.on("update", this.onUpdate, this);
23581 store.on("clear", this.refresh, this);
23590 * Returns the template node the passed child belongs to or null if it doesn't belong to one.
23591 * @param {HTMLElement} node
23592 * @return {HTMLElement} The template node
23594 findItemFromChild : function(node){
23595 var el = this.el.dom;
23596 if(!node || node.parentNode == el){
23599 var p = node.parentNode;
23600 while(p && p != el){
23601 if(p.parentNode == el){
23610 onClick : function(e){
23611 var item = this.findItemFromChild(e.getTarget());
23613 var index = this.indexOf(item);
23614 if(this.onItemClick(item, index, e) !== false){
23615 this.fireEvent("click", this, index, item, e);
23618 this.clearSelections();
23623 onContextMenu : function(e){
23624 var item = this.findItemFromChild(e.getTarget());
23626 this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
23631 onDblClick : function(e){
23632 var item = this.findItemFromChild(e.getTarget());
23634 this.fireEvent("dblclick", this, this.indexOf(item), item, e);
23638 onItemClick : function(item, index, e){
23639 if(this.fireEvent("beforeclick", this, index, item, e) === false){
23642 if(this.multiSelect || this.singleSelect){
23643 if(this.multiSelect && e.shiftKey && this.lastSelection){
23644 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
23646 this.select(item, this.multiSelect && e.ctrlKey);
23647 this.lastSelection = item;
23649 e.preventDefault();
23655 * Get the number of selected nodes.
23658 getSelectionCount : function(){
23659 return this.selections.length;
23663 * Get the currently selected nodes.
23664 * @return {Array} An array of HTMLElements
23666 getSelectedNodes : function(){
23667 return this.selections;
23671 * Get the indexes of the selected nodes.
23674 getSelectedIndexes : function(){
23675 var indexes = [], s = this.selections;
23676 for(var i = 0, len = s.length; i < len; i++){
23677 indexes.push(s[i].nodeIndex);
23683 * Clear all selections
23684 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
23686 clearSelections : function(suppressEvent){
23687 if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
23688 this.cmp.elements = this.selections;
23689 this.cmp.removeClass(this.selectedClass);
23690 this.selections = [];
23691 if(!suppressEvent){
23692 this.fireEvent("selectionchange", this, this.selections);
23698 * Returns true if the passed node is selected
23699 * @param {HTMLElement/Number} node The node or node index
23700 * @return {Boolean}
23702 isSelected : function(node){
23703 var s = this.selections;
23707 node = this.getNode(node);
23708 return s.indexOf(node) !== -1;
23713 * @param {Array/HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node, id of a template node or an array of any of those to select
23714 * @param {Boolean} keepExisting (optional) true to keep existing selections
23715 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
23717 select : function(nodeInfo, keepExisting, suppressEvent){
23718 if(nodeInfo instanceof Array){
23720 this.clearSelections(true);
23722 for(var i = 0, len = nodeInfo.length; i < len; i++){
23723 this.select(nodeInfo[i], true, true);
23726 var node = this.getNode(nodeInfo);
23727 if(node && !this.isSelected(node)){
23729 this.clearSelections(true);
23731 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
23732 Roo.fly(node).addClass(this.selectedClass);
23733 this.selections.push(node);
23734 if(!suppressEvent){
23735 this.fireEvent("selectionchange", this, this.selections);
23743 * Gets a template node.
23744 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
23745 * @return {HTMLElement} The node or null if it wasn't found
23747 getNode : function(nodeInfo){
23748 if(typeof nodeInfo == "string"){
23749 return document.getElementById(nodeInfo);
23750 }else if(typeof nodeInfo == "number"){
23751 return this.nodes[nodeInfo];
23757 * Gets a range template nodes.
23758 * @param {Number} startIndex
23759 * @param {Number} endIndex
23760 * @return {Array} An array of nodes
23762 getNodes : function(start, end){
23763 var ns = this.nodes;
23764 start = start || 0;
23765 end = typeof end == "undefined" ? ns.length - 1 : end;
23768 for(var i = start; i <= end; i++){
23772 for(var i = start; i >= end; i--){
23780 * Finds the index of the passed node
23781 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
23782 * @return {Number} The index of the node or -1
23784 indexOf : function(node){
23785 node = this.getNode(node);
23786 if(typeof node.nodeIndex == "number"){
23787 return node.nodeIndex;
23789 var ns = this.nodes;
23790 for(var i = 0, len = ns.length; i < len; i++){
23800 * Ext JS Library 1.1.1
23801 * Copyright(c) 2006-2007, Ext JS, LLC.
23803 * Originally Released Under LGPL - original licence link has changed is not relivant.
23806 * <script type="text/javascript">
23810 * @class Roo.JsonView
23811 * @extends Roo.View
23812 * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
23814 var view = new Roo.JsonView({
23815 container: "my-element",
23816 tpl: '<div id="{id}">{foo} - {bar}</div>', // auto create template
23821 // listen for node click?
23822 view.on("click", function(vw, index, node, e){
23823 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
23826 // direct load of JSON data
23827 view.load("foobar.php");
23829 // Example from my blog list
23830 var tpl = new Roo.Template(
23831 '<div class="entry">' +
23832 '<a class="entry-title" href="{link}">{title}</a>' +
23833 "<h4>{date} by {author} | {comments} Comments</h4>{description}" +
23834 "</div><hr />"
23837 var moreView = new Roo.JsonView({
23838 container : "entry-list",
23842 moreView.on("beforerender", this.sortEntries, this);
23844 url: "/blog/get-posts.php",
23845 params: "allposts=true",
23846 text: "Loading Blog Entries..."
23850 * Note: old code is supported with arguments : (container, template, config)
23854 * Create a new JsonView
23856 * @param {Object} config The config object
23859 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
23862 Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
23864 var um = this.el.getUpdateManager();
23865 um.setRenderer(this);
23866 um.on("update", this.onLoad, this);
23867 um.on("failure", this.onLoadException, this);
23870 * @event beforerender
23871 * Fires before rendering of the downloaded JSON data.
23872 * @param {Roo.JsonView} this
23873 * @param {Object} data The JSON data loaded
23877 * Fires when data is loaded.
23878 * @param {Roo.JsonView} this
23879 * @param {Object} data The JSON data loaded
23880 * @param {Object} response The raw Connect response object
23883 * @event loadexception
23884 * Fires when loading fails.
23885 * @param {Roo.JsonView} this
23886 * @param {Object} response The raw Connect response object
23889 'beforerender' : true,
23891 'loadexception' : true
23894 Roo.extend(Roo.JsonView, Roo.View, {
23896 * @type {String} The root property in the loaded JSON object that contains the data
23901 * Refreshes the view.
23903 refresh : function(){
23904 this.clearSelections();
23905 this.el.update("");
23907 var o = this.jsonData;
23908 if(o && o.length > 0){
23909 for(var i = 0, len = o.length; i < len; i++){
23910 var data = this.prepareData(o[i], i, o);
23911 html[html.length] = this.tpl.apply(data);
23914 html.push(this.emptyText);
23916 this.el.update(html.join(""));
23917 this.nodes = this.el.dom.childNodes;
23918 this.updateIndexes(0);
23922 * Performs an async HTTP request, and loads the JSON from the response. If <i>params</i> are specified it uses POST, otherwise it uses GET.
23923 * @param {Object/String/Function} url The URL for this request, or a function to call to get the URL, or a config object containing any of the following options:
23926 url: "your-url.php",
23927 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
23928 callback: yourFunction,
23929 scope: yourObject, //(optional scope)
23932 text: "Loading...",
23937 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
23938 * are respectively shorthand for <i>disableCaching</i>, <i>indicatorText</i>, and <i>loadScripts</i> and are used to set their associated property on this UpdateManager instance.
23939 * @param {String/Object} params (optional) The parameters to pass, as either a URL encoded string "param1=1&param2=2" or an object {param1: 1, param2: 2}
23940 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
23941 * @param {Boolean} discardUrl (optional) By default when you execute an update the defaultUrl is changed to the last used URL. If true, it will not store the URL.
23944 var um = this.el.getUpdateManager();
23945 um.update.apply(um, arguments);
23948 render : function(el, response){
23949 this.clearSelections();
23950 this.el.update("");
23953 o = Roo.util.JSON.decode(response.responseText);
23956 o = /** eval:var:o */ eval("o." + this.jsonRoot);
23961 * The current JSON data or null
23964 this.beforeRender();
23969 * Get the number of records in the current JSON dataset
23972 getCount : function(){
23973 return this.jsonData ? this.jsonData.length : 0;
23977 * Returns the JSON object for the specified node(s)
23978 * @param {HTMLElement/Array} node The node or an array of nodes
23979 * @return {Object/Array} If you pass in an array, you get an array back, otherwise
23980 * you get the JSON object for the node
23982 getNodeData : function(node){
23983 if(node instanceof Array){
23985 for(var i = 0, len = node.length; i < len; i++){
23986 data.push(this.getNodeData(node[i]));
23990 return this.jsonData[this.indexOf(node)] || null;
23993 beforeRender : function(){
23994 this.snapshot = this.jsonData;
23996 this.sort.apply(this, this.sortInfo);
23998 this.fireEvent("beforerender", this, this.jsonData);
24001 onLoad : function(el, o){
24002 this.fireEvent("load", this, this.jsonData, o);
24005 onLoadException : function(el, o){
24006 this.fireEvent("loadexception", this, o);
24010 * Filter the data by a specific property.
24011 * @param {String} property A property on your JSON objects
24012 * @param {String/RegExp} value Either string that the property values
24013 * should start with, or a RegExp to test against the property
24015 filter : function(property, value){
24018 var ss = this.snapshot;
24019 if(typeof value == "string"){
24020 var vlen = value.length;
24022 this.clearFilter();
24025 value = value.toLowerCase();
24026 for(var i = 0, len = ss.length; i < len; i++){
24028 if(o[property].substr(0, vlen).toLowerCase() == value){
24032 } else if(value.exec){ // regex?
24033 for(var i = 0, len = ss.length; i < len; i++){
24035 if(value.test(o[property])){
24042 this.jsonData = data;
24048 * Filter by a function. The passed function will be called with each
24049 * object in the current dataset. If the function returns true the value is kept,
24050 * otherwise it is filtered.
24051 * @param {Function} fn
24052 * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
24054 filterBy : function(fn, scope){
24057 var ss = this.snapshot;
24058 for(var i = 0, len = ss.length; i < len; i++){
24060 if(fn.call(scope || this, o)){
24064 this.jsonData = data;
24070 * Clears the current filter.
24072 clearFilter : function(){
24073 if(this.snapshot && this.jsonData != this.snapshot){
24074 this.jsonData = this.snapshot;
24081 * Sorts the data for this view and refreshes it.
24082 * @param {String} property A property on your JSON objects to sort on
24083 * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
24084 * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
24086 sort : function(property, dir, sortType){
24087 this.sortInfo = Array.prototype.slice.call(arguments, 0);
24090 var dsc = dir && dir.toLowerCase() == "desc";
24091 var f = function(o1, o2){
24092 var v1 = sortType ? sortType(o1[p]) : o1[p];
24093 var v2 = sortType ? sortType(o2[p]) : o2[p];
24096 return dsc ? +1 : -1;
24097 } else if(v1 > v2){
24098 return dsc ? -1 : +1;
24103 this.jsonData.sort(f);
24105 if(this.jsonData != this.snapshot){
24106 this.snapshot.sort(f);
24112 * Ext JS Library 1.1.1
24113 * Copyright(c) 2006-2007, Ext JS, LLC.
24115 * Originally Released Under LGPL - original licence link has changed is not relivant.
24118 * <script type="text/javascript">
24123 * @class Roo.ColorPalette
24124 * @extends Roo.Component
24125 * Simple color palette class for choosing colors. The palette can be rendered to any container.<br />
24126 * Here's an example of typical usage:
24128 var cp = new Roo.ColorPalette({value:'993300'}); // initial selected color
24129 cp.render('my-div');
24131 cp.on('select', function(palette, selColor){
24132 // do something with selColor
24136 * Create a new ColorPalette
24137 * @param {Object} config The config object
24139 Roo.ColorPalette = function(config){
24140 Roo.ColorPalette.superclass.constructor.call(this, config);
24144 * Fires when a color is selected
24145 * @param {ColorPalette} this
24146 * @param {String} color The 6-digit color hex code (without the # symbol)
24152 this.on("select", this.handler, this.scope, true);
24155 Roo.extend(Roo.ColorPalette, Roo.Component, {
24157 * @cfg {String} itemCls
24158 * The CSS class to apply to the containing element (defaults to "x-color-palette")
24160 itemCls : "x-color-palette",
24162 * @cfg {String} value
24163 * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol). Note that
24164 * the hex codes are case-sensitive.
24167 clickEvent:'click',
24169 ctype: "Roo.ColorPalette",
24172 * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
24174 allowReselect : false,
24177 * <p>An array of 6-digit color hex code strings (without the # symbol). This array can contain any number
24178 * of colors, and each hex code should be unique. The width of the palette is controlled via CSS by adjusting
24179 * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
24180 * of colors with the width setting until the box is symmetrical.</p>
24181 * <p>You can override individual colors if needed:</p>
24183 var cp = new Roo.ColorPalette();
24184 cp.colors[0] = "FF0000"; // change the first box to red
24187 Or you can provide a custom array of your own for complete control:
24189 var cp = new Roo.ColorPalette();
24190 cp.colors = ["000000", "993300", "333300"];
24195 "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
24196 "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
24197 "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
24198 "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
24199 "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
24203 onRender : function(container, position){
24204 var t = new Roo.MasterTemplate(
24205 '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on"> </span></em></a></tpl>'
24207 var c = this.colors;
24208 for(var i = 0, len = c.length; i < len; i++){
24211 var el = document.createElement("div");
24212 el.className = this.itemCls;
24214 container.dom.insertBefore(el, position);
24215 this.el = Roo.get(el);
24216 this.el.on(this.clickEvent, this.handleClick, this, {delegate: "a"});
24217 if(this.clickEvent != 'click'){
24218 this.el.on('click', Roo.emptyFn, this, {delegate: "a", preventDefault:true});
24223 afterRender : function(){
24224 Roo.ColorPalette.superclass.afterRender.call(this);
24226 var s = this.value;
24233 handleClick : function(e, t){
24234 e.preventDefault();
24235 if(!this.disabled){
24236 var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
24237 this.select(c.toUpperCase());
24242 * Selects the specified color in the palette (fires the select event)
24243 * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
24245 select : function(color){
24246 color = color.replace("#", "");
24247 if(color != this.value || this.allowReselect){
24250 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
24252 el.child("a.color-"+color).addClass("x-color-palette-sel");
24253 this.value = color;
24254 this.fireEvent("select", this, color);
24259 * Ext JS Library 1.1.1
24260 * Copyright(c) 2006-2007, Ext JS, LLC.
24262 * Originally Released Under LGPL - original licence link has changed is not relivant.
24265 * <script type="text/javascript">
24269 * @class Roo.DatePicker
24270 * @extends Roo.Component
24271 * Simple date picker class.
24273 * Create a new DatePicker
24274 * @param {Object} config The config object
24276 Roo.DatePicker = function(config){
24277 Roo.DatePicker.superclass.constructor.call(this, config);
24279 this.value = config && config.value ?
24280 config.value.clearTime() : new Date().clearTime();
24285 * Fires when a date is selected
24286 * @param {DatePicker} this
24287 * @param {Date} date The selected date
24293 this.on("select", this.handler, this.scope || this);
24295 // build the disabledDatesRE
24296 if(!this.disabledDatesRE && this.disabledDates){
24297 var dd = this.disabledDates;
24299 for(var i = 0; i < dd.length; i++){
24301 if(i != dd.length-1) re += "|";
24303 this.disabledDatesRE = new RegExp(re + ")");
24307 Roo.extend(Roo.DatePicker, Roo.Component, {
24309 * @cfg {String} todayText
24310 * The text to display on the button that selects the current date (defaults to "Today")
24312 todayText : "Today",
24314 * @cfg {String} okText
24315 * The text to display on the ok button
24317 okText : " OK ", //   to give the user extra clicking room
24319 * @cfg {String} cancelText
24320 * The text to display on the cancel button
24322 cancelText : "Cancel",
24324 * @cfg {String} todayTip
24325 * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
24327 todayTip : "{0} (Spacebar)",
24329 * @cfg {Date} minDate
24330 * Minimum allowable date (JavaScript date object, defaults to null)
24334 * @cfg {Date} maxDate
24335 * Maximum allowable date (JavaScript date object, defaults to null)
24339 * @cfg {String} minText
24340 * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
24342 minText : "This date is before the minimum date",
24344 * @cfg {String} maxText
24345 * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
24347 maxText : "This date is after the maximum date",
24349 * @cfg {String} format
24350 * The default date format string which can be overriden for localization support. The format must be
24351 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
24355 * @cfg {Array} disabledDays
24356 * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
24358 disabledDays : null,
24360 * @cfg {String} disabledDaysText
24361 * The tooltip to display when the date falls on a disabled day (defaults to "")
24363 disabledDaysText : "",
24365 * @cfg {RegExp} disabledDatesRE
24366 * JavaScript regular expression used to disable a pattern of dates (defaults to null)
24368 disabledDatesRE : null,
24370 * @cfg {String} disabledDatesText
24371 * The tooltip text to display when the date falls on a disabled date (defaults to "")
24373 disabledDatesText : "",
24375 * @cfg {Boolean} constrainToViewport
24376 * True to constrain the date picker to the viewport (defaults to true)
24378 constrainToViewport : true,
24380 * @cfg {Array} monthNames
24381 * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
24383 monthNames : Date.monthNames,
24385 * @cfg {Array} dayNames
24386 * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
24388 dayNames : Date.dayNames,
24390 * @cfg {String} nextText
24391 * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
24393 nextText: 'Next Month (Control+Right)',
24395 * @cfg {String} prevText
24396 * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
24398 prevText: 'Previous Month (Control+Left)',
24400 * @cfg {String} monthYearText
24401 * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
24403 monthYearText: 'Choose a month (Control+Up/Down to move years)',
24405 * @cfg {Number} startDay
24406 * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
24410 * @cfg {Bool} showClear
24411 * Show a clear button (usefull for date form elements that can be blank.)
24417 * Sets the value of the date field
24418 * @param {Date} value The date to set
24420 setValue : function(value){
24421 var old = this.value;
24422 this.value = value.clearTime(true);
24424 this.update(this.value);
24429 * Gets the current selected value of the date field
24430 * @return {Date} The selected date
24432 getValue : function(){
24437 focus : function(){
24439 this.update(this.activeDate);
24444 onRender : function(container, position){
24446 '<table cellspacing="0">',
24447 '<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'"> </a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'"> </a></td></tr>',
24448 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
24449 var dn = this.dayNames;
24450 for(var i = 0; i < 7; i++){
24451 var d = this.startDay+i;
24455 m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
24457 m[m.length] = "</tr></thead><tbody><tr>";
24458 for(var i = 0; i < 42; i++) {
24459 if(i % 7 == 0 && i != 0){
24460 m[m.length] = "</tr><tr>";
24462 m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
24464 m[m.length] = '</tr></tbody></table></td></tr><tr>'+
24465 '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
24467 var el = document.createElement("div");
24468 el.className = "x-date-picker";
24469 el.innerHTML = m.join("");
24471 container.dom.insertBefore(el, position);
24473 this.el = Roo.get(el);
24474 this.eventEl = Roo.get(el.firstChild);
24476 new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
24477 handler: this.showPrevMonth,
24479 preventDefault:true,
24483 new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
24484 handler: this.showNextMonth,
24486 preventDefault:true,
24490 this.eventEl.on("mousewheel", this.handleMouseWheel, this);
24492 this.monthPicker = this.el.down('div.x-date-mp');
24493 this.monthPicker.enableDisplayMode('block');
24495 var kn = new Roo.KeyNav(this.eventEl, {
24496 "left" : function(e){
24498 this.showPrevMonth() :
24499 this.update(this.activeDate.add("d", -1));
24502 "right" : function(e){
24504 this.showNextMonth() :
24505 this.update(this.activeDate.add("d", 1));
24508 "up" : function(e){
24510 this.showNextYear() :
24511 this.update(this.activeDate.add("d", -7));
24514 "down" : function(e){
24516 this.showPrevYear() :
24517 this.update(this.activeDate.add("d", 7));
24520 "pageUp" : function(e){
24521 this.showNextMonth();
24524 "pageDown" : function(e){
24525 this.showPrevMonth();
24528 "enter" : function(e){
24529 e.stopPropagation();
24536 this.eventEl.on("click", this.handleDateClick, this, {delegate: "a.x-date-date"});
24538 this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday, this);
24540 this.el.unselectable();
24542 this.cells = this.el.select("table.x-date-inner tbody td");
24543 this.textNodes = this.el.query("table.x-date-inner tbody span");
24545 this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
24547 tooltip: this.monthYearText
24550 this.mbtn.on('click', this.showMonthPicker, this);
24551 this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
24554 var today = (new Date()).dateFormat(this.format);
24556 var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
24558 text: String.format(this.todayText, today),
24559 tooltip: String.format(this.todayTip, today),
24560 handler: this.selectToday,
24564 //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
24567 if (this.showClear) {
24569 baseTb.add( new Roo.Toolbar.Fill());
24572 cls: 'x-btn-icon x-btn-clear',
24573 handler: function() {
24575 this.fireEvent("select", this, '');
24585 this.update(this.value);
24588 createMonthPicker : function(){
24589 if(!this.monthPicker.dom.firstChild){
24590 var buf = ['<table border="0" cellspacing="0">'];
24591 for(var i = 0; i < 6; i++){
24593 '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
24594 '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
24596 '<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' :
24597 '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
24601 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
24603 '</button><button type="button" class="x-date-mp-cancel">',
24605 '</button></td></tr>',
24608 this.monthPicker.update(buf.join(''));
24609 this.monthPicker.on('click', this.onMonthClick, this);
24610 this.monthPicker.on('dblclick', this.onMonthDblClick, this);
24612 this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
24613 this.mpYears = this.monthPicker.select('td.x-date-mp-year');
24615 this.mpMonths.each(function(m, a, i){
24618 m.dom.xmonth = 5 + Math.round(i * .5);
24620 m.dom.xmonth = Math.round((i-1) * .5);
24626 showMonthPicker : function(){
24627 this.createMonthPicker();
24628 var size = this.el.getSize();
24629 this.monthPicker.setSize(size);
24630 this.monthPicker.child('table').setSize(size);
24632 this.mpSelMonth = (this.activeDate || this.value).getMonth();
24633 this.updateMPMonth(this.mpSelMonth);
24634 this.mpSelYear = (this.activeDate || this.value).getFullYear();
24635 this.updateMPYear(this.mpSelYear);
24637 this.monthPicker.slideIn('t', {duration:.2});
24640 updateMPYear : function(y){
24642 var ys = this.mpYears.elements;
24643 for(var i = 1; i <= 10; i++){
24644 var td = ys[i-1], y2;
24646 y2 = y + Math.round(i * .5);
24647 td.firstChild.innerHTML = y2;
24650 y2 = y - (5-Math.round(i * .5));
24651 td.firstChild.innerHTML = y2;
24654 this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
24658 updateMPMonth : function(sm){
24659 this.mpMonths.each(function(m, a, i){
24660 m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
24664 selectMPMonth: function(m){
24668 onMonthClick : function(e, t){
24670 var el = new Roo.Element(t), pn;
24671 if(el.is('button.x-date-mp-cancel')){
24672 this.hideMonthPicker();
24674 else if(el.is('button.x-date-mp-ok')){
24675 this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
24676 this.hideMonthPicker();
24678 else if(pn = el.up('td.x-date-mp-month', 2)){
24679 this.mpMonths.removeClass('x-date-mp-sel');
24680 pn.addClass('x-date-mp-sel');
24681 this.mpSelMonth = pn.dom.xmonth;
24683 else if(pn = el.up('td.x-date-mp-year', 2)){
24684 this.mpYears.removeClass('x-date-mp-sel');
24685 pn.addClass('x-date-mp-sel');
24686 this.mpSelYear = pn.dom.xyear;
24688 else if(el.is('a.x-date-mp-prev')){
24689 this.updateMPYear(this.mpyear-10);
24691 else if(el.is('a.x-date-mp-next')){
24692 this.updateMPYear(this.mpyear+10);
24696 onMonthDblClick : function(e, t){
24698 var el = new Roo.Element(t), pn;
24699 if(pn = el.up('td.x-date-mp-month', 2)){
24700 this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
24701 this.hideMonthPicker();
24703 else if(pn = el.up('td.x-date-mp-year', 2)){
24704 this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
24705 this.hideMonthPicker();
24709 hideMonthPicker : function(disableAnim){
24710 if(this.monthPicker){
24711 if(disableAnim === true){
24712 this.monthPicker.hide();
24714 this.monthPicker.slideOut('t', {duration:.2});
24720 showPrevMonth : function(e){
24721 this.update(this.activeDate.add("mo", -1));
24725 showNextMonth : function(e){
24726 this.update(this.activeDate.add("mo", 1));
24730 showPrevYear : function(){
24731 this.update(this.activeDate.add("y", -1));
24735 showNextYear : function(){
24736 this.update(this.activeDate.add("y", 1));
24740 handleMouseWheel : function(e){
24741 var delta = e.getWheelDelta();
24743 this.showPrevMonth();
24745 } else if(delta < 0){
24746 this.showNextMonth();
24752 handleDateClick : function(e, t){
24754 if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
24755 this.setValue(new Date(t.dateValue));
24756 this.fireEvent("select", this, this.value);
24761 selectToday : function(){
24762 this.setValue(new Date().clearTime());
24763 this.fireEvent("select", this, this.value);
24767 update : function(date){
24768 var vd = this.activeDate;
24769 this.activeDate = date;
24771 var t = date.getTime();
24772 if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
24773 this.cells.removeClass("x-date-selected");
24774 this.cells.each(function(c){
24775 if(c.dom.firstChild.dateValue == t){
24776 c.addClass("x-date-selected");
24777 setTimeout(function(){
24778 try{c.dom.firstChild.focus();}catch(e){}
24786 var days = date.getDaysInMonth();
24787 var firstOfMonth = date.getFirstDateOfMonth();
24788 var startingPos = firstOfMonth.getDay()-this.startDay;
24790 if(startingPos <= this.startDay){
24794 var pm = date.add("mo", -1);
24795 var prevStart = pm.getDaysInMonth()-startingPos;
24797 var cells = this.cells.elements;
24798 var textEls = this.textNodes;
24799 days += startingPos;
24801 // convert everything to numbers so it's fast
24802 var day = 86400000;
24803 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
24804 var today = new Date().clearTime().getTime();
24805 var sel = date.clearTime().getTime();
24806 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
24807 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
24808 var ddMatch = this.disabledDatesRE;
24809 var ddText = this.disabledDatesText;
24810 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
24811 var ddaysText = this.disabledDaysText;
24812 var format = this.format;
24814 var setCellClass = function(cal, cell){
24816 var t = d.getTime();
24817 cell.firstChild.dateValue = t;
24819 cell.className += " x-date-today";
24820 cell.title = cal.todayText;
24823 cell.className += " x-date-selected";
24824 setTimeout(function(){
24825 try{cell.firstChild.focus();}catch(e){}
24830 cell.className = " x-date-disabled";
24831 cell.title = cal.minText;
24835 cell.className = " x-date-disabled";
24836 cell.title = cal.maxText;
24840 if(ddays.indexOf(d.getDay()) != -1){
24841 cell.title = ddaysText;
24842 cell.className = " x-date-disabled";
24845 if(ddMatch && format){
24846 var fvalue = d.dateFormat(format);
24847 if(ddMatch.test(fvalue)){
24848 cell.title = ddText.replace("%0", fvalue);
24849 cell.className = " x-date-disabled";
24855 for(; i < startingPos; i++) {
24856 textEls[i].innerHTML = (++prevStart);
24857 d.setDate(d.getDate()+1);
24858 cells[i].className = "x-date-prevday";
24859 setCellClass(this, cells[i]);
24861 for(; i < days; i++){
24862 intDay = i - startingPos + 1;
24863 textEls[i].innerHTML = (intDay);
24864 d.setDate(d.getDate()+1);
24865 cells[i].className = "x-date-active";
24866 setCellClass(this, cells[i]);
24869 for(; i < 42; i++) {
24870 textEls[i].innerHTML = (++extraDays);
24871 d.setDate(d.getDate()+1);
24872 cells[i].className = "x-date-nextday";
24873 setCellClass(this, cells[i]);
24876 this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
24878 if(!this.internalRender){
24879 var main = this.el.dom.firstChild;
24880 var w = main.offsetWidth;
24881 this.el.setWidth(w + this.el.getBorderWidth("lr"));
24882 Roo.fly(main).setWidth(w);
24883 this.internalRender = true;
24884 // opera does not respect the auto grow header center column
24885 // then, after it gets a width opera refuses to recalculate
24886 // without a second pass
24887 if(Roo.isOpera && !this.secondPass){
24888 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
24889 this.secondPass = true;
24890 this.update.defer(10, this, [date]);
24896 * Ext JS Library 1.1.1
24897 * Copyright(c) 2006-2007, Ext JS, LLC.
24899 * Originally Released Under LGPL - original licence link has changed is not relivant.
24902 * <script type="text/javascript">
24905 * @class Roo.TabPanel
24906 * @extends Roo.util.Observable
24907 * A lightweight tab container.
24911 // basic tabs 1, built from existing content
24912 var tabs = new Roo.TabPanel("tabs1");
24913 tabs.addTab("script", "View Script");
24914 tabs.addTab("markup", "View Markup");
24915 tabs.activate("script");
24917 // more advanced tabs, built from javascript
24918 var jtabs = new Roo.TabPanel("jtabs");
24919 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
24921 // set up the UpdateManager
24922 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
24923 var updater = tab2.getUpdateManager();
24924 updater.setDefaultUrl("ajax1.htm");
24925 tab2.on('activate', updater.refresh, updater, true);
24927 // Use setUrl for Ajax loading
24928 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
24929 tab3.setUrl("ajax2.htm", null, true);
24932 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
24935 jtabs.activate("jtabs-1");
24938 * Create a new TabPanel.
24939 * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
24940 * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
24942 Roo.TabPanel = function(container, config){
24944 * The container element for this TabPanel.
24945 * @type Roo.Element
24947 this.el = Roo.get(container, true);
24949 if(typeof config == "boolean"){
24950 this.tabPosition = config ? "bottom" : "top";
24952 Roo.apply(this, config);
24955 if(this.tabPosition == "bottom"){
24956 this.bodyEl = Roo.get(this.createBody(this.el.dom));
24957 this.el.addClass("x-tabs-bottom");
24959 this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
24960 this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
24961 this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
24963 Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
24965 if(this.tabPosition != "bottom"){
24966 /** The body element that contains {@link Roo.TabPanelItem} bodies.
24967 * @type Roo.Element
24969 this.bodyEl = Roo.get(this.createBody(this.el.dom));
24970 this.el.addClass("x-tabs-top");
24974 this.bodyEl.setStyle("position", "relative");
24976 this.active = null;
24977 this.activateDelegate = this.activate.createDelegate(this);
24982 * Fires when the active tab changes
24983 * @param {Roo.TabPanel} this
24984 * @param {Roo.TabPanelItem} activePanel The new active tab
24988 * @event beforetabchange
24989 * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
24990 * @param {Roo.TabPanel} this
24991 * @param {Object} e Set cancel to true on this object to cancel the tab change
24992 * @param {Roo.TabPanelItem} tab The tab being changed to
24994 "beforetabchange" : true
24997 Roo.EventManager.onWindowResize(this.onResize, this);
24998 this.cpad = this.el.getPadding("lr");
24999 this.hiddenCount = 0;
25001 Roo.TabPanel.superclass.constructor.call(this);
25004 Roo.extend(Roo.TabPanel, Roo.util.Observable, {
25006 *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
25008 tabPosition : "top",
25010 *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
25012 currentTabWidth : 0,
25014 *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
25018 *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
25022 *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
25024 preferredTabWidth : 175,
25026 *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
25028 resizeTabs : false,
25030 *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
25032 monitorResize : true,
25035 * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
25036 * @param {String} id The id of the div to use <b>or create</b>
25037 * @param {String} text The text for the tab
25038 * @param {String} content (optional) Content to put in the TabPanelItem body
25039 * @param {Boolean} closable (optional) True to create a close icon on the tab
25040 * @return {Roo.TabPanelItem} The created TabPanelItem
25042 addTab : function(id, text, content, closable){
25043 var item = new Roo.TabPanelItem(this, id, text, closable);
25044 this.addTabItem(item);
25046 item.setContent(content);
25052 * Returns the {@link Roo.TabPanelItem} with the specified id/index
25053 * @param {String/Number} id The id or index of the TabPanelItem to fetch.
25054 * @return {Roo.TabPanelItem}
25056 getTab : function(id){
25057 return this.items[id];
25061 * Hides the {@link Roo.TabPanelItem} with the specified id/index
25062 * @param {String/Number} id The id or index of the TabPanelItem to hide.
25064 hideTab : function(id){
25065 var t = this.items[id];
25068 this.hiddenCount++;
25069 this.autoSizeTabs();
25074 * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
25075 * @param {String/Number} id The id or index of the TabPanelItem to unhide.
25077 unhideTab : function(id){
25078 var t = this.items[id];
25080 t.setHidden(false);
25081 this.hiddenCount--;
25082 this.autoSizeTabs();
25087 * Adds an existing {@link Roo.TabPanelItem}.
25088 * @param {Roo.TabPanelItem} item The TabPanelItem to add
25090 addTabItem : function(item){
25091 this.items[item.id] = item;
25092 this.items.push(item);
25093 if(this.resizeTabs){
25094 item.setWidth(this.currentTabWidth || this.preferredTabWidth);
25095 this.autoSizeTabs();
25102 * Removes a {@link Roo.TabPanelItem}.
25103 * @param {String/Number} id The id or index of the TabPanelItem to remove.
25105 removeTab : function(id){
25106 var items = this.items;
25107 var tab = items[id];
25109 var index = items.indexOf(tab);
25110 if(this.active == tab && items.length > 1){
25111 var newTab = this.getNextAvailable(index);
25112 if(newTab)newTab.activate();
25114 this.stripEl.dom.removeChild(tab.pnode.dom);
25115 if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
25116 this.bodyEl.dom.removeChild(tab.bodyEl.dom);
25118 items.splice(index, 1);
25119 delete this.items[tab.id];
25120 tab.fireEvent("close", tab);
25121 tab.purgeListeners();
25122 this.autoSizeTabs();
25125 getNextAvailable : function(start){
25126 var items = this.items;
25128 // look for a next tab that will slide over to
25129 // replace the one being removed
25130 while(index < items.length){
25131 var item = items[++index];
25132 if(item && !item.isHidden()){
25136 // if one isn't found select the previous tab (on the left)
25139 var item = items[--index];
25140 if(item && !item.isHidden()){
25148 * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
25149 * @param {String/Number} id The id or index of the TabPanelItem to disable.
25151 disableTab : function(id){
25152 var tab = this.items[id];
25153 if(tab && this.active != tab){
25159 * Enables a {@link Roo.TabPanelItem} that is disabled.
25160 * @param {String/Number} id The id or index of the TabPanelItem to enable.
25162 enableTab : function(id){
25163 var tab = this.items[id];
25168 * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
25169 * @param {String/Number} id The id or index of the TabPanelItem to activate.
25170 * @return {Roo.TabPanelItem} The TabPanelItem.
25172 activate : function(id){
25173 var tab = this.items[id];
25177 if(tab == this.active || tab.disabled){
25181 this.fireEvent("beforetabchange", this, e, tab);
25182 if(e.cancel !== true && !tab.disabled){
25184 this.active.hide();
25186 this.active = this.items[id];
25187 this.active.show();
25188 this.fireEvent("tabchange", this, this.active);
25194 * Gets the active {@link Roo.TabPanelItem}.
25195 * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
25197 getActiveTab : function(){
25198 return this.active;
25202 * Updates the tab body element to fit the height of the container element
25203 * for overflow scrolling
25204 * @param {Number} targetHeight (optional) Override the starting height from the elements height
25206 syncHeight : function(targetHeight){
25207 var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
25208 var bm = this.bodyEl.getMargins();
25209 var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
25210 this.bodyEl.setHeight(newHeight);
25214 onResize : function(){
25215 if(this.monitorResize){
25216 this.autoSizeTabs();
25221 * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
25223 beginUpdate : function(){
25224 this.updating = true;
25228 * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
25230 endUpdate : function(){
25231 this.updating = false;
25232 this.autoSizeTabs();
25236 * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
25238 autoSizeTabs : function(){
25239 var count = this.items.length;
25240 var vcount = count - this.hiddenCount;
25241 if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) return;
25242 var w = Math.max(this.el.getWidth() - this.cpad, 10);
25243 var availWidth = Math.floor(w / vcount);
25244 var b = this.stripBody;
25245 if(b.getWidth() > w){
25246 var tabs = this.items;
25247 this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
25248 if(availWidth < this.minTabWidth){
25249 /*if(!this.sleft){ // incomplete scrolling code
25250 this.createScrollButtons();
25253 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
25256 if(this.currentTabWidth < this.preferredTabWidth){
25257 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
25263 * Returns the number of tabs in this TabPanel.
25266 getCount : function(){
25267 return this.items.length;
25271 * Resizes all the tabs to the passed width
25272 * @param {Number} The new width
25274 setTabWidth : function(width){
25275 this.currentTabWidth = width;
25276 for(var i = 0, len = this.items.length; i < len; i++) {
25277 if(!this.items[i].isHidden())this.items[i].setWidth(width);
25282 * Destroys this TabPanel
25283 * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
25285 destroy : function(removeEl){
25286 Roo.EventManager.removeResizeListener(this.onResize, this);
25287 for(var i = 0, len = this.items.length; i < len; i++){
25288 this.items[i].purgeListeners();
25290 if(removeEl === true){
25291 this.el.update("");
25298 * @class Roo.TabPanelItem
25299 * @extends Roo.util.Observable
25300 * Represents an individual item (tab plus body) in a TabPanel.
25301 * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
25302 * @param {String} id The id of this TabPanelItem
25303 * @param {String} text The text for the tab of this TabPanelItem
25304 * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
25306 Roo.TabPanelItem = function(tabPanel, id, text, closable){
25308 * The {@link Roo.TabPanel} this TabPanelItem belongs to
25309 * @type Roo.TabPanel
25311 this.tabPanel = tabPanel;
25313 * The id for this TabPanelItem
25318 this.disabled = false;
25322 this.loaded = false;
25323 this.closable = closable;
25326 * The body element for this TabPanelItem.
25327 * @type Roo.Element
25329 this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
25330 this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
25331 this.bodyEl.setStyle("display", "block");
25332 this.bodyEl.setStyle("zoom", "1");
25335 var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
25337 this.el = Roo.get(els.el, true);
25338 this.inner = Roo.get(els.inner, true);
25339 this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
25340 this.pnode = Roo.get(els.el.parentNode, true);
25341 this.el.on("mousedown", this.onTabMouseDown, this);
25342 this.el.on("click", this.onTabClick, this);
25345 var c = Roo.get(els.close, true);
25346 c.dom.title = this.closeText;
25347 c.addClassOnOver("close-over");
25348 c.on("click", this.closeClick, this);
25354 * Fires when this tab becomes the active tab.
25355 * @param {Roo.TabPanel} tabPanel The parent TabPanel
25356 * @param {Roo.TabPanelItem} this
25360 * @event beforeclose
25361 * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
25362 * @param {Roo.TabPanelItem} this
25363 * @param {Object} e Set cancel to true on this object to cancel the close.
25365 "beforeclose": true,
25368 * Fires when this tab is closed.
25369 * @param {Roo.TabPanelItem} this
25373 * @event deactivate
25374 * Fires when this tab is no longer the active tab.
25375 * @param {Roo.TabPanel} tabPanel The parent TabPanel
25376 * @param {Roo.TabPanelItem} this
25378 "deactivate" : true
25380 this.hidden = false;
25382 Roo.TabPanelItem.superclass.constructor.call(this);
25385 Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
25386 purgeListeners : function(){
25387 Roo.util.Observable.prototype.purgeListeners.call(this);
25388 this.el.removeAllListeners();
25391 * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
25394 this.pnode.addClass("on");
25397 this.tabPanel.stripWrap.repaint();
25399 this.fireEvent("activate", this.tabPanel, this);
25403 * Returns true if this tab is the active tab.
25404 * @return {Boolean}
25406 isActive : function(){
25407 return this.tabPanel.getActiveTab() == this;
25411 * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
25414 this.pnode.removeClass("on");
25416 this.fireEvent("deactivate", this.tabPanel, this);
25419 hideAction : function(){
25420 this.bodyEl.hide();
25421 this.bodyEl.setStyle("position", "absolute");
25422 this.bodyEl.setLeft("-20000px");
25423 this.bodyEl.setTop("-20000px");
25426 showAction : function(){
25427 this.bodyEl.setStyle("position", "relative");
25428 this.bodyEl.setTop("");
25429 this.bodyEl.setLeft("");
25430 this.bodyEl.show();
25434 * Set the tooltip for the tab.
25435 * @param {String} tooltip The tab's tooltip
25437 setTooltip : function(text){
25438 if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
25439 this.textEl.dom.qtip = text;
25440 this.textEl.dom.removeAttribute('title');
25442 this.textEl.dom.title = text;
25446 onTabClick : function(e){
25447 e.preventDefault();
25448 this.tabPanel.activate(this.id);
25451 onTabMouseDown : function(e){
25452 e.preventDefault();
25453 this.tabPanel.activate(this.id);
25456 getWidth : function(){
25457 return this.inner.getWidth();
25460 setWidth : function(width){
25461 var iwidth = width - this.pnode.getPadding("lr");
25462 this.inner.setWidth(iwidth);
25463 this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
25464 this.pnode.setWidth(width);
25468 * Show or hide the tab
25469 * @param {Boolean} hidden True to hide or false to show.
25471 setHidden : function(hidden){
25472 this.hidden = hidden;
25473 this.pnode.setStyle("display", hidden ? "none" : "");
25477 * Returns true if this tab is "hidden"
25478 * @return {Boolean}
25480 isHidden : function(){
25481 return this.hidden;
25485 * Returns the text for this tab
25488 getText : function(){
25492 autoSize : function(){
25493 //this.el.beginMeasure();
25494 this.textEl.setWidth(1);
25495 this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr"));
25496 //this.el.endMeasure();
25500 * Sets the text for the tab (Note: this also sets the tooltip text)
25501 * @param {String} text The tab's text and tooltip
25503 setText : function(text){
25505 this.textEl.update(text);
25506 this.setTooltip(text);
25507 if(!this.tabPanel.resizeTabs){
25512 * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
25514 activate : function(){
25515 this.tabPanel.activate(this.id);
25519 * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
25521 disable : function(){
25522 if(this.tabPanel.active != this){
25523 this.disabled = true;
25524 this.pnode.addClass("disabled");
25529 * Enables this TabPanelItem if it was previously disabled.
25531 enable : function(){
25532 this.disabled = false;
25533 this.pnode.removeClass("disabled");
25537 * Sets the content for this TabPanelItem.
25538 * @param {String} content The content
25539 * @param {Boolean} loadScripts true to look for and load scripts
25541 setContent : function(content, loadScripts){
25542 this.bodyEl.update(content, loadScripts);
25546 * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
25547 * @return {Roo.UpdateManager} The UpdateManager
25549 getUpdateManager : function(){
25550 return this.bodyEl.getUpdateManager();
25554 * Set a URL to be used to load the content for this TabPanelItem.
25555 * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
25556 * @param {String/Object} params (optional) The string params for the update call or an object of the params. See {@link Roo.UpdateManager#update} for more details. (Defaults to null)
25557 * @param {Boolean} loadOnce (optional) Whether to only load the content once. If this is false it makes the Ajax call every time this TabPanelItem is activated. (Defaults to false)
25558 * @return {Roo.UpdateManager} The UpdateManager
25560 setUrl : function(url, params, loadOnce){
25561 if(this.refreshDelegate){
25562 this.un('activate', this.refreshDelegate);
25564 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
25565 this.on("activate", this.refreshDelegate);
25566 return this.bodyEl.getUpdateManager();
25570 _handleRefresh : function(url, params, loadOnce){
25571 if(!loadOnce || !this.loaded){
25572 var updater = this.bodyEl.getUpdateManager();
25573 updater.update(url, params, this._setLoaded.createDelegate(this));
25578 * Forces a content refresh from the URL specified in the {@link #setUrl} method.
25579 * Will fail silently if the setUrl method has not been called.
25580 * This does not activate the panel, just updates its content.
25582 refresh : function(){
25583 if(this.refreshDelegate){
25584 this.loaded = false;
25585 this.refreshDelegate();
25590 _setLoaded : function(){
25591 this.loaded = true;
25595 closeClick : function(e){
25598 this.fireEvent("beforeclose", this, o);
25599 if(o.cancel !== true){
25600 this.tabPanel.removeTab(this.id);
25604 * The text displayed in the tooltip for the close icon.
25607 closeText : "Close this tab"
25611 Roo.TabPanel.prototype.createStrip = function(container){
25612 var strip = document.createElement("div");
25613 strip.className = "x-tabs-wrap";
25614 container.appendChild(strip);
25618 Roo.TabPanel.prototype.createStripList = function(strip){
25619 // div wrapper for retard IE
25620 strip.innerHTML = '<div class="x-tabs-strip-wrap"><table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr></tr></tbody></table></div>';
25621 return strip.firstChild.firstChild.firstChild.firstChild;
25624 Roo.TabPanel.prototype.createBody = function(container){
25625 var body = document.createElement("div");
25626 Roo.id(body, "tab-body");
25627 Roo.fly(body).addClass("x-tabs-body");
25628 container.appendChild(body);
25632 Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
25633 var body = Roo.getDom(id);
25635 body = document.createElement("div");
25638 Roo.fly(body).addClass("x-tabs-item-body");
25639 bodyEl.insertBefore(body, bodyEl.firstChild);
25643 Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
25644 var td = document.createElement("td");
25645 stripEl.appendChild(td);
25647 td.className = "x-tabs-closable";
25648 if(!this.closeTpl){
25649 this.closeTpl = new Roo.Template(
25650 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
25651 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
25652 '<div unselectable="on" class="close-icon"> </div></em></span></a>'
25655 var el = this.closeTpl.overwrite(td, {"text": text});
25656 var close = el.getElementsByTagName("div")[0];
25657 var inner = el.getElementsByTagName("em")[0];
25658 return {"el": el, "close": close, "inner": inner};
25661 this.tabTpl = new Roo.Template(
25662 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
25663 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
25666 var el = this.tabTpl.overwrite(td, {"text": text});
25667 var inner = el.getElementsByTagName("em")[0];
25668 return {"el": el, "inner": inner};
25672 * Ext JS Library 1.1.1
25673 * Copyright(c) 2006-2007, Ext JS, LLC.
25675 * Originally Released Under LGPL - original licence link has changed is not relivant.
25678 * <script type="text/javascript">
25682 * @class Roo.Button
25683 * @extends Roo.util.Observable
25684 * Simple Button class
25685 * @cfg {String} text The button text
25686 * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
25687 * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
25688 * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
25689 * @cfg {Object} scope The scope of the handler
25690 * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
25691 * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
25692 * @cfg {Boolean} hidden True to start hidden (defaults to false)
25693 * @cfg {Boolean} disabled True to start disabled (defaults to false)
25694 * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
25695 * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
25696 applies if enableToggle = true)
25697 * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
25698 * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
25699 an {@link Roo.util.ClickRepeater} config object (defaults to false).
25701 * Create a new button
25702 * @param {Object} config The config object
25704 Roo.Button = function(renderTo, config)
25708 renderTo = config.renderTo || false;
25711 Roo.apply(this, config);
25715 * Fires when this button is clicked
25716 * @param {Button} this
25717 * @param {EventObject} e The click event
25722 * Fires when the "pressed" state of this button changes (only if enableToggle = true)
25723 * @param {Button} this
25724 * @param {Boolean} pressed
25729 * Fires when the mouse hovers over the button
25730 * @param {Button} this
25731 * @param {Event} e The event object
25733 'mouseover' : true,
25736 * Fires when the mouse exits the button
25737 * @param {Button} this
25738 * @param {Event} e The event object
25743 * Fires when the button is rendered
25744 * @param {Button} this
25749 this.menu = Roo.menu.MenuMgr.get(this.menu);
25752 this.render(renderTo);
25755 Roo.util.Observable.call(this);
25758 Roo.extend(Roo.Button, Roo.util.Observable, {
25764 * Read-only. True if this button is hidden
25769 * Read-only. True if this button is disabled
25774 * Read-only. True if this button is pressed (only if enableToggle = true)
25780 * @cfg {Number} tabIndex
25781 * The DOM tabIndex for this button (defaults to undefined)
25783 tabIndex : undefined,
25786 * @cfg {Boolean} enableToggle
25787 * True to enable pressed/not pressed toggling (defaults to false)
25789 enableToggle: false,
25791 * @cfg {Mixed} menu
25792 * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
25796 * @cfg {String} menuAlign
25797 * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
25799 menuAlign : "tl-bl?",
25802 * @cfg {String} iconCls
25803 * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
25805 iconCls : undefined,
25807 * @cfg {String} type
25808 * The button's type, corresponding to the DOM input element type attribute. Either "submit," "reset" or "button" (default).
25813 menuClassTarget: 'tr',
25816 * @cfg {String} clickEvent
25817 * The type of event to map to the button's event handler (defaults to 'click')
25819 clickEvent : 'click',
25822 * @cfg {Boolean} handleMouseEvents
25823 * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
25825 handleMouseEvents : true,
25828 * @cfg {String} tooltipType
25829 * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
25831 tooltipType : 'qtip',
25834 * @cfg {String} cls
25835 * A CSS class to apply to the button's main element.
25839 * @cfg {Roo.Template} template (Optional)
25840 * An {@link Roo.Template} with which to create the Button's main element. This Template must
25841 * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
25842 * require code modifications if required elements (e.g. a button) aren't present.
25846 render : function(renderTo){
25848 if(this.hideParent){
25849 this.parentEl = Roo.get(renderTo);
25851 if(!this.dhconfig){
25852 if(!this.template){
25853 if(!Roo.Button.buttonTemplate){
25854 // hideous table template
25855 Roo.Button.buttonTemplate = new Roo.Template(
25856 '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
25857 '<td class="x-btn-left"><i> </i></td><td class="x-btn-center"><em unselectable="on"><button class="x-btn-text" type="{1}">{0}</button></em></td><td class="x-btn-right"><i> </i></td>',
25858 "</tr></tbody></table>");
25860 this.template = Roo.Button.buttonTemplate;
25862 btn = this.template.append(renderTo, [this.text || ' ', this.type], true);
25863 var btnEl = btn.child("button:first");
25864 btnEl.on('focus', this.onFocus, this);
25865 btnEl.on('blur', this.onBlur, this);
25867 btn.addClass(this.cls);
25870 btnEl.setStyle('background-image', 'url(' +this.icon +')');
25873 btnEl.addClass(this.iconCls);
25875 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
25878 if(this.tabIndex !== undefined){
25879 btnEl.dom.tabIndex = this.tabIndex;
25882 if(typeof this.tooltip == 'object'){
25883 Roo.QuickTips.tips(Roo.apply({
25887 btnEl.dom[this.tooltipType] = this.tooltip;
25891 btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
25895 this.el.dom.id = this.el.id = this.id;
25898 this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
25899 this.menu.on("show", this.onMenuShow, this);
25900 this.menu.on("hide", this.onMenuHide, this);
25902 btn.addClass("x-btn");
25903 if(Roo.isIE && !Roo.isIE7){
25904 this.autoWidth.defer(1, this);
25908 if(this.handleMouseEvents){
25909 btn.on("mouseover", this.onMouseOver, this);
25910 btn.on("mouseout", this.onMouseOut, this);
25911 btn.on("mousedown", this.onMouseDown, this);
25913 btn.on(this.clickEvent, this.onClick, this);
25914 //btn.on("mouseup", this.onMouseUp, this);
25921 Roo.ButtonToggleMgr.register(this);
25923 this.el.addClass("x-btn-pressed");
25926 var repeater = new Roo.util.ClickRepeater(btn,
25927 typeof this.repeat == "object" ? this.repeat : {}
25929 repeater.on("click", this.onClick, this);
25931 this.fireEvent('render', this);
25935 * Returns the button's underlying element
25936 * @return {Roo.Element} The element
25938 getEl : function(){
25943 * Destroys this Button and removes any listeners.
25945 destroy : function(){
25946 Roo.ButtonToggleMgr.unregister(this);
25947 this.el.removeAllListeners();
25948 this.purgeListeners();
25953 autoWidth : function(){
25955 this.el.setWidth("auto");
25956 if(Roo.isIE7 && Roo.isStrict){
25957 var ib = this.el.child('button');
25958 if(ib && ib.getWidth() > 20){
25960 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
25965 this.el.beginMeasure();
25967 if(this.el.getWidth() < this.minWidth){
25968 this.el.setWidth(this.minWidth);
25971 this.el.endMeasure();
25978 * Assigns this button's click handler
25979 * @param {Function} handler The function to call when the button is clicked
25980 * @param {Object} scope (optional) Scope for the function passed in
25982 setHandler : function(handler, scope){
25983 this.handler = handler;
25984 this.scope = scope;
25988 * Sets this button's text
25989 * @param {String} text The button text
25991 setText : function(text){
25994 this.el.child("td.x-btn-center button.x-btn-text").update(text);
26000 * Gets the text for this button
26001 * @return {String} The button text
26003 getText : function(){
26011 this.hidden = false;
26013 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
26021 this.hidden = true;
26023 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
26028 * Convenience function for boolean show/hide
26029 * @param {Boolean} visible True to show, false to hide
26031 setVisible: function(visible){
26040 * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
26041 * @param {Boolean} state (optional) Force a particular state
26043 toggle : function(state){
26044 state = state === undefined ? !this.pressed : state;
26045 if(state != this.pressed){
26047 this.el.addClass("x-btn-pressed");
26048 this.pressed = true;
26049 this.fireEvent("toggle", this, true);
26051 this.el.removeClass("x-btn-pressed");
26052 this.pressed = false;
26053 this.fireEvent("toggle", this, false);
26055 if(this.toggleHandler){
26056 this.toggleHandler.call(this.scope || this, this, state);
26064 focus : function(){
26065 this.el.child('button:first').focus();
26069 * Disable this button
26071 disable : function(){
26073 this.el.addClass("x-btn-disabled");
26075 this.disabled = true;
26079 * Enable this button
26081 enable : function(){
26083 this.el.removeClass("x-btn-disabled");
26085 this.disabled = false;
26089 * Convenience function for boolean enable/disable
26090 * @param {Boolean} enabled True to enable, false to disable
26092 setDisabled : function(v){
26093 this[v !== true ? "enable" : "disable"]();
26097 onClick : function(e){
26099 e.preventDefault();
26104 if(!this.disabled){
26105 if(this.enableToggle){
26108 if(this.menu && !this.menu.isVisible()){
26109 this.menu.show(this.el, this.menuAlign);
26111 this.fireEvent("click", this, e);
26113 this.el.removeClass("x-btn-over");
26114 this.handler.call(this.scope || this, this, e);
26119 onMouseOver : function(e){
26120 if(!this.disabled){
26121 this.el.addClass("x-btn-over");
26122 this.fireEvent('mouseover', this, e);
26126 onMouseOut : function(e){
26127 if(!e.within(this.el, true)){
26128 this.el.removeClass("x-btn-over");
26129 this.fireEvent('mouseout', this, e);
26133 onFocus : function(e){
26134 if(!this.disabled){
26135 this.el.addClass("x-btn-focus");
26139 onBlur : function(e){
26140 this.el.removeClass("x-btn-focus");
26143 onMouseDown : function(e){
26144 if(!this.disabled && e.button == 0){
26145 this.el.addClass("x-btn-click");
26146 Roo.get(document).on('mouseup', this.onMouseUp, this);
26150 onMouseUp : function(e){
26152 this.el.removeClass("x-btn-click");
26153 Roo.get(document).un('mouseup', this.onMouseUp, this);
26157 onMenuShow : function(e){
26158 this.el.addClass("x-btn-menu-active");
26161 onMenuHide : function(e){
26162 this.el.removeClass("x-btn-menu-active");
26166 // Private utility class used by Button
26167 Roo.ButtonToggleMgr = function(){
26170 function toggleGroup(btn, state){
26172 var g = groups[btn.toggleGroup];
26173 for(var i = 0, l = g.length; i < l; i++){
26175 g[i].toggle(false);
26182 register : function(btn){
26183 if(!btn.toggleGroup){
26186 var g = groups[btn.toggleGroup];
26188 g = groups[btn.toggleGroup] = [];
26191 btn.on("toggle", toggleGroup);
26194 unregister : function(btn){
26195 if(!btn.toggleGroup){
26198 var g = groups[btn.toggleGroup];
26201 btn.un("toggle", toggleGroup);
26207 * Ext JS Library 1.1.1
26208 * Copyright(c) 2006-2007, Ext JS, LLC.
26210 * Originally Released Under LGPL - original licence link has changed is not relivant.
26213 * <script type="text/javascript">
26217 * @class Roo.SplitButton
26218 * @extends Roo.Button
26219 * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
26220 * click event of the button. Typically this would be used to display a dropdown menu that provides additional
26221 * options to the primary button action, but any custom handler can provide the arrowclick implementation.
26222 * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
26223 * @cfg {String} arrowTooltip The title attribute of the arrow
26225 * Create a new menu button
26226 * @param {String/HTMLElement/Element} renderTo The element to append the button to
26227 * @param {Object} config The config object
26229 Roo.SplitButton = function(renderTo, config){
26230 Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
26232 * @event arrowclick
26233 * Fires when this button's arrow is clicked
26234 * @param {SplitButton} this
26235 * @param {EventObject} e The click event
26237 this.addEvents({"arrowclick":true});
26240 Roo.extend(Roo.SplitButton, Roo.Button, {
26241 render : function(renderTo){
26242 // this is one sweet looking template!
26243 var tpl = new Roo.Template(
26244 '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
26245 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
26246 '<tr><td class="x-btn-left"><i> </i></td><td class="x-btn-center"><button class="x-btn-text" type="{1}">{0}</button></td></tr>',
26247 "</tbody></table></td><td>",
26248 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
26249 '<tr><td class="x-btn-center"><button class="x-btn-menu-arrow-el" type="button"> </button></td><td class="x-btn-right"><i> </i></td></tr>',
26250 "</tbody></table></td></tr></table>"
26252 var btn = tpl.append(renderTo, [this.text, this.type], true);
26253 var btnEl = btn.child("button");
26255 btn.addClass(this.cls);
26258 btnEl.setStyle('background-image', 'url(' +this.icon +')');
26261 btnEl.addClass(this.iconCls);
26263 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
26267 if(this.handleMouseEvents){
26268 btn.on("mouseover", this.onMouseOver, this);
26269 btn.on("mouseout", this.onMouseOut, this);
26270 btn.on("mousedown", this.onMouseDown, this);
26271 btn.on("mouseup", this.onMouseUp, this);
26273 btn.on(this.clickEvent, this.onClick, this);
26275 if(typeof this.tooltip == 'object'){
26276 Roo.QuickTips.tips(Roo.apply({
26280 btnEl.dom[this.tooltipType] = this.tooltip;
26283 if(this.arrowTooltip){
26284 btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
26293 this.el.addClass("x-btn-pressed");
26295 if(Roo.isIE && !Roo.isIE7){
26296 this.autoWidth.defer(1, this);
26301 this.menu.on("show", this.onMenuShow, this);
26302 this.menu.on("hide", this.onMenuHide, this);
26304 this.fireEvent('render', this);
26308 autoWidth : function(){
26310 var tbl = this.el.child("table:first");
26311 var tbl2 = this.el.child("table:last");
26312 this.el.setWidth("auto");
26313 tbl.setWidth("auto");
26314 if(Roo.isIE7 && Roo.isStrict){
26315 var ib = this.el.child('button:first');
26316 if(ib && ib.getWidth() > 20){
26318 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
26323 this.el.beginMeasure();
26325 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
26326 tbl.setWidth(this.minWidth-tbl2.getWidth());
26329 this.el.endMeasure();
26332 this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
26336 * Sets this button's click handler
26337 * @param {Function} handler The function to call when the button is clicked
26338 * @param {Object} scope (optional) Scope for the function passed above
26340 setHandler : function(handler, scope){
26341 this.handler = handler;
26342 this.scope = scope;
26346 * Sets this button's arrow click handler
26347 * @param {Function} handler The function to call when the arrow is clicked
26348 * @param {Object} scope (optional) Scope for the function passed above
26350 setArrowHandler : function(handler, scope){
26351 this.arrowHandler = handler;
26352 this.scope = scope;
26358 focus : function(){
26360 this.el.child("button:first").focus();
26365 onClick : function(e){
26366 e.preventDefault();
26367 if(!this.disabled){
26368 if(e.getTarget(".x-btn-menu-arrow-wrap")){
26369 if(this.menu && !this.menu.isVisible()){
26370 this.menu.show(this.el, this.menuAlign);
26372 this.fireEvent("arrowclick", this, e);
26373 if(this.arrowHandler){
26374 this.arrowHandler.call(this.scope || this, this, e);
26377 this.fireEvent("click", this, e);
26379 this.handler.call(this.scope || this, this, e);
26385 onMouseDown : function(e){
26386 if(!this.disabled){
26387 Roo.fly(e.getTarget("table")).addClass("x-btn-click");
26391 onMouseUp : function(e){
26392 Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
26397 // backwards compat
26398 Roo.MenuButton = Roo.SplitButton;/*
26400 * Ext JS Library 1.1.1
26401 * Copyright(c) 2006-2007, Ext JS, LLC.
26403 * Originally Released Under LGPL - original licence link has changed is not relivant.
26406 * <script type="text/javascript">
26410 * @class Roo.Toolbar
26411 * Basic Toolbar class.
26413 * Creates a new Toolbar
26414 * @param {Object} config The config object
26416 Roo.Toolbar = function(container, buttons, config)
26418 /// old consturctor format still supported..
26419 if(container instanceof Array){ // omit the container for later rendering
26420 buttons = container;
26424 if (typeof(container) == 'object' && container.xtype) {
26425 config = container;
26426 container = config.container;
26427 buttons = config.buttons; // not really - use items!!
26430 if (config && config.items) {
26431 xitems = config.items;
26432 delete config.items;
26434 Roo.apply(this, config);
26435 this.buttons = buttons;
26438 this.render(container);
26440 Roo.each(xitems, function(b) {
26446 Roo.Toolbar.prototype = {
26448 * @cfg {Roo.data.Store} items
26449 * array of button configs or elements to add
26453 * @cfg {String/HTMLElement/Element} container
26454 * The id or element that will contain the toolbar
26457 render : function(ct){
26458 this.el = Roo.get(ct);
26460 this.el.addClass(this.cls);
26462 // using a table allows for vertical alignment
26463 // 100% width is needed by Safari...
26464 this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
26465 this.tr = this.el.child("tr", true);
26467 this.items = new Roo.util.MixedCollection(false, function(o){
26468 return o.id || ("item" + (++autoId));
26471 this.add.apply(this, this.buttons);
26472 delete this.buttons;
26477 * Adds element(s) to the toolbar -- this function takes a variable number of
26478 * arguments of mixed type and adds them to the toolbar.
26479 * @param {Mixed} arg1 The following types of arguments are all valid:<br />
26481 * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
26482 * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
26483 * <li>Field: Any form field (equivalent to {@link #addField})</li>
26484 * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
26485 * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
26486 * Note that there are a few special strings that are treated differently as explained nRoo.</li>
26487 * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
26488 * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
26489 * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
26491 * @param {Mixed} arg2
26492 * @param {Mixed} etc.
26495 var a = arguments, l = a.length;
26496 for(var i = 0; i < l; i++){
26501 _add : function(el) {
26504 el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
26507 if (el.applyTo){ // some kind of form field
26508 return this.addField(el);
26510 if (el.render){ // some kind of Toolbar.Item
26511 return this.addItem(el);
26513 if (typeof el == "string"){ // string
26514 if(el == "separator" || el == "-"){
26515 return this.addSeparator();
26518 return this.addSpacer();
26521 return this.addFill();
26523 return this.addText(el);
26526 if(el.tagName){ // element
26527 return this.addElement(el);
26529 if(typeof el == "object"){ // must be button config?
26530 return this.addButton(el);
26532 // and now what?!?!
26538 * Add an Xtype element
26539 * @param {Object} xtype Xtype Object
26540 * @return {Object} created Object
26542 addxtype : function(e){
26543 return this.add(e);
26547 * Returns the Element for this toolbar.
26548 * @return {Roo.Element}
26550 getEl : function(){
26556 * @return {Roo.Toolbar.Item} The separator item
26558 addSeparator : function(){
26559 return this.addItem(new Roo.Toolbar.Separator());
26563 * Adds a spacer element
26564 * @return {Roo.Toolbar.Spacer} The spacer item
26566 addSpacer : function(){
26567 return this.addItem(new Roo.Toolbar.Spacer());
26571 * Adds a fill element that forces subsequent additions to the right side of the toolbar
26572 * @return {Roo.Toolbar.Fill} The fill item
26574 addFill : function(){
26575 return this.addItem(new Roo.Toolbar.Fill());
26579 * Adds any standard HTML element to the toolbar
26580 * @param {String/HTMLElement/Element} el The element or id of the element to add
26581 * @return {Roo.Toolbar.Item} The element's item
26583 addElement : function(el){
26584 return this.addItem(new Roo.Toolbar.Item(el));
26587 * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
26588 * @type Roo.util.MixedCollection
26593 * Adds any Toolbar.Item or subclass
26594 * @param {Roo.Toolbar.Item} item
26595 * @return {Roo.Toolbar.Item} The item
26597 addItem : function(item){
26598 var td = this.nextBlock();
26600 this.items.add(item);
26605 * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
26606 * @param {Object/Array} config A button config or array of configs
26607 * @return {Roo.Toolbar.Button/Array}
26609 addButton : function(config){
26610 if(config instanceof Array){
26612 for(var i = 0, len = config.length; i < len; i++) {
26613 buttons.push(this.addButton(config[i]));
26618 if(!(config instanceof Roo.Toolbar.Button)){
26620 new Roo.Toolbar.SplitButton(config) :
26621 new Roo.Toolbar.Button(config);
26623 var td = this.nextBlock();
26630 * Adds text to the toolbar
26631 * @param {String} text The text to add
26632 * @return {Roo.Toolbar.Item} The element's item
26634 addText : function(text){
26635 return this.addItem(new Roo.Toolbar.TextItem(text));
26639 * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
26640 * @param {Number} index The index where the item is to be inserted
26641 * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
26642 * @return {Roo.Toolbar.Button/Item}
26644 insertButton : function(index, item){
26645 if(item instanceof Array){
26647 for(var i = 0, len = item.length; i < len; i++) {
26648 buttons.push(this.insertButton(index + i, item[i]));
26652 if (!(item instanceof Roo.Toolbar.Button)){
26653 item = new Roo.Toolbar.Button(item);
26655 var td = document.createElement("td");
26656 this.tr.insertBefore(td, this.tr.childNodes[index]);
26658 this.items.insert(index, item);
26663 * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
26664 * @param {Object} config
26665 * @return {Roo.Toolbar.Item} The element's item
26667 addDom : function(config, returnEl){
26668 var td = this.nextBlock();
26669 Roo.DomHelper.overwrite(td, config);
26670 var ti = new Roo.Toolbar.Item(td.firstChild);
26672 this.items.add(ti);
26677 * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
26678 * @type Roo.util.MixedCollection
26683 * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc). Note: the field should not have
26684 * been rendered yet. For a field that has already been rendered, use {@link #addElement}.
26685 * @param {Roo.form.Field} field
26686 * @return {Roo.ToolbarItem}
26690 addField : function(field) {
26691 if (!this.fields) {
26693 this.fields = new Roo.util.MixedCollection(false, function(o){
26694 return o.id || ("item" + (++autoId));
26699 var td = this.nextBlock();
26701 var ti = new Roo.Toolbar.Item(td.firstChild);
26703 this.items.add(ti);
26704 this.fields.add(field);
26715 this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
26716 this.el.child('div').hide();
26724 this.el.child('div').show();
26728 nextBlock : function(){
26729 var td = document.createElement("td");
26730 this.tr.appendChild(td);
26735 destroy : function(){
26736 if(this.items){ // rendered?
26737 Roo.destroy.apply(Roo, this.items.items);
26739 if(this.fields){ // rendered?
26740 Roo.destroy.apply(Roo, this.fields.items);
26742 Roo.Element.uncache(this.el, this.tr);
26747 * @class Roo.Toolbar.Item
26748 * The base class that other classes should extend in order to get some basic common toolbar item functionality.
26750 * Creates a new Item
26751 * @param {HTMLElement} el
26753 Roo.Toolbar.Item = function(el){
26754 this.el = Roo.getDom(el);
26755 this.id = Roo.id(this.el);
26756 this.hidden = false;
26759 Roo.Toolbar.Item.prototype = {
26762 * Get this item's HTML Element
26763 * @return {HTMLElement}
26765 getEl : function(){
26770 render : function(td){
26772 td.appendChild(this.el);
26776 * Removes and destroys this item.
26778 destroy : function(){
26779 this.td.parentNode.removeChild(this.td);
26786 this.hidden = false;
26787 this.td.style.display = "";
26794 this.hidden = true;
26795 this.td.style.display = "none";
26799 * Convenience function for boolean show/hide.
26800 * @param {Boolean} visible true to show/false to hide
26802 setVisible: function(visible){
26811 * Try to focus this item.
26813 focus : function(){
26814 Roo.fly(this.el).focus();
26818 * Disables this item.
26820 disable : function(){
26821 Roo.fly(this.td).addClass("x-item-disabled");
26822 this.disabled = true;
26823 this.el.disabled = true;
26827 * Enables this item.
26829 enable : function(){
26830 Roo.fly(this.td).removeClass("x-item-disabled");
26831 this.disabled = false;
26832 this.el.disabled = false;
26838 * @class Roo.Toolbar.Separator
26839 * @extends Roo.Toolbar.Item
26840 * A simple toolbar separator class
26842 * Creates a new Separator
26844 Roo.Toolbar.Separator = function(){
26845 var s = document.createElement("span");
26846 s.className = "ytb-sep";
26847 Roo.Toolbar.Separator.superclass.constructor.call(this, s);
26849 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
26850 enable:Roo.emptyFn,
26851 disable:Roo.emptyFn,
26856 * @class Roo.Toolbar.Spacer
26857 * @extends Roo.Toolbar.Item
26858 * A simple element that adds extra horizontal space to a toolbar.
26860 * Creates a new Spacer
26862 Roo.Toolbar.Spacer = function(){
26863 var s = document.createElement("div");
26864 s.className = "ytb-spacer";
26865 Roo.Toolbar.Spacer.superclass.constructor.call(this, s);
26867 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
26868 enable:Roo.emptyFn,
26869 disable:Roo.emptyFn,
26874 * @class Roo.Toolbar.Fill
26875 * @extends Roo.Toolbar.Spacer
26876 * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
26878 * Creates a new Spacer
26880 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
26882 render : function(td){
26883 td.style.width = '100%';
26884 Roo.Toolbar.Fill.superclass.render.call(this, td);
26889 * @class Roo.Toolbar.TextItem
26890 * @extends Roo.Toolbar.Item
26891 * A simple class that renders text directly into a toolbar.
26893 * Creates a new TextItem
26894 * @param {String} text
26896 Roo.Toolbar.TextItem = function(text){
26897 if (typeof(text) == 'object') {
26900 var s = document.createElement("span");
26901 s.className = "ytb-text";
26902 s.innerHTML = text;
26903 Roo.Toolbar.TextItem.superclass.constructor.call(this, s);
26905 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
26906 enable:Roo.emptyFn,
26907 disable:Roo.emptyFn,
26912 * @class Roo.Toolbar.Button
26913 * @extends Roo.Button
26914 * A button that renders into a toolbar.
26916 * Creates a new Button
26917 * @param {Object} config A standard {@link Roo.Button} config object
26919 Roo.Toolbar.Button = function(config){
26920 Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
26922 Roo.extend(Roo.Toolbar.Button, Roo.Button, {
26923 render : function(td){
26925 Roo.Toolbar.Button.superclass.render.call(this, td);
26929 * Removes and destroys this button
26931 destroy : function(){
26932 Roo.Toolbar.Button.superclass.destroy.call(this);
26933 this.td.parentNode.removeChild(this.td);
26937 * Shows this button
26940 this.hidden = false;
26941 this.td.style.display = "";
26945 * Hides this button
26948 this.hidden = true;
26949 this.td.style.display = "none";
26953 * Disables this item
26955 disable : function(){
26956 Roo.fly(this.td).addClass("x-item-disabled");
26957 this.disabled = true;
26961 * Enables this item
26963 enable : function(){
26964 Roo.fly(this.td).removeClass("x-item-disabled");
26965 this.disabled = false;
26968 // backwards compat
26969 Roo.ToolbarButton = Roo.Toolbar.Button;
26972 * @class Roo.Toolbar.SplitButton
26973 * @extends Roo.SplitButton
26974 * A menu button that renders into a toolbar.
26976 * Creates a new SplitButton
26977 * @param {Object} config A standard {@link Roo.SplitButton} config object
26979 Roo.Toolbar.SplitButton = function(config){
26980 Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
26982 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
26983 render : function(td){
26985 Roo.Toolbar.SplitButton.superclass.render.call(this, td);
26989 * Removes and destroys this button
26991 destroy : function(){
26992 Roo.Toolbar.SplitButton.superclass.destroy.call(this);
26993 this.td.parentNode.removeChild(this.td);
26997 * Shows this button
27000 this.hidden = false;
27001 this.td.style.display = "";
27005 * Hides this button
27008 this.hidden = true;
27009 this.td.style.display = "none";
27013 // backwards compat
27014 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
27016 * Ext JS Library 1.1.1
27017 * Copyright(c) 2006-2007, Ext JS, LLC.
27019 * Originally Released Under LGPL - original licence link has changed is not relivant.
27022 * <script type="text/javascript">
27026 * @class Roo.PagingToolbar
27027 * @extends Roo.Toolbar
27028 * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
27030 * Create a new PagingToolbar
27031 * @param {Object} config The config object
27033 Roo.PagingToolbar = function(el, ds, config)
27035 // old args format still supported... - xtype is prefered..
27036 if (typeof(el) == 'object' && el.xtype) {
27037 // created from xtype...
27039 ds = el.dataSource;
27040 el = config.container;
27044 Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
27047 this.renderButtons(this.el);
27051 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
27053 * @cfg {Roo.data.Store} dataSource
27054 * The underlying data store providing the paged data
27057 * @cfg {String/HTMLElement/Element} container
27058 * container The id or element that will contain the toolbar
27061 * @cfg {Boolean} displayInfo
27062 * True to display the displayMsg (defaults to false)
27065 * @cfg {Number} pageSize
27066 * The number of records to display per page (defaults to 20)
27070 * @cfg {String} displayMsg
27071 * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
27073 displayMsg : 'Displaying {0} - {1} of {2}',
27075 * @cfg {String} emptyMsg
27076 * The message to display when no records are found (defaults to "No data to display")
27078 emptyMsg : 'No data to display',
27080 * Customizable piece of the default paging text (defaults to "Page")
27083 beforePageText : "Page",
27085 * Customizable piece of the default paging text (defaults to "of %0")
27088 afterPageText : "of {0}",
27090 * Customizable piece of the default paging text (defaults to "First Page")
27093 firstText : "First Page",
27095 * Customizable piece of the default paging text (defaults to "Previous Page")
27098 prevText : "Previous Page",
27100 * Customizable piece of the default paging text (defaults to "Next Page")
27103 nextText : "Next Page",
27105 * Customizable piece of the default paging text (defaults to "Last Page")
27108 lastText : "Last Page",
27110 * Customizable piece of the default paging text (defaults to "Refresh")
27113 refreshText : "Refresh",
27116 renderButtons : function(el){
27117 Roo.PagingToolbar.superclass.render.call(this, el);
27118 this.first = this.addButton({
27119 tooltip: this.firstText,
27120 cls: "x-btn-icon x-grid-page-first",
27122 handler: this.onClick.createDelegate(this, ["first"])
27124 this.prev = this.addButton({
27125 tooltip: this.prevText,
27126 cls: "x-btn-icon x-grid-page-prev",
27128 handler: this.onClick.createDelegate(this, ["prev"])
27130 this.addSeparator();
27131 this.add(this.beforePageText);
27132 this.field = Roo.get(this.addDom({
27137 cls: "x-grid-page-number"
27139 this.field.on("keydown", this.onPagingKeydown, this);
27140 this.field.on("focus", function(){this.dom.select();});
27141 this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
27142 this.field.setHeight(18);
27143 this.addSeparator();
27144 this.next = this.addButton({
27145 tooltip: this.nextText,
27146 cls: "x-btn-icon x-grid-page-next",
27148 handler: this.onClick.createDelegate(this, ["next"])
27150 this.last = this.addButton({
27151 tooltip: this.lastText,
27152 cls: "x-btn-icon x-grid-page-last",
27154 handler: this.onClick.createDelegate(this, ["last"])
27156 this.addSeparator();
27157 this.loading = this.addButton({
27158 tooltip: this.refreshText,
27159 cls: "x-btn-icon x-grid-loading",
27160 handler: this.onClick.createDelegate(this, ["refresh"])
27163 if(this.displayInfo){
27164 this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
27169 updateInfo : function(){
27170 if(this.displayEl){
27171 var count = this.ds.getCount();
27172 var msg = count == 0 ?
27176 this.cursor+1, this.cursor+count, this.ds.getTotalCount()
27178 this.displayEl.update(msg);
27183 onLoad : function(ds, r, o){
27184 this.cursor = o.params ? o.params.start : 0;
27185 var d = this.getPageData(), ap = d.activePage, ps = d.pages;
27187 this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
27188 this.field.dom.value = ap;
27189 this.first.setDisabled(ap == 1);
27190 this.prev.setDisabled(ap == 1);
27191 this.next.setDisabled(ap == ps);
27192 this.last.setDisabled(ap == ps);
27193 this.loading.enable();
27198 getPageData : function(){
27199 var total = this.ds.getTotalCount();
27202 activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
27203 pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
27208 onLoadError : function(){
27209 this.loading.enable();
27213 onPagingKeydown : function(e){
27214 var k = e.getKey();
27215 var d = this.getPageData();
27217 var v = this.field.dom.value, pageNum;
27218 if(!v || isNaN(pageNum = parseInt(v, 10))){
27219 this.field.dom.value = d.activePage;
27222 pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
27223 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
27226 else if(k == e.HOME || (k == e.UP && e.ctrlKey) || (k == e.PAGEUP && e.ctrlKey) || (k == e.RIGHT && e.ctrlKey) || k == e.END || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey))
27228 var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
27229 this.field.dom.value = pageNum;
27230 this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
27233 else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
27235 var v = this.field.dom.value, pageNum;
27236 var increment = (e.shiftKey) ? 10 : 1;
27237 if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
27239 if(!v || isNaN(pageNum = parseInt(v, 10))) {
27240 this.field.dom.value = d.activePage;
27243 else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
27245 this.field.dom.value = parseInt(v, 10) + increment;
27246 pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
27247 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
27254 beforeLoad : function(){
27256 this.loading.disable();
27261 onClick : function(which){
27265 ds.load({params:{start: 0, limit: this.pageSize}});
27268 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
27271 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
27274 var total = ds.getTotalCount();
27275 var extra = total % this.pageSize;
27276 var lastStart = extra ? (total - extra) : total-this.pageSize;
27277 ds.load({params:{start: lastStart, limit: this.pageSize}});
27280 ds.load({params:{start: this.cursor, limit: this.pageSize}});
27286 * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
27287 * @param {Roo.data.Store} store The data store to unbind
27289 unbind : function(ds){
27290 ds.un("beforeload", this.beforeLoad, this);
27291 ds.un("load", this.onLoad, this);
27292 ds.un("loadexception", this.onLoadError, this);
27293 ds.un("remove", this.updateInfo, this);
27294 ds.un("add", this.updateInfo, this);
27295 this.ds = undefined;
27299 * Binds the paging toolbar to the specified {@link Roo.data.Store}
27300 * @param {Roo.data.Store} store The data store to bind
27302 bind : function(ds){
27303 ds.on("beforeload", this.beforeLoad, this);
27304 ds.on("load", this.onLoad, this);
27305 ds.on("loadexception", this.onLoadError, this);
27306 ds.on("remove", this.updateInfo, this);
27307 ds.on("add", this.updateInfo, this);
27312 * Ext JS Library 1.1.1
27313 * Copyright(c) 2006-2007, Ext JS, LLC.
27315 * Originally Released Under LGPL - original licence link has changed is not relivant.
27318 * <script type="text/javascript">
27322 * @class Roo.Resizable
27323 * @extends Roo.util.Observable
27324 * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
27325 * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
27326 * the textarea in a div and set "resizeChild" to true (or to the id of the element), <b>or</b> set wrap:true in your config and
27327 * the element will be wrapped for you automatically.</p>
27328 * <p>Here is the list of valid resize handles:</p>
27331 ------ -------------------
27342 * <p>Here's an example showing the creation of a typical Resizable:</p>
27344 var resizer = new Roo.Resizable("element-id", {
27352 resizer.on("resize", myHandler);
27354 * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
27355 * resizer.east.setDisplayed(false);</p>
27356 * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
27357 * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
27358 * resize operation's new size (defaults to [0, 0])
27359 * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
27360 * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
27361 * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
27362 * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
27363 * @cfg {Boolean} enabled False to disable resizing (defaults to true)
27364 * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
27365 * @cfg {Number} width The width of the element in pixels (defaults to null)
27366 * @cfg {Number} height The height of the element in pixels (defaults to null)
27367 * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
27368 * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
27369 * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
27370 * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
27371 * @cfg {Boolean} multiDirectional <b>Deprecated</b>. The old style of adding multi-direction resize handles, deprecated
27372 * in favor of the handles config option (defaults to false)
27373 * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
27374 * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
27375 * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
27376 * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
27377 * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
27378 * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
27379 * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
27380 * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
27381 * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
27382 * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
27383 * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
27385 * Create a new resizable component
27386 * @param {String/HTMLElement/Roo.Element} el The id or element to resize
27387 * @param {Object} config configuration options
27389 Roo.Resizable = function(el, config){
27390 this.el = Roo.get(el);
27392 if(config && config.wrap){
27393 config.resizeChild = this.el;
27394 this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
27395 this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
27396 this.el.setStyle("overflow", "hidden");
27397 this.el.setPositioning(config.resizeChild.getPositioning());
27398 config.resizeChild.clearPositioning();
27399 if(!config.width || !config.height){
27400 var csize = config.resizeChild.getSize();
27401 this.el.setSize(csize.width, csize.height);
27403 if(config.pinned && !config.adjustments){
27404 config.adjustments = "auto";
27408 this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
27409 this.proxy.unselectable();
27410 this.proxy.enableDisplayMode('block');
27412 Roo.apply(this, config);
27415 this.disableTrackOver = true;
27416 this.el.addClass("x-resizable-pinned");
27418 // if the element isn't positioned, make it relative
27419 var position = this.el.getStyle("position");
27420 if(position != "absolute" && position != "fixed"){
27421 this.el.setStyle("position", "relative");
27423 if(!this.handles){ // no handles passed, must be legacy style
27424 this.handles = 's,e,se';
27425 if(this.multiDirectional){
27426 this.handles += ',n,w';
27429 if(this.handles == "all"){
27430 this.handles = "n s e w ne nw se sw";
27432 var hs = this.handles.split(/\s*?[,;]\s*?| /);
27433 var ps = Roo.Resizable.positions;
27434 for(var i = 0, len = hs.length; i < len; i++){
27435 if(hs[i] && ps[hs[i]]){
27436 var pos = ps[hs[i]];
27437 this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
27441 this.corner = this.southeast;
27443 if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1){
27444 this.updateBox = true;
27447 this.activeHandle = null;
27449 if(this.resizeChild){
27450 if(typeof this.resizeChild == "boolean"){
27451 this.resizeChild = Roo.get(this.el.dom.firstChild, true);
27453 this.resizeChild = Roo.get(this.resizeChild, true);
27457 if(this.adjustments == "auto"){
27458 var rc = this.resizeChild;
27459 var hw = this.west, he = this.east, hn = this.north, hs = this.south;
27460 if(rc && (hw || hn)){
27461 rc.position("relative");
27462 rc.setLeft(hw ? hw.el.getWidth() : 0);
27463 rc.setTop(hn ? hn.el.getHeight() : 0);
27465 this.adjustments = [
27466 (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
27467 (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
27471 if(this.draggable){
27472 this.dd = this.dynamic ?
27473 this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
27474 this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
27480 * @event beforeresize
27481 * Fired before resize is allowed. Set enabled to false to cancel resize.
27482 * @param {Roo.Resizable} this
27483 * @param {Roo.EventObject} e The mousedown event
27485 "beforeresize" : true,
27488 * Fired after a resize.
27489 * @param {Roo.Resizable} this
27490 * @param {Number} width The new width
27491 * @param {Number} height The new height
27492 * @param {Roo.EventObject} e The mouseup event
27497 if(this.width !== null && this.height !== null){
27498 this.resizeTo(this.width, this.height);
27500 this.updateChildSize();
27503 this.el.dom.style.zoom = 1;
27505 Roo.Resizable.superclass.constructor.call(this);
27508 Roo.extend(Roo.Resizable, Roo.util.Observable, {
27509 resizeChild : false,
27510 adjustments : [0, 0],
27520 multiDirectional : false,
27521 disableTrackOver : false,
27522 easing : 'easeOutStrong',
27523 widthIncrement : 0,
27524 heightIncrement : 0,
27528 preserveRatio : false,
27529 transparent: false,
27535 * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
27537 constrainTo: undefined,
27539 * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
27541 resizeRegion: undefined,
27545 * Perform a manual resize
27546 * @param {Number} width
27547 * @param {Number} height
27549 resizeTo : function(width, height){
27550 this.el.setSize(width, height);
27551 this.updateChildSize();
27552 this.fireEvent("resize", this, width, height, null);
27556 startSizing : function(e, handle){
27557 this.fireEvent("beforeresize", this, e);
27558 if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
27561 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: " "});
27562 this.overlay.unselectable();
27563 this.overlay.enableDisplayMode("block");
27564 this.overlay.on("mousemove", this.onMouseMove, this);
27565 this.overlay.on("mouseup", this.onMouseUp, this);
27567 this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
27569 this.resizing = true;
27570 this.startBox = this.el.getBox();
27571 this.startPoint = e.getXY();
27572 this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
27573 (this.startBox.y + this.startBox.height) - this.startPoint[1]];
27575 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
27576 this.overlay.show();
27578 if(this.constrainTo) {
27579 var ct = Roo.get(this.constrainTo);
27580 this.resizeRegion = ct.getRegion().adjust(
27581 ct.getFrameWidth('t'),
27582 ct.getFrameWidth('l'),
27583 -ct.getFrameWidth('b'),
27584 -ct.getFrameWidth('r')
27588 this.proxy.setStyle('visibility', 'hidden'); // workaround display none
27590 this.proxy.setBox(this.startBox);
27592 this.proxy.setStyle('visibility', 'visible');
27598 onMouseDown : function(handle, e){
27601 this.activeHandle = handle;
27602 this.startSizing(e, handle);
27607 onMouseUp : function(e){
27608 var size = this.resizeElement();
27609 this.resizing = false;
27611 this.overlay.hide();
27613 this.fireEvent("resize", this, size.width, size.height, e);
27617 updateChildSize : function(){
27618 if(this.resizeChild){
27620 var child = this.resizeChild;
27621 var adj = this.adjustments;
27622 if(el.dom.offsetWidth){
27623 var b = el.getSize(true);
27624 child.setSize(b.width+adj[0], b.height+adj[1]);
27626 // Second call here for IE
27627 // The first call enables instant resizing and
27628 // the second call corrects scroll bars if they
27631 setTimeout(function(){
27632 if(el.dom.offsetWidth){
27633 var b = el.getSize(true);
27634 child.setSize(b.width+adj[0], b.height+adj[1]);
27642 snap : function(value, inc, min){
27643 if(!inc || !value) return value;
27644 var newValue = value;
27645 var m = value % inc;
27648 newValue = value + (inc-m);
27650 newValue = value - m;
27653 return Math.max(min, newValue);
27657 resizeElement : function(){
27658 var box = this.proxy.getBox();
27659 if(this.updateBox){
27660 this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
27662 this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
27664 this.updateChildSize();
27672 constrain : function(v, diff, m, mx){
27675 }else if(v - diff > mx){
27682 onMouseMove : function(e){
27684 try{// try catch so if something goes wrong the user doesn't get hung
27686 if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
27690 //var curXY = this.startPoint;
27691 var curSize = this.curSize || this.startBox;
27692 var x = this.startBox.x, y = this.startBox.y;
27693 var ox = x, oy = y;
27694 var w = curSize.width, h = curSize.height;
27695 var ow = w, oh = h;
27696 var mw = this.minWidth, mh = this.minHeight;
27697 var mxw = this.maxWidth, mxh = this.maxHeight;
27698 var wi = this.widthIncrement;
27699 var hi = this.heightIncrement;
27701 var eventXY = e.getXY();
27702 var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
27703 var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
27705 var pos = this.activeHandle.position;
27710 w = Math.min(Math.max(mw, w), mxw);
27714 h = Math.min(Math.max(mh, h), mxh);
27719 w = Math.min(Math.max(mw, w), mxw);
27720 h = Math.min(Math.max(mh, h), mxh);
27723 diffY = this.constrain(h, diffY, mh, mxh);
27728 diffX = this.constrain(w, diffX, mw, mxw);
27734 w = Math.min(Math.max(mw, w), mxw);
27735 diffY = this.constrain(h, diffY, mh, mxh);
27740 diffX = this.constrain(w, diffX, mw, mxw);
27741 diffY = this.constrain(h, diffY, mh, mxh);
27748 diffX = this.constrain(w, diffX, mw, mxw);
27750 h = Math.min(Math.max(mh, h), mxh);
27756 var sw = this.snap(w, wi, mw);
27757 var sh = this.snap(h, hi, mh);
27758 if(sw != w || sh != h){
27781 if(this.preserveRatio){
27786 h = Math.min(Math.max(mh, h), mxh);
27791 w = Math.min(Math.max(mw, w), mxw);
27796 w = Math.min(Math.max(mw, w), mxw);
27802 w = Math.min(Math.max(mw, w), mxw);
27808 h = Math.min(Math.max(mh, h), mxh);
27816 h = Math.min(Math.max(mh, h), mxh);
27826 h = Math.min(Math.max(mh, h), mxh);
27834 this.proxy.setBounds(x, y, w, h);
27836 this.resizeElement();
27843 handleOver : function(){
27845 this.el.addClass("x-resizable-over");
27850 handleOut : function(){
27851 if(!this.resizing){
27852 this.el.removeClass("x-resizable-over");
27857 * Returns the element this component is bound to.
27858 * @return {Roo.Element}
27860 getEl : function(){
27865 * Returns the resizeChild element (or null).
27866 * @return {Roo.Element}
27868 getResizeChild : function(){
27869 return this.resizeChild;
27873 * Destroys this resizable. If the element was wrapped and
27874 * removeEl is not true then the element remains.
27875 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
27877 destroy : function(removeEl){
27878 this.proxy.remove();
27880 this.overlay.removeAllListeners();
27881 this.overlay.remove();
27883 var ps = Roo.Resizable.positions;
27885 if(typeof ps[k] != "function" && this[ps[k]]){
27886 var h = this[ps[k]];
27887 h.el.removeAllListeners();
27892 this.el.update("");
27899 // hash to map config positions to true positions
27900 Roo.Resizable.positions = {
27901 n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast"
27905 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
27907 // only initialize the template if resizable is used
27908 var tpl = Roo.DomHelper.createTemplate(
27909 {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
27912 Roo.Resizable.Handle.prototype.tpl = tpl;
27914 this.position = pos;
27916 this.el = this.tpl.append(rz.el.dom, [this.position], true);
27917 this.el.unselectable();
27919 this.el.setOpacity(0);
27921 this.el.on("mousedown", this.onMouseDown, this);
27922 if(!disableTrackOver){
27923 this.el.on("mouseover", this.onMouseOver, this);
27924 this.el.on("mouseout", this.onMouseOut, this);
27929 Roo.Resizable.Handle.prototype = {
27930 afterResize : function(rz){
27934 onMouseDown : function(e){
27935 this.rz.onMouseDown(this, e);
27938 onMouseOver : function(e){
27939 this.rz.handleOver(this, e);
27942 onMouseOut : function(e){
27943 this.rz.handleOut(this, e);
27947 * Ext JS Library 1.1.1
27948 * Copyright(c) 2006-2007, Ext JS, LLC.
27950 * Originally Released Under LGPL - original licence link has changed is not relivant.
27953 * <script type="text/javascript">
27957 * @class Roo.Editor
27958 * @extends Roo.Component
27959 * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
27961 * Create a new Editor
27962 * @param {Roo.form.Field} field The Field object (or descendant)
27963 * @param {Object} config The config object
27965 Roo.Editor = function(field, config){
27966 Roo.Editor.superclass.constructor.call(this, config);
27967 this.field = field;
27970 * @event beforestartedit
27971 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
27972 * false from the handler of this event.
27973 * @param {Editor} this
27974 * @param {Roo.Element} boundEl The underlying element bound to this editor
27975 * @param {Mixed} value The field value being set
27977 "beforestartedit" : true,
27980 * Fires when this editor is displayed
27981 * @param {Roo.Element} boundEl The underlying element bound to this editor
27982 * @param {Mixed} value The starting field value
27984 "startedit" : true,
27986 * @event beforecomplete
27987 * Fires after a change has been made to the field, but before the change is reflected in the underlying
27988 * field. Saving the change to the field can be canceled by returning false from the handler of this event.
27989 * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
27990 * event will not fire since no edit actually occurred.
27991 * @param {Editor} this
27992 * @param {Mixed} value The current field value
27993 * @param {Mixed} startValue The original field value
27995 "beforecomplete" : true,
27998 * Fires after editing is complete and any changed value has been written to the underlying field.
27999 * @param {Editor} this
28000 * @param {Mixed} value The current field value
28001 * @param {Mixed} startValue The original field value
28005 * @event specialkey
28006 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
28007 * {@link Roo.EventObject#getKey} to determine which key was pressed.
28008 * @param {Roo.form.Field} this
28009 * @param {Roo.EventObject} e The event object
28011 "specialkey" : true
28015 Roo.extend(Roo.Editor, Roo.Component, {
28017 * @cfg {Boolean/String} autosize
28018 * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
28019 * or "height" to adopt the height only (defaults to false)
28022 * @cfg {Boolean} revertInvalid
28023 * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
28024 * validation fails (defaults to true)
28027 * @cfg {Boolean} ignoreNoChange
28028 * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
28029 * the value has not changed (defaults to false). Applies only to string values - edits for other data types
28030 * will never be ignored.
28033 * @cfg {Boolean} hideEl
28034 * False to keep the bound element visible while the editor is displayed (defaults to true)
28037 * @cfg {Mixed} value
28038 * The data value of the underlying field (defaults to "")
28042 * @cfg {String} alignment
28043 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
28047 * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
28048 * for bottom-right shadow (defaults to "frame")
28052 * @cfg {Boolean} constrain True to constrain the editor to the viewport
28056 * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
28058 completeOnEnter : false,
28060 * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
28062 cancelOnEsc : false,
28064 * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
28069 onRender : function(ct, position){
28070 this.el = new Roo.Layer({
28071 shadow: this.shadow,
28077 constrain: this.constrain
28079 this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
28080 if(this.field.msgTarget != 'title'){
28081 this.field.msgTarget = 'qtip';
28083 this.field.render(this.el);
28085 this.field.el.dom.setAttribute('autocomplete', 'off');
28087 this.field.on("specialkey", this.onSpecialKey, this);
28088 if(this.swallowKeys){
28089 this.field.el.swallowEvent(['keydown','keypress']);
28092 this.field.on("blur", this.onBlur, this);
28093 if(this.field.grow){
28094 this.field.on("autosize", this.el.sync, this.el, {delay:1});
28098 onSpecialKey : function(field, e){
28099 if(this.completeOnEnter && e.getKey() == e.ENTER){
28101 this.completeEdit();
28102 }else if(this.cancelOnEsc && e.getKey() == e.ESC){
28105 this.fireEvent('specialkey', field, e);
28110 * Starts the editing process and shows the editor.
28111 * @param {String/HTMLElement/Element} el The element to edit
28112 * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
28113 * to the innerHTML of el.
28115 startEdit : function(el, value){
28117 this.completeEdit();
28119 this.boundEl = Roo.get(el);
28120 var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
28121 if(!this.rendered){
28122 this.render(this.parentEl || document.body);
28124 if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
28127 this.startValue = v;
28128 this.field.setValue(v);
28130 var sz = this.boundEl.getSize();
28131 switch(this.autoSize){
28133 this.setSize(sz.width, "");
28136 this.setSize("", sz.height);
28139 this.setSize(sz.width, sz.height);
28142 this.el.alignTo(this.boundEl, this.alignment);
28143 this.editing = true;
28145 Roo.QuickTips.disable();
28151 * Sets the height and width of this editor.
28152 * @param {Number} width The new width
28153 * @param {Number} height The new height
28155 setSize : function(w, h){
28156 this.field.setSize(w, h);
28163 * Realigns the editor to the bound field based on the current alignment config value.
28165 realign : function(){
28166 this.el.alignTo(this.boundEl, this.alignment);
28170 * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
28171 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
28173 completeEdit : function(remainVisible){
28177 var v = this.getValue();
28178 if(this.revertInvalid !== false && !this.field.isValid()){
28179 v = this.startValue;
28180 this.cancelEdit(true);
28182 if(String(v) === String(this.startValue) && this.ignoreNoChange){
28183 this.editing = false;
28187 if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
28188 this.editing = false;
28189 if(this.updateEl && this.boundEl){
28190 this.boundEl.update(v);
28192 if(remainVisible !== true){
28195 this.fireEvent("complete", this, v, this.startValue);
28200 onShow : function(){
28202 if(this.hideEl !== false){
28203 this.boundEl.hide();
28206 if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
28207 this.fixIEFocus = true;
28208 this.deferredFocus.defer(50, this);
28210 this.field.focus();
28212 this.fireEvent("startedit", this.boundEl, this.startValue);
28215 deferredFocus : function(){
28217 this.field.focus();
28222 * Cancels the editing process and hides the editor without persisting any changes. The field value will be
28223 * reverted to the original starting value.
28224 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
28225 * cancel (defaults to false)
28227 cancelEdit : function(remainVisible){
28229 this.setValue(this.startValue);
28230 if(remainVisible !== true){
28237 onBlur : function(){
28238 if(this.allowBlur !== true && this.editing){
28239 this.completeEdit();
28244 onHide : function(){
28246 this.completeEdit();
28250 if(this.field.collapse){
28251 this.field.collapse();
28254 if(this.hideEl !== false){
28255 this.boundEl.show();
28258 Roo.QuickTips.enable();
28263 * Sets the data value of the editor
28264 * @param {Mixed} value Any valid value supported by the underlying field
28266 setValue : function(v){
28267 this.field.setValue(v);
28271 * Gets the data value of the editor
28272 * @return {Mixed} The data value
28274 getValue : function(){
28275 return this.field.getValue();
28279 * Ext JS Library 1.1.1
28280 * Copyright(c) 2006-2007, Ext JS, LLC.
28282 * Originally Released Under LGPL - original licence link has changed is not relivant.
28285 * <script type="text/javascript">
28289 * @class Roo.BasicDialog
28290 * @extends Roo.util.Observable
28291 * Lightweight Dialog Class. The code below shows the creation of a typical dialog using existing HTML markup:
28293 var dlg = new Roo.BasicDialog("my-dlg", {
28302 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
28303 dlg.addButton('OK', dlg.hide, dlg); // Could call a save function instead of hiding
28304 dlg.addButton('Cancel', dlg.hide, dlg);
28307 <b>A Dialog should always be a direct child of the body element.</b>
28308 * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
28309 * @cfg {String} title Default text to display in the title bar (defaults to null)
28310 * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
28311 * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
28312 * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
28313 * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
28314 * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
28315 * (defaults to null with no animation)
28316 * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
28317 * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
28318 * property for valid values (defaults to 'all')
28319 * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
28320 * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
28321 * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
28322 * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
28323 * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
28324 * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
28325 * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
28326 * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
28327 * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
28328 * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
28329 * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
28330 * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
28331 * draggable = true (defaults to false)
28332 * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
28333 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
28334 * shadow (defaults to false)
28335 * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
28336 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
28337 * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
28338 * @cfg {Array} buttons Array of buttons
28339 * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
28341 * Create a new BasicDialog.
28342 * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
28343 * @param {Object} config Configuration options
28345 Roo.BasicDialog = function(el, config){
28346 this.el = Roo.get(el);
28347 var dh = Roo.DomHelper;
28348 if(!this.el && config && config.autoCreate){
28349 if(typeof config.autoCreate == "object"){
28350 if(!config.autoCreate.id){
28351 config.autoCreate.id = el;
28353 this.el = dh.append(document.body,
28354 config.autoCreate, true);
28356 this.el = dh.append(document.body,
28357 {tag: "div", id: el, style:'visibility:hidden;'}, true);
28361 el.setDisplayed(true);
28362 el.hide = this.hideAction;
28364 el.addClass("x-dlg");
28366 Roo.apply(this, config);
28368 this.proxy = el.createProxy("x-dlg-proxy");
28369 this.proxy.hide = this.hideAction;
28370 this.proxy.setOpacity(.5);
28374 el.setWidth(config.width);
28377 el.setHeight(config.height);
28379 this.size = el.getSize();
28380 if(typeof config.x != "undefined" && typeof config.y != "undefined"){
28381 this.xy = [config.x,config.y];
28383 this.xy = el.getCenterXY(true);
28385 /** The header element @type Roo.Element */
28386 this.header = el.child("> .x-dlg-hd");
28387 /** The body element @type Roo.Element */
28388 this.body = el.child("> .x-dlg-bd");
28389 /** The footer element @type Roo.Element */
28390 this.footer = el.child("> .x-dlg-ft");
28393 this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: " "}, this.body ? this.body.dom : null);
28396 this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
28399 this.header.unselectable();
28401 this.header.update(this.title);
28403 // this element allows the dialog to be focused for keyboard event
28404 this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
28405 this.focusEl.swallowEvent("click", true);
28407 this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
28409 // wrap the body and footer for special rendering
28410 this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
28412 this.bwrap.dom.appendChild(this.footer.dom);
28415 this.bg = this.el.createChild({
28416 tag: "div", cls:"x-dlg-bg",
28417 html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center"> </div></div></div>'
28419 this.centerBg = this.bg.child("div.x-dlg-bg-center");
28422 if(this.autoScroll !== false && !this.autoTabs){
28423 this.body.setStyle("overflow", "auto");
28426 this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
28428 if(this.closable !== false){
28429 this.el.addClass("x-dlg-closable");
28430 this.close = this.toolbox.createChild({cls:"x-dlg-close"});
28431 this.close.on("click", this.closeClick, this);
28432 this.close.addClassOnOver("x-dlg-close-over");
28434 if(this.collapsible !== false){
28435 this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
28436 this.collapseBtn.on("click", this.collapseClick, this);
28437 this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
28438 this.header.on("dblclick", this.collapseClick, this);
28440 if(this.resizable !== false){
28441 this.el.addClass("x-dlg-resizable");
28442 this.resizer = new Roo.Resizable(el, {
28443 minWidth: this.minWidth || 80,
28444 minHeight:this.minHeight || 80,
28445 handles: this.resizeHandles || "all",
28448 this.resizer.on("beforeresize", this.beforeResize, this);
28449 this.resizer.on("resize", this.onResize, this);
28451 if(this.draggable !== false){
28452 el.addClass("x-dlg-draggable");
28453 if (!this.proxyDrag) {
28454 var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
28457 var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
28459 dd.setHandleElId(this.header.id);
28460 dd.endDrag = this.endMove.createDelegate(this);
28461 dd.startDrag = this.startMove.createDelegate(this);
28462 dd.onDrag = this.onDrag.createDelegate(this);
28467 this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
28468 this.mask.enableDisplayMode("block");
28470 this.el.addClass("x-dlg-modal");
28473 this.shadow = new Roo.Shadow({
28474 mode : typeof this.shadow == "string" ? this.shadow : "sides",
28475 offset : this.shadowOffset
28478 this.shadowOffset = 0;
28480 if(Roo.useShims && this.shim !== false){
28481 this.shim = this.el.createShim();
28482 this.shim.hide = this.hideAction;
28490 if (this.buttons) {
28491 var bts= this.buttons;
28493 Roo.each(bts, function(b) {
28502 * Fires when a key is pressed
28503 * @param {Roo.BasicDialog} this
28504 * @param {Roo.EventObject} e
28509 * Fires when this dialog is moved by the user.
28510 * @param {Roo.BasicDialog} this
28511 * @param {Number} x The new page X
28512 * @param {Number} y The new page Y
28517 * Fires when this dialog is resized by the user.
28518 * @param {Roo.BasicDialog} this
28519 * @param {Number} width The new width
28520 * @param {Number} height The new height
28524 * @event beforehide
28525 * Fires before this dialog is hidden.
28526 * @param {Roo.BasicDialog} this
28528 "beforehide" : true,
28531 * Fires when this dialog is hidden.
28532 * @param {Roo.BasicDialog} this
28536 * @event beforeshow
28537 * Fires before this dialog is shown.
28538 * @param {Roo.BasicDialog} this
28540 "beforeshow" : true,
28543 * Fires when this dialog is shown.
28544 * @param {Roo.BasicDialog} this
28548 el.on("keydown", this.onKeyDown, this);
28549 el.on("mousedown", this.toFront, this);
28550 Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
28552 Roo.DialogManager.register(this);
28553 Roo.BasicDialog.superclass.constructor.call(this);
28556 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
28557 shadowOffset: Roo.isIE ? 6 : 5,
28560 minButtonWidth: 75,
28561 defaultButton: null,
28562 buttonAlign: "right",
28567 * Sets the dialog title text
28568 * @param {String} text The title text to display
28569 * @return {Roo.BasicDialog} this
28571 setTitle : function(text){
28572 this.header.update(text);
28577 closeClick : function(){
28582 collapseClick : function(){
28583 this[this.collapsed ? "expand" : "collapse"]();
28587 * Collapses the dialog to its minimized state (only the title bar is visible).
28588 * Equivalent to the user clicking the collapse dialog button.
28590 collapse : function(){
28591 if(!this.collapsed){
28592 this.collapsed = true;
28593 this.el.addClass("x-dlg-collapsed");
28594 this.restoreHeight = this.el.getHeight();
28595 this.resizeTo(this.el.getWidth(), this.header.getHeight());
28600 * Expands a collapsed dialog back to its normal state. Equivalent to the user
28601 * clicking the expand dialog button.
28603 expand : function(){
28604 if(this.collapsed){
28605 this.collapsed = false;
28606 this.el.removeClass("x-dlg-collapsed");
28607 this.resizeTo(this.el.getWidth(), this.restoreHeight);
28612 * Reinitializes the tabs component, clearing out old tabs and finding new ones.
28613 * @return {Roo.TabPanel} The tabs component
28615 initTabs : function(){
28616 var tabs = this.getTabs();
28617 while(tabs.getTab(0)){
28620 this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
28622 tabs.addTab(Roo.id(dom), dom.title);
28630 beforeResize : function(){
28631 this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
28635 onResize : function(){
28636 this.refreshSize();
28637 this.syncBodyHeight();
28638 this.adjustAssets();
28640 this.fireEvent("resize", this, this.size.width, this.size.height);
28644 onKeyDown : function(e){
28645 if(this.isVisible()){
28646 this.fireEvent("keydown", this, e);
28651 * Resizes the dialog.
28652 * @param {Number} width
28653 * @param {Number} height
28654 * @return {Roo.BasicDialog} this
28656 resizeTo : function(width, height){
28657 this.el.setSize(width, height);
28658 this.size = {width: width, height: height};
28659 this.syncBodyHeight();
28660 if(this.fixedcenter){
28663 if(this.isVisible()){
28664 this.constrainXY();
28665 this.adjustAssets();
28667 this.fireEvent("resize", this, width, height);
28673 * Resizes the dialog to fit the specified content size.
28674 * @param {Number} width
28675 * @param {Number} height
28676 * @return {Roo.BasicDialog} this
28678 setContentSize : function(w, h){
28679 h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
28680 w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
28681 //if(!this.el.isBorderBox()){
28682 h += this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
28683 w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
28686 h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
28687 w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
28689 this.resizeTo(w, h);
28694 * Adds a key listener for when this dialog is displayed. This allows you to hook in a function that will be
28695 * executed in response to a particular key being pressed while the dialog is active.
28696 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
28697 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
28698 * @param {Function} fn The function to call
28699 * @param {Object} scope (optional) The scope of the function
28700 * @return {Roo.BasicDialog} this
28702 addKeyListener : function(key, fn, scope){
28703 var keyCode, shift, ctrl, alt;
28704 if(typeof key == "object" && !(key instanceof Array)){
28705 keyCode = key["key"];
28706 shift = key["shift"];
28707 ctrl = key["ctrl"];
28712 var handler = function(dlg, e){
28713 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
28714 var k = e.getKey();
28715 if(keyCode instanceof Array){
28716 for(var i = 0, len = keyCode.length; i < len; i++){
28717 if(keyCode[i] == k){
28718 fn.call(scope || window, dlg, k, e);
28724 fn.call(scope || window, dlg, k, e);
28729 this.on("keydown", handler);
28734 * Returns the TabPanel component (creates it if it doesn't exist).
28735 * Note: If you wish to simply check for the existence of tabs without creating them,
28736 * check for a null 'tabs' property.
28737 * @return {Roo.TabPanel} The tabs component
28739 getTabs : function(){
28741 this.el.addClass("x-dlg-auto-tabs");
28742 this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
28743 this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
28749 * Adds a button to the footer section of the dialog.
28750 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
28751 * object or a valid Roo.DomHelper element config
28752 * @param {Function} handler The function called when the button is clicked
28753 * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
28754 * @return {Roo.Button} The new button
28756 addButton : function(config, handler, scope){
28757 var dh = Roo.DomHelper;
28759 this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
28761 if(!this.btnContainer){
28762 var tb = this.footer.createChild({
28764 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
28765 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
28767 this.btnContainer = tb.firstChild.firstChild.firstChild;
28772 minWidth: this.minButtonWidth,
28775 if(typeof config == "string"){
28776 bconfig.text = config;
28779 bconfig.dhconfig = config;
28781 Roo.apply(bconfig, config);
28785 if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
28786 bconfig.position = Math.max(0, bconfig.position);
28787 fc = this.btnContainer.childNodes[bconfig.position];
28790 var btn = new Roo.Button(
28792 this.btnContainer.insertBefore(document.createElement("td"),fc)
28793 : this.btnContainer.appendChild(document.createElement("td")),
28794 //Roo.get(this.btnContainer).createChild( { tag: 'td'}, fc ),
28797 this.syncBodyHeight();
28800 * Array of all the buttons that have been added to this dialog via addButton
28805 this.buttons.push(btn);
28810 * Sets the default button to be focused when the dialog is displayed.
28811 * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
28812 * @return {Roo.BasicDialog} this
28814 setDefaultButton : function(btn){
28815 this.defaultButton = btn;
28820 getHeaderFooterHeight : function(safe){
28823 height += this.header.getHeight();
28826 var fm = this.footer.getMargins();
28827 height += (this.footer.getHeight()+fm.top+fm.bottom);
28829 height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
28830 height += this.centerBg.getPadding("tb");
28835 syncBodyHeight : function(){
28836 var bd = this.body, cb = this.centerBg, bw = this.bwrap;
28837 var height = this.size.height - this.getHeaderFooterHeight(false);
28838 bd.setHeight(height-bd.getMargins("tb"));
28839 var hh = this.header.getHeight();
28840 var h = this.size.height-hh;
28842 bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
28843 bw.setHeight(h-cb.getPadding("tb"));
28844 bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
28845 bd.setWidth(bw.getWidth(true));
28847 this.tabs.syncHeight();
28849 this.tabs.el.repaint();
28855 * Restores the previous state of the dialog if Roo.state is configured.
28856 * @return {Roo.BasicDialog} this
28858 restoreState : function(){
28859 var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
28860 if(box && box.width){
28861 this.xy = [box.x, box.y];
28862 this.resizeTo(box.width, box.height);
28868 beforeShow : function(){
28870 if(this.fixedcenter){
28871 this.xy = this.el.getCenterXY(true);
28874 Roo.get(document.body).addClass("x-body-masked");
28875 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
28878 this.constrainXY();
28882 animShow : function(){
28883 var b = Roo.get(this.animateTarget, true).getBox();
28884 this.proxy.setSize(b.width, b.height);
28885 this.proxy.setLocation(b.x, b.y);
28887 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
28888 true, .35, this.showEl.createDelegate(this));
28892 * Shows the dialog.
28893 * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
28894 * @return {Roo.BasicDialog} this
28896 show : function(animateTarget){
28897 if (this.fireEvent("beforeshow", this) === false){
28900 if(this.syncHeightBeforeShow){
28901 this.syncBodyHeight();
28902 }else if(this.firstShow){
28903 this.firstShow = false;
28904 this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
28906 this.animateTarget = animateTarget || this.animateTarget;
28907 if(!this.el.isVisible()){
28909 if(this.animateTarget){
28919 showEl : function(){
28921 this.el.setXY(this.xy);
28923 this.adjustAssets(true);
28926 // IE peekaboo bug - fix found by Dave Fenwick
28930 this.fireEvent("show", this);
28934 * Focuses the dialog. If a defaultButton is set, it will receive focus, otherwise the
28935 * dialog itself will receive focus.
28937 focus : function(){
28938 if(this.defaultButton){
28939 this.defaultButton.focus();
28941 this.focusEl.focus();
28946 constrainXY : function(){
28947 if(this.constraintoviewport !== false){
28948 if(!this.viewSize){
28949 if(this.container){
28950 var s = this.container.getSize();
28951 this.viewSize = [s.width, s.height];
28953 this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
28956 var s = Roo.get(this.container||document).getScroll();
28958 var x = this.xy[0], y = this.xy[1];
28959 var w = this.size.width, h = this.size.height;
28960 var vw = this.viewSize[0], vh = this.viewSize[1];
28961 // only move it if it needs it
28963 // first validate right/bottom
28964 if(x + w > vw+s.left){
28968 if(y + h > vh+s.top){
28972 // then make sure top/left isn't negative
28984 if(this.isVisible()){
28985 this.el.setLocation(x, y);
28986 this.adjustAssets();
28993 onDrag : function(){
28994 if(!this.proxyDrag){
28995 this.xy = this.el.getXY();
28996 this.adjustAssets();
29001 adjustAssets : function(doShow){
29002 var x = this.xy[0], y = this.xy[1];
29003 var w = this.size.width, h = this.size.height;
29004 if(doShow === true){
29006 this.shadow.show(this.el);
29012 if(this.shadow && this.shadow.isVisible()){
29013 this.shadow.show(this.el);
29015 if(this.shim && this.shim.isVisible()){
29016 this.shim.setBounds(x, y, w, h);
29021 adjustViewport : function(w, h){
29023 w = Roo.lib.Dom.getViewWidth();
29024 h = Roo.lib.Dom.getViewHeight();
29027 this.viewSize = [w, h];
29028 if(this.modal && this.mask.isVisible()){
29029 this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
29030 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
29032 if(this.isVisible()){
29033 this.constrainXY();
29038 * Destroys this dialog and all its supporting elements (including any tabs, shim,
29039 * shadow, proxy, mask, etc.) Also removes all event listeners.
29040 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
29042 destroy : function(removeEl){
29043 if(this.isVisible()){
29044 this.animateTarget = null;
29047 Roo.EventManager.removeResizeListener(this.adjustViewport, this);
29049 this.tabs.destroy(removeEl);
29062 for(var i = 0, len = this.buttons.length; i < len; i++){
29063 this.buttons[i].destroy();
29066 this.el.removeAllListeners();
29067 if(removeEl === true){
29068 this.el.update("");
29071 Roo.DialogManager.unregister(this);
29075 startMove : function(){
29076 if(this.proxyDrag){
29079 if(this.constraintoviewport !== false){
29080 this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
29085 endMove : function(){
29086 if(!this.proxyDrag){
29087 Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
29089 Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
29092 this.refreshSize();
29093 this.adjustAssets();
29095 this.fireEvent("move", this, this.xy[0], this.xy[1]);
29099 * Brings this dialog to the front of any other visible dialogs
29100 * @return {Roo.BasicDialog} this
29102 toFront : function(){
29103 Roo.DialogManager.bringToFront(this);
29108 * Sends this dialog to the back (under) of any other visible dialogs
29109 * @return {Roo.BasicDialog} this
29111 toBack : function(){
29112 Roo.DialogManager.sendToBack(this);
29117 * Centers this dialog in the viewport
29118 * @return {Roo.BasicDialog} this
29120 center : function(){
29121 var xy = this.el.getCenterXY(true);
29122 this.moveTo(xy[0], xy[1]);
29127 * Moves the dialog's top-left corner to the specified point
29128 * @param {Number} x
29129 * @param {Number} y
29130 * @return {Roo.BasicDialog} this
29132 moveTo : function(x, y){
29134 if(this.isVisible()){
29135 this.el.setXY(this.xy);
29136 this.adjustAssets();
29142 * Aligns the dialog to the specified element
29143 * @param {String/HTMLElement/Roo.Element} element The element to align to.
29144 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
29145 * @param {Array} offsets (optional) Offset the positioning by [x, y]
29146 * @return {Roo.BasicDialog} this
29148 alignTo : function(element, position, offsets){
29149 this.xy = this.el.getAlignToXY(element, position, offsets);
29150 if(this.isVisible()){
29151 this.el.setXY(this.xy);
29152 this.adjustAssets();
29158 * Anchors an element to another element and realigns it when the window is resized.
29159 * @param {String/HTMLElement/Roo.Element} element The element to align to.
29160 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
29161 * @param {Array} offsets (optional) Offset the positioning by [x, y]
29162 * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
29163 * is a number, it is used as the buffer delay (defaults to 50ms).
29164 * @return {Roo.BasicDialog} this
29166 anchorTo : function(el, alignment, offsets, monitorScroll){
29167 var action = function(){
29168 this.alignTo(el, alignment, offsets);
29170 Roo.EventManager.onWindowResize(action, this);
29171 var tm = typeof monitorScroll;
29172 if(tm != 'undefined'){
29173 Roo.EventManager.on(window, 'scroll', action, this,
29174 {buffer: tm == 'number' ? monitorScroll : 50});
29181 * Returns true if the dialog is visible
29182 * @return {Boolean}
29184 isVisible : function(){
29185 return this.el.isVisible();
29189 animHide : function(callback){
29190 var b = Roo.get(this.animateTarget).getBox();
29192 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
29194 this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
29195 this.hideEl.createDelegate(this, [callback]));
29199 * Hides the dialog.
29200 * @param {Function} callback (optional) Function to call when the dialog is hidden
29201 * @return {Roo.BasicDialog} this
29203 hide : function(callback){
29204 if (this.fireEvent("beforehide", this) === false){
29208 this.shadow.hide();
29213 if(this.animateTarget){
29214 this.animHide(callback);
29217 this.hideEl(callback);
29223 hideEl : function(callback){
29227 Roo.get(document.body).removeClass("x-body-masked");
29229 this.fireEvent("hide", this);
29230 if(typeof callback == "function"){
29236 hideAction : function(){
29237 this.setLeft("-10000px");
29238 this.setTop("-10000px");
29239 this.setStyle("visibility", "hidden");
29243 refreshSize : function(){
29244 this.size = this.el.getSize();
29245 this.xy = this.el.getXY();
29246 Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
29250 // z-index is managed by the DialogManager and may be overwritten at any time
29251 setZIndex : function(index){
29253 this.mask.setStyle("z-index", index);
29256 this.shim.setStyle("z-index", ++index);
29259 this.shadow.setZIndex(++index);
29261 this.el.setStyle("z-index", ++index);
29263 this.proxy.setStyle("z-index", ++index);
29266 this.resizer.proxy.setStyle("z-index", ++index);
29269 this.lastZIndex = index;
29273 * Returns the element for this dialog
29274 * @return {Roo.Element} The underlying dialog Element
29276 getEl : function(){
29282 * @class Roo.DialogManager
29283 * Provides global access to BasicDialogs that have been created and
29284 * support for z-indexing (layering) multiple open dialogs.
29286 Roo.DialogManager = function(){
29288 var accessList = [];
29292 var sortDialogs = function(d1, d2){
29293 return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
29297 var orderDialogs = function(){
29298 accessList.sort(sortDialogs);
29299 var seed = Roo.DialogManager.zseed;
29300 for(var i = 0, len = accessList.length; i < len; i++){
29301 var dlg = accessList[i];
29303 dlg.setZIndex(seed + (i*10));
29310 * The starting z-index for BasicDialogs (defaults to 9000)
29311 * @type Number The z-index value
29316 register : function(dlg){
29317 list[dlg.id] = dlg;
29318 accessList.push(dlg);
29322 unregister : function(dlg){
29323 delete list[dlg.id];
29326 if(!accessList.indexOf){
29327 for( i = 0, len = accessList.length; i < len; i++){
29328 if(accessList[i] == dlg){
29329 accessList.splice(i, 1);
29334 i = accessList.indexOf(dlg);
29336 accessList.splice(i, 1);
29342 * Gets a registered dialog by id
29343 * @param {String/Object} id The id of the dialog or a dialog
29344 * @return {Roo.BasicDialog} this
29346 get : function(id){
29347 return typeof id == "object" ? id : list[id];
29351 * Brings the specified dialog to the front
29352 * @param {String/Object} dlg The id of the dialog or a dialog
29353 * @return {Roo.BasicDialog} this
29355 bringToFront : function(dlg){
29356 dlg = this.get(dlg);
29359 dlg._lastAccess = new Date().getTime();
29366 * Sends the specified dialog to the back
29367 * @param {String/Object} dlg The id of the dialog or a dialog
29368 * @return {Roo.BasicDialog} this
29370 sendToBack : function(dlg){
29371 dlg = this.get(dlg);
29372 dlg._lastAccess = -(new Date().getTime());
29378 * Hides all dialogs
29380 hideAll : function(){
29381 for(var id in list){
29382 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
29391 * @class Roo.LayoutDialog
29392 * @extends Roo.BasicDialog
29393 * Dialog which provides adjustments for working with a layout in a Dialog.
29394 * Add your necessary layout config options to the dialog's config.<br>
29395 * Example usage (including a nested layout):
29398 dialog = new Roo.LayoutDialog("download-dlg", {
29407 // layout config merges with the dialog config
29409 tabPosition: "top",
29410 alwaysShowTabs: true
29413 dialog.addKeyListener(27, dialog.hide, dialog);
29414 dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
29415 dialog.addButton("Build It!", this.getDownload, this);
29417 // we can even add nested layouts
29418 var innerLayout = new Roo.BorderLayout("dl-inner", {
29428 innerLayout.beginUpdate();
29429 innerLayout.add("east", new Roo.ContentPanel("dl-details"));
29430 innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
29431 innerLayout.endUpdate(true);
29433 var layout = dialog.getLayout();
29434 layout.beginUpdate();
29435 layout.add("center", new Roo.ContentPanel("standard-panel",
29436 {title: "Download the Source", fitToFrame:true}));
29437 layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
29438 {title: "Build your own roo.js"}));
29439 layout.getRegion("center").showPanel(sp);
29440 layout.endUpdate();
29444 * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
29445 * @param {Object} config configuration options
29447 Roo.LayoutDialog = function(el, cfg){
29450 if (typeof(cfg) == 'undefined') {
29451 config = Roo.apply({}, el);
29452 el = Roo.get( document.documentElement || document.body).createChild();
29453 //config.autoCreate = true;
29457 config.autoTabs = false;
29458 Roo.LayoutDialog.superclass.constructor.call(this, el, config);
29459 this.body.setStyle({overflow:"hidden", position:"relative"});
29460 this.layout = new Roo.BorderLayout(this.body.dom, config);
29461 this.layout.monitorWindowResize = false;
29462 this.el.addClass("x-dlg-auto-layout");
29463 // fix case when center region overwrites center function
29464 this.center = Roo.BasicDialog.prototype.center;
29465 this.on("show", this.layout.layout, this.layout, true);
29466 if (config.items) {
29467 var xitems = config.items;
29468 delete config.items;
29469 Roo.each(xitems, this.addxtype, this);
29474 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
29476 * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
29479 endUpdate : function(){
29480 this.layout.endUpdate();
29484 * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
29487 beginUpdate : function(){
29488 this.layout.beginUpdate();
29492 * Get the BorderLayout for this dialog
29493 * @return {Roo.BorderLayout}
29495 getLayout : function(){
29496 return this.layout;
29499 showEl : function(){
29500 Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
29502 this.layout.layout();
29507 // Use the syncHeightBeforeShow config option to control this automatically
29508 syncBodyHeight : function(){
29509 Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
29510 if(this.layout){this.layout.layout();}
29514 * Add an xtype element (actually adds to the layout.)
29515 * @return {Object} xdata xtype object data.
29518 addxtype : function(c) {
29519 return this.layout.addxtype(c);
29523 * Ext JS Library 1.1.1
29524 * Copyright(c) 2006-2007, Ext JS, LLC.
29526 * Originally Released Under LGPL - original licence link has changed is not relivant.
29529 * <script type="text/javascript">
29533 * @class Roo.MessageBox
29534 * Utility class for generating different styles of message boxes. The alias Roo.Msg can also be used.
29538 Roo.Msg.alert('Status', 'Changes saved successfully.');
29540 // Prompt for user data:
29541 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
29543 // process text value...
29547 // Show a dialog using config options:
29549 title:'Save Changes?',
29550 msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
29551 buttons: Roo.Msg.YESNOCANCEL,
29558 Roo.MessageBox = function(){
29559 var dlg, opt, mask, waitTimer;
29560 var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
29561 var buttons, activeTextEl, bwidth;
29564 var handleButton = function(button){
29566 Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
29570 var handleHide = function(){
29571 if(opt && opt.cls){
29572 dlg.el.removeClass(opt.cls);
29575 Roo.TaskMgr.stop(waitTimer);
29581 var updateButtons = function(b){
29584 buttons["ok"].hide();
29585 buttons["cancel"].hide();
29586 buttons["yes"].hide();
29587 buttons["no"].hide();
29588 dlg.footer.dom.style.display = 'none';
29591 dlg.footer.dom.style.display = '';
29592 for(var k in buttons){
29593 if(typeof buttons[k] != "function"){
29596 buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
29597 width += buttons[k].el.getWidth()+15;
29607 var handleEsc = function(d, k, e){
29608 if(opt && opt.closable !== false){
29618 * Returns a reference to the underlying {@link Roo.BasicDialog} element
29619 * @return {Roo.BasicDialog} The BasicDialog element
29621 getDialog : function(){
29623 dlg = new Roo.BasicDialog("x-msg-box", {
29628 constraintoviewport:false,
29630 collapsible : false,
29633 width:400, height:100,
29634 buttonAlign:"center",
29635 closeClick : function(){
29636 if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
29637 handleButton("no");
29639 handleButton("cancel");
29643 dlg.on("hide", handleHide);
29645 dlg.addKeyListener(27, handleEsc);
29647 var bt = this.buttonText;
29648 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
29649 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
29650 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
29651 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
29652 bodyEl = dlg.body.createChild({
29654 html:'<span class="roo-mb-text"></span><br /><input type="text" class="roo-mb-input" /><textarea class="roo-mb-textarea"></textarea><div class="roo-mb-progress-wrap"><div class="roo-mb-progress"><div class="roo-mb-progress-bar"> </div></div></div>'
29656 msgEl = bodyEl.dom.firstChild;
29657 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
29658 textboxEl.enableDisplayMode();
29659 textboxEl.addKeyListener([10,13], function(){
29660 if(dlg.isVisible() && opt && opt.buttons){
29661 if(opt.buttons.ok){
29662 handleButton("ok");
29663 }else if(opt.buttons.yes){
29664 handleButton("yes");
29668 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
29669 textareaEl.enableDisplayMode();
29670 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
29671 progressEl.enableDisplayMode();
29672 var pf = progressEl.dom.firstChild;
29674 pp = Roo.get(pf.firstChild);
29675 pp.setHeight(pf.offsetHeight);
29683 * Updates the message box body text
29684 * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
29685 * the XHTML-compliant non-breaking space character '&#160;')
29686 * @return {Roo.MessageBox} This message box
29688 updateText : function(text){
29689 if(!dlg.isVisible() && !opt.width){
29690 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
29692 msgEl.innerHTML = text || ' ';
29693 var w = Math.max(Math.min(opt.width || msgEl.offsetWidth, this.maxWidth),
29694 Math.max(opt.minWidth || this.minWidth, bwidth));
29696 activeTextEl.setWidth(w);
29698 if(dlg.isVisible()){
29699 dlg.fixedcenter = false;
29701 dlg.setContentSize(w, bodyEl.getHeight());
29702 if(dlg.isVisible()){
29703 dlg.fixedcenter = true;
29709 * Updates a progress-style message box's text and progress bar. Only relevant on message boxes
29710 * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
29711 * @param {Number} value Any number between 0 and 1 (e.g., .5)
29712 * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
29713 * @return {Roo.MessageBox} This message box
29715 updateProgress : function(value, text){
29717 this.updateText(text);
29719 if (pp) { // weird bug on my firefox - for some reason this is not defined
29720 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
29726 * Returns true if the message box is currently displayed
29727 * @return {Boolean} True if the message box is visible, else false
29729 isVisible : function(){
29730 return dlg && dlg.isVisible();
29734 * Hides the message box if it is displayed
29737 if(this.isVisible()){
29743 * Displays a new message box, or reinitializes an existing message box, based on the config options
29744 * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
29745 * The following config object properties are supported:
29747 Property Type Description
29748 ---------- --------------- ------------------------------------------------------------------------------------
29749 animEl String/Element An id or Element from which the message box should animate as it opens and
29750 closes (defaults to undefined)
29751 buttons Object/Boolean A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
29752 cancel:'Bar'}), or false to not show any buttons (defaults to false)
29753 closable Boolean False to hide the top-right close button (defaults to true). Note that
29754 progress and wait dialogs will ignore this property and always hide the
29755 close button as they can only be closed programmatically.
29756 cls String A custom CSS class to apply to the message box element
29757 defaultTextHeight Number The default height in pixels of the message box's multiline textarea if
29758 displayed (defaults to 75)
29759 fn Function A callback function to execute after closing the dialog. The arguments to the
29760 function will be btn (the name of the button that was clicked, if applicable,
29761 e.g. "ok"), and text (the value of the active text field, if applicable).
29762 Progress and wait dialogs will ignore this option since they do not respond to
29763 user actions and can only be closed programmatically, so any required function
29764 should be called by the same code after it closes the dialog.
29765 icon String A CSS class that provides a background image to be used as an icon for
29766 the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
29767 maxWidth Number The maximum width in pixels of the message box (defaults to 600)
29768 minWidth Number The minimum width in pixels of the message box (defaults to 100)
29769 modal Boolean False to allow user interaction with the page while the message box is
29770 displayed (defaults to true)
29771 msg String A string that will replace the existing message box body text (defaults
29772 to the XHTML-compliant non-breaking space character ' ')
29773 multiline Boolean True to prompt the user to enter multi-line text (defaults to false)
29774 progress Boolean True to display a progress bar (defaults to false)
29775 progressText String The text to display inside the progress bar if progress = true (defaults to '')
29776 prompt Boolean True to prompt the user to enter single-line text (defaults to false)
29777 proxyDrag Boolean True to display a lightweight proxy while dragging (defaults to false)
29778 title String The title text
29779 value String The string value to set into the active textbox element if displayed
29780 wait Boolean True to display a progress bar (defaults to false)
29781 width Number The width of the dialog in pixels
29788 msg: 'Please enter your address:',
29790 buttons: Roo.MessageBox.OKCANCEL,
29793 animEl: 'addAddressBtn'
29796 * @param {Object} config Configuration options
29797 * @return {Roo.MessageBox} This message box
29799 show : function(options){
29800 if(this.isVisible()){
29803 var d = this.getDialog();
29805 d.setTitle(opt.title || " ");
29806 d.close.setDisplayed(opt.closable !== false);
29807 activeTextEl = textboxEl;
29808 opt.prompt = opt.prompt || (opt.multiline ? true : false);
29813 textareaEl.setHeight(typeof opt.multiline == "number" ?
29814 opt.multiline : this.defaultTextHeight);
29815 activeTextEl = textareaEl;
29824 progressEl.setDisplayed(opt.progress === true);
29825 this.updateProgress(0);
29826 activeTextEl.dom.value = opt.value || "";
29828 dlg.setDefaultButton(activeTextEl);
29830 var bs = opt.buttons;
29833 db = buttons["ok"];
29834 }else if(bs && bs.yes){
29835 db = buttons["yes"];
29837 dlg.setDefaultButton(db);
29839 bwidth = updateButtons(opt.buttons);
29840 this.updateText(opt.msg);
29842 d.el.addClass(opt.cls);
29844 d.proxyDrag = opt.proxyDrag === true;
29845 d.modal = opt.modal !== false;
29846 d.mask = opt.modal !== false ? mask : false;
29847 if(!d.isVisible()){
29848 // force it to the end of the z-index stack so it gets a cursor in FF
29849 document.body.appendChild(dlg.el.dom);
29850 d.animateTarget = null;
29851 d.show(options.animEl);
29857 * Displays a message box with a progress bar. This message box has no buttons and is not closeable by
29858 * the user. You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
29859 * and closing the message box when the process is complete.
29860 * @param {String} title The title bar text
29861 * @param {String} msg The message box body text
29862 * @return {Roo.MessageBox} This message box
29864 progress : function(title, msg){
29871 minWidth: this.minProgressWidth,
29878 * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
29879 * If a callback function is passed it will be called after the user clicks the button, and the
29880 * id of the button that was clicked will be passed as the only parameter to the callback
29881 * (could also be the top-right close button).
29882 * @param {String} title The title bar text
29883 * @param {String} msg The message box body text
29884 * @param {Function} fn (optional) The callback function invoked after the message box is closed
29885 * @param {Object} scope (optional) The scope of the callback function
29886 * @return {Roo.MessageBox} This message box
29888 alert : function(title, msg, fn, scope){
29901 * Displays a message box with an infinitely auto-updating progress bar. This can be used to block user
29902 * interaction while waiting for a long-running process to complete that does not have defined intervals.
29903 * You are responsible for closing the message box when the process is complete.
29904 * @param {String} msg The message box body text
29905 * @param {String} title (optional) The title bar text
29906 * @return {Roo.MessageBox} This message box
29908 wait : function(msg, title){
29919 waitTimer = Roo.TaskMgr.start({
29921 Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
29929 * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
29930 * If a callback function is passed it will be called after the user clicks either button, and the id of the
29931 * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
29932 * @param {String} title The title bar text
29933 * @param {String} msg The message box body text
29934 * @param {Function} fn (optional) The callback function invoked after the message box is closed
29935 * @param {Object} scope (optional) The scope of the callback function
29936 * @return {Roo.MessageBox} This message box
29938 confirm : function(title, msg, fn, scope){
29942 buttons: this.YESNO,
29951 * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
29952 * JavaScript's Window.prompt). The prompt can be a single-line or multi-line textbox. If a callback function
29953 * is passed it will be called after the user clicks either button, and the id of the button that was clicked
29954 * (could also be the top-right close button) and the text that was entered will be passed as the two
29955 * parameters to the callback.
29956 * @param {String} title The title bar text
29957 * @param {String} msg The message box body text
29958 * @param {Function} fn (optional) The callback function invoked after the message box is closed
29959 * @param {Object} scope (optional) The scope of the callback function
29960 * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
29961 * property, or the height in pixels to create the textbox (defaults to false / single-line)
29962 * @return {Roo.MessageBox} This message box
29964 prompt : function(title, msg, fn, scope, multiline){
29968 buttons: this.OKCANCEL,
29973 multiline: multiline,
29980 * Button config that displays a single OK button
29985 * Button config that displays Yes and No buttons
29988 YESNO : {yes:true, no:true},
29990 * Button config that displays OK and Cancel buttons
29993 OKCANCEL : {ok:true, cancel:true},
29995 * Button config that displays Yes, No and Cancel buttons
29998 YESNOCANCEL : {yes:true, no:true, cancel:true},
30001 * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
30004 defaultTextHeight : 75,
30006 * The maximum width in pixels of the message box (defaults to 600)
30011 * The minimum width in pixels of the message box (defaults to 100)
30016 * The minimum width in pixels of the message box if it is a progress-style dialog. This is useful
30017 * for setting a different minimum width than text-only dialogs may need (defaults to 250)
30020 minProgressWidth : 250,
30022 * An object containing the default button text strings that can be overriden for localized language support.
30023 * Supported properties are: ok, cancel, yes and no.
30024 * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
30037 * Shorthand for {@link Roo.MessageBox}
30039 Roo.Msg = Roo.MessageBox;/*
30041 * Ext JS Library 1.1.1
30042 * Copyright(c) 2006-2007, Ext JS, LLC.
30044 * Originally Released Under LGPL - original licence link has changed is not relivant.
30047 * <script type="text/javascript">
30050 * @class Roo.QuickTips
30051 * Provides attractive and customizable tooltips for any element.
30054 Roo.QuickTips = function(){
30055 var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
30056 var ce, bd, xy, dd;
30057 var visible = false, disabled = true, inited = false;
30058 var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
30060 var onOver = function(e){
30064 var t = e.getTarget();
30065 if(!t || t.nodeType !== 1 || t == document || t == document.body){
30068 if(ce && t == ce.el){
30069 clearTimeout(hideProc);
30072 if(t && tagEls[t.id]){
30073 tagEls[t.id].el = t;
30074 showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
30077 var ttp, et = Roo.fly(t);
30078 var ns = cfg.namespace;
30079 if(tm.interceptTitles && t.title){
30082 t.removeAttribute("title");
30083 e.preventDefault();
30085 ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute);
30088 showProc = show.defer(tm.showDelay, tm, [{
30091 width: et.getAttributeNS(ns, cfg.width),
30092 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
30093 title: et.getAttributeNS(ns, cfg.title),
30094 cls: et.getAttributeNS(ns, cfg.cls)
30099 var onOut = function(e){
30100 clearTimeout(showProc);
30101 var t = e.getTarget();
30102 if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
30103 hideProc = setTimeout(hide, tm.hideDelay);
30107 var onMove = function(e){
30113 if(tm.trackMouse && ce){
30118 var onDown = function(e){
30119 clearTimeout(showProc);
30120 clearTimeout(hideProc);
30122 if(tm.hideOnClick){
30125 tm.enable.defer(100, tm);
30130 var getPad = function(){
30131 return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
30134 var show = function(o){
30138 clearTimeout(dismissProc);
30140 if(removeCls){ // in case manually hidden
30141 el.removeClass(removeCls);
30145 el.addClass(ce.cls);
30146 removeCls = ce.cls;
30149 tipTitle.update(ce.title);
30152 tipTitle.update('');
30155 el.dom.style.width = tm.maxWidth+'px';
30156 //tipBody.dom.style.width = '';
30157 tipBodyText.update(o.text);
30158 var p = getPad(), w = ce.width;
30160 var td = tipBodyText.dom;
30161 var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
30162 if(aw > tm.maxWidth){
30164 }else if(aw < tm.minWidth){
30170 //tipBody.setWidth(w);
30171 el.setWidth(parseInt(w, 10) + p);
30172 if(ce.autoHide === false){
30173 close.setDisplayed(true);
30178 close.setDisplayed(false);
30184 el.avoidY = xy[1]-18;
30189 el.setStyle("visibility", "visible");
30190 el.fadeIn({callback: afterShow});
30196 var afterShow = function(){
30200 if(tm.autoDismiss && ce.autoHide !== false){
30201 dismissProc = setTimeout(hide, tm.autoDismissDelay);
30206 var hide = function(noanim){
30207 clearTimeout(dismissProc);
30208 clearTimeout(hideProc);
30210 if(el.isVisible()){
30212 if(noanim !== true && tm.animate){
30213 el.fadeOut({callback: afterHide});
30220 var afterHide = function(){
30223 el.removeClass(removeCls);
30230 * @cfg {Number} minWidth
30231 * The minimum width of the quick tip (defaults to 40)
30235 * @cfg {Number} maxWidth
30236 * The maximum width of the quick tip (defaults to 300)
30240 * @cfg {Boolean} interceptTitles
30241 * True to automatically use the element's DOM title value if available (defaults to false)
30243 interceptTitles : false,
30245 * @cfg {Boolean} trackMouse
30246 * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
30248 trackMouse : false,
30250 * @cfg {Boolean} hideOnClick
30251 * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
30253 hideOnClick : true,
30255 * @cfg {Number} showDelay
30256 * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
30260 * @cfg {Number} hideDelay
30261 * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
30265 * @cfg {Boolean} autoHide
30266 * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
30267 * Used in conjunction with hideDelay.
30272 * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
30273 * (defaults to true). Used in conjunction with autoDismissDelay.
30275 autoDismiss : true,
30278 * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
30280 autoDismissDelay : 5000,
30282 * @cfg {Boolean} animate
30283 * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
30288 * @cfg {String} title
30289 * Title text to display (defaults to ''). This can be any valid HTML markup.
30293 * @cfg {String} text
30294 * Body text to display (defaults to ''). This can be any valid HTML markup.
30298 * @cfg {String} cls
30299 * A CSS class to apply to the base quick tip element (defaults to '').
30303 * @cfg {Number} width
30304 * Width in pixels of the quick tip (defaults to auto). Width will be ignored if it exceeds the bounds of
30305 * minWidth or maxWidth.
30310 * Initialize and enable QuickTips for first use. This should be called once before the first attempt to access
30311 * or display QuickTips in a page.
30314 tm = Roo.QuickTips;
30315 cfg = tm.tagConfig;
30317 if(!Roo.isReady){ // allow calling of init() before onReady
30318 Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
30321 el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
30322 el.fxDefaults = {stopFx: true};
30323 // maximum custom styling
30324 //el.update('<div class="x-tip-top-left"><div class="x-tip-top-right"><div class="x-tip-top"></div></div></div><div class="x-tip-bd-left"><div class="x-tip-bd-right"><div class="x-tip-bd"><div class="x-tip-close"></div><h3></h3><div class="x-tip-bd-inner"></div><div class="x-clear"></div></div></div></div><div class="x-tip-ft-left"><div class="x-tip-ft-right"><div class="x-tip-ft"></div></div></div>');
30325 el.update('<div class="x-tip-bd"><div class="x-tip-close"></div><h3></h3><div class="x-tip-bd-inner"></div><div class="x-clear"></div></div>');
30326 tipTitle = el.child('h3');
30327 tipTitle.enableDisplayMode("block");
30328 tipBody = el.child('div.x-tip-bd');
30329 tipBodyText = el.child('div.x-tip-bd-inner');
30330 //bdLeft = el.child('div.x-tip-bd-left');
30331 //bdRight = el.child('div.x-tip-bd-right');
30332 close = el.child('div.x-tip-close');
30333 close.enableDisplayMode("block");
30334 close.on("click", hide);
30335 var d = Roo.get(document);
30336 d.on("mousedown", onDown);
30337 d.on("mouseover", onOver);
30338 d.on("mouseout", onOut);
30339 d.on("mousemove", onMove);
30340 esc = d.addKeyListener(27, hide);
30343 dd = el.initDD("default", null, {
30344 onDrag : function(){
30348 dd.setHandleElId(tipTitle.id);
30357 * Configures a new quick tip instance and assigns it to a target element. The following config options
30360 Property Type Description
30361 ---------- --------------------- ------------------------------------------------------------------------
30362 target Element/String/Array An Element, id or array of ids that this quick tip should be tied to
30364 * @param {Object} config The config object
30366 register : function(config){
30367 var cs = config instanceof Array ? config : arguments;
30368 for(var i = 0, len = cs.length; i < len; i++) {
30370 var target = c.target;
30372 if(target instanceof Array){
30373 for(var j = 0, jlen = target.length; j < jlen; j++){
30374 tagEls[target[j]] = c;
30377 tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
30384 * Removes this quick tip from its element and destroys it.
30385 * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
30387 unregister : function(el){
30388 delete tagEls[Roo.id(el)];
30392 * Enable this quick tip.
30394 enable : function(){
30395 if(inited && disabled){
30397 if(locks.length < 1){
30404 * Disable this quick tip.
30406 disable : function(){
30408 clearTimeout(showProc);
30409 clearTimeout(hideProc);
30410 clearTimeout(dismissProc);
30418 * Returns true if the quick tip is enabled, else false.
30420 isEnabled : function(){
30427 attribute : "qtip",
30437 // backwards compat
30438 Roo.QuickTips.tips = Roo.QuickTips.register;/*
30440 * Ext JS Library 1.1.1
30441 * Copyright(c) 2006-2007, Ext JS, LLC.
30443 * Originally Released Under LGPL - original licence link has changed is not relivant.
30446 * <script type="text/javascript">
30451 * @class Roo.tree.TreePanel
30452 * @extends Roo.data.Tree
30454 * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
30455 * @cfg {Boolean} lines false to disable tree lines (defaults to true)
30456 * @cfg {Boolean} enableDD true to enable drag and drop
30457 * @cfg {Boolean} enableDrag true to enable just drag
30458 * @cfg {Boolean} enableDrop true to enable just drop
30459 * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
30460 * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
30461 * @cfg {String} ddGroup The DD group this TreePanel belongs to
30462 * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
30463 * @cfg {Boolean} ddScroll true to enable YUI body scrolling
30464 * @cfg {Boolean} containerScroll true to register this container with ScrollManager
30465 * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
30466 * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
30467 * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
30468 * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
30469 * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
30470 * @cfg {Boolean} loader A TreeLoader for use with this TreePanel
30471 * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
30472 * @cfg {Function} renderer Sets the rendering (formatting) function for the nodes. to return HTML markup for the tree view. The render function is called with the following parameters:<ul><li>The {Object} The data for the node.</li></ul>
30473 * @cfg {Function} rendererTip Sets the rendering (formatting) function for the nodes hovertip to return HTML markup for the tree view. The render function is called with the following parameters:<ul><li>The {Object} The data for the node.</li></ul>
30476 * @param {String/HTMLElement/Element} el The container element
30477 * @param {Object} config
30479 Roo.tree.TreePanel = function(el, config){
30481 var loader = false;
30483 root = config.root;
30484 delete config.root;
30486 if (config.loader) {
30487 loader = config.loader;
30488 delete config.loader;
30491 Roo.apply(this, config);
30492 Roo.tree.TreePanel.superclass.constructor.call(this);
30493 this.el = Roo.get(el);
30494 this.el.addClass('x-tree');
30495 //console.log(root);
30497 this.setRootNode( Roo.factory(root, Roo.tree));
30500 this.loader = Roo.factory(loader, Roo.tree);
30503 * Read-only. The id of the container element becomes this TreePanel's id.
30505 this.id = this.el.id;
30508 * @event beforeload
30509 * Fires before a node is loaded, return false to cancel
30510 * @param {Node} node The node being loaded
30512 "beforeload" : true,
30515 * Fires when a node is loaded
30516 * @param {Node} node The node that was loaded
30520 * @event textchange
30521 * Fires when the text for a node is changed
30522 * @param {Node} node The node
30523 * @param {String} text The new text
30524 * @param {String} oldText The old text
30526 "textchange" : true,
30528 * @event beforeexpand
30529 * Fires before a node is expanded, return false to cancel.
30530 * @param {Node} node The node
30531 * @param {Boolean} deep
30532 * @param {Boolean} anim
30534 "beforeexpand" : true,
30536 * @event beforecollapse
30537 * Fires before a node is collapsed, return false to cancel.
30538 * @param {Node} node The node
30539 * @param {Boolean} deep
30540 * @param {Boolean} anim
30542 "beforecollapse" : true,
30545 * Fires when a node is expanded
30546 * @param {Node} node The node
30550 * @event disabledchange
30551 * Fires when the disabled status of a node changes
30552 * @param {Node} node The node
30553 * @param {Boolean} disabled
30555 "disabledchange" : true,
30558 * Fires when a node is collapsed
30559 * @param {Node} node The node
30563 * @event beforeclick
30564 * Fires before click processing on a node. Return false to cancel the default action.
30565 * @param {Node} node The node
30566 * @param {Roo.EventObject} e The event object
30568 "beforeclick":true,
30570 * @event checkchange
30571 * Fires when a node with a checkbox's checked property changes
30572 * @param {Node} this This node
30573 * @param {Boolean} checked
30575 "checkchange":true,
30578 * Fires when a node is clicked
30579 * @param {Node} node The node
30580 * @param {Roo.EventObject} e The event object
30585 * Fires when a node is double clicked
30586 * @param {Node} node The node
30587 * @param {Roo.EventObject} e The event object
30591 * @event contextmenu
30592 * Fires when a node is right clicked
30593 * @param {Node} node The node
30594 * @param {Roo.EventObject} e The event object
30596 "contextmenu":true,
30598 * @event beforechildrenrendered
30599 * Fires right before the child nodes for a node are rendered
30600 * @param {Node} node The node
30602 "beforechildrenrendered":true,
30605 * Fires when a node starts being dragged
30606 * @param {Roo.tree.TreePanel} this
30607 * @param {Roo.tree.TreeNode} node
30608 * @param {event} e The raw browser event
30610 "startdrag" : true,
30613 * Fires when a drag operation is complete
30614 * @param {Roo.tree.TreePanel} this
30615 * @param {Roo.tree.TreeNode} node
30616 * @param {event} e The raw browser event
30621 * Fires when a dragged node is dropped on a valid DD target
30622 * @param {Roo.tree.TreePanel} this
30623 * @param {Roo.tree.TreeNode} node
30624 * @param {DD} dd The dd it was dropped on
30625 * @param {event} e The raw browser event
30629 * @event beforenodedrop
30630 * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
30631 * passed to handlers has the following properties:<br />
30632 * <ul style="padding:5px;padding-left:16px;">
30633 * <li>tree - The TreePanel</li>
30634 * <li>target - The node being targeted for the drop</li>
30635 * <li>data - The drag data from the drag source</li>
30636 * <li>point - The point of the drop - append, above or below</li>
30637 * <li>source - The drag source</li>
30638 * <li>rawEvent - Raw mouse event</li>
30639 * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
30640 * to be inserted by setting them on this object.</li>
30641 * <li>cancel - Set this to true to cancel the drop.</li>
30643 * @param {Object} dropEvent
30645 "beforenodedrop" : true,
30648 * Fires after a DD object is dropped on a node in this tree. The dropEvent
30649 * passed to handlers has the following properties:<br />
30650 * <ul style="padding:5px;padding-left:16px;">
30651 * <li>tree - The TreePanel</li>
30652 * <li>target - The node being targeted for the drop</li>
30653 * <li>data - The drag data from the drag source</li>
30654 * <li>point - The point of the drop - append, above or below</li>
30655 * <li>source - The drag source</li>
30656 * <li>rawEvent - Raw mouse event</li>
30657 * <li>dropNode - Dropped node(s).</li>
30659 * @param {Object} dropEvent
30663 * @event nodedragover
30664 * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
30665 * passed to handlers has the following properties:<br />
30666 * <ul style="padding:5px;padding-left:16px;">
30667 * <li>tree - The TreePanel</li>
30668 * <li>target - The node being targeted for the drop</li>
30669 * <li>data - The drag data from the drag source</li>
30670 * <li>point - The point of the drop - append, above or below</li>
30671 * <li>source - The drag source</li>
30672 * <li>rawEvent - Raw mouse event</li>
30673 * <li>dropNode - Drop node(s) provided by the source.</li>
30674 * <li>cancel - Set this to true to signal drop not allowed.</li>
30676 * @param {Object} dragOverEvent
30678 "nodedragover" : true
30681 if(this.singleExpand){
30682 this.on("beforeexpand", this.restrictExpand, this);
30685 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
30686 rootVisible : true,
30687 animate: Roo.enableFx,
30690 hlDrop : Roo.enableFx,
30694 rendererTip: false,
30696 restrictExpand : function(node){
30697 var p = node.parentNode;
30699 if(p.expandedChild && p.expandedChild.parentNode == p){
30700 p.expandedChild.collapse();
30702 p.expandedChild = node;
30706 // private override
30707 setRootNode : function(node){
30708 Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
30709 if(!this.rootVisible){
30710 node.ui = new Roo.tree.RootTreeNodeUI(node);
30716 * Returns the container element for this TreePanel
30718 getEl : function(){
30723 * Returns the default TreeLoader for this TreePanel
30725 getLoader : function(){
30726 return this.loader;
30732 expandAll : function(){
30733 this.root.expand(true);
30737 * Collapse all nodes
30739 collapseAll : function(){
30740 this.root.collapse(true);
30744 * Returns the selection model used by this TreePanel
30746 getSelectionModel : function(){
30747 if(!this.selModel){
30748 this.selModel = new Roo.tree.DefaultSelectionModel();
30750 return this.selModel;
30754 * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
30755 * @param {String} attribute (optional) Defaults to null (return the actual nodes)
30756 * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
30759 getChecked : function(a, startNode){
30760 startNode = startNode || this.root;
30762 var f = function(){
30763 if(this.attributes.checked){
30764 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
30767 startNode.cascade(f);
30772 * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
30773 * @param {String} path
30774 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
30775 * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
30776 * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
30778 expandPath : function(path, attr, callback){
30779 attr = attr || "id";
30780 var keys = path.split(this.pathSeparator);
30781 var curNode = this.root;
30782 if(curNode.attributes[attr] != keys[1]){ // invalid root
30784 callback(false, null);
30789 var f = function(){
30790 if(++index == keys.length){
30792 callback(true, curNode);
30796 var c = curNode.findChild(attr, keys[index]);
30799 callback(false, curNode);
30804 c.expand(false, false, f);
30806 curNode.expand(false, false, f);
30810 * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
30811 * @param {String} path
30812 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
30813 * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
30814 * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
30816 selectPath : function(path, attr, callback){
30817 attr = attr || "id";
30818 var keys = path.split(this.pathSeparator);
30819 var v = keys.pop();
30820 if(keys.length > 0){
30821 var f = function(success, node){
30822 if(success && node){
30823 var n = node.findChild(attr, v);
30829 }else if(callback){
30830 callback(false, n);
30834 callback(false, n);
30838 this.expandPath(keys.join(this.pathSeparator), attr, f);
30840 this.root.select();
30842 callback(true, this.root);
30847 getTreeEl : function(){
30852 * Trigger rendering of this TreePanel
30854 render : function(){
30855 if (this.innerCt) {
30856 return this; // stop it rendering more than once!!
30859 this.innerCt = this.el.createChild({tag:"ul",
30860 cls:"x-tree-root-ct " +
30861 (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
30863 if(this.containerScroll){
30864 Roo.dd.ScrollManager.register(this.el);
30866 if((this.enableDD || this.enableDrop) && !this.dropZone){
30868 * The dropZone used by this tree if drop is enabled
30869 * @type Roo.tree.TreeDropZone
30871 this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
30872 ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
30875 if((this.enableDD || this.enableDrag) && !this.dragZone){
30877 * The dragZone used by this tree if drag is enabled
30878 * @type Roo.tree.TreeDragZone
30880 this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
30881 ddGroup: this.ddGroup || "TreeDD",
30882 scroll: this.ddScroll
30885 this.getSelectionModel().init(this);
30887 console.log("ROOT not set in tree");
30890 this.root.render();
30891 if(!this.rootVisible){
30892 this.root.renderChildren();
30898 * Ext JS Library 1.1.1
30899 * Copyright(c) 2006-2007, Ext JS, LLC.
30901 * Originally Released Under LGPL - original licence link has changed is not relivant.
30904 * <script type="text/javascript">
30909 * @class Roo.tree.DefaultSelectionModel
30910 * @extends Roo.util.Observable
30911 * The default single selection for a TreePanel.
30913 Roo.tree.DefaultSelectionModel = function(){
30914 this.selNode = null;
30918 * @event selectionchange
30919 * Fires when the selected node changes
30920 * @param {DefaultSelectionModel} this
30921 * @param {TreeNode} node the new selection
30923 "selectionchange" : true,
30926 * @event beforeselect
30927 * Fires before the selected node changes, return false to cancel the change
30928 * @param {DefaultSelectionModel} this
30929 * @param {TreeNode} node the new selection
30930 * @param {TreeNode} node the old selection
30932 "beforeselect" : true
30936 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
30937 init : function(tree){
30939 tree.getTreeEl().on("keydown", this.onKeyDown, this);
30940 tree.on("click", this.onNodeClick, this);
30943 onNodeClick : function(node, e){
30944 if (e.ctrlKey && this.selNode == node) {
30945 this.unselect(node);
30953 * @param {TreeNode} node The node to select
30954 * @return {TreeNode} The selected node
30956 select : function(node){
30957 var last = this.selNode;
30958 if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
30960 last.ui.onSelectedChange(false);
30962 this.selNode = node;
30963 node.ui.onSelectedChange(true);
30964 this.fireEvent("selectionchange", this, node, last);
30971 * @param {TreeNode} node The node to unselect
30973 unselect : function(node){
30974 if(this.selNode == node){
30975 this.clearSelections();
30980 * Clear all selections
30982 clearSelections : function(){
30983 var n = this.selNode;
30985 n.ui.onSelectedChange(false);
30986 this.selNode = null;
30987 this.fireEvent("selectionchange", this, null);
30993 * Get the selected node
30994 * @return {TreeNode} The selected node
30996 getSelectedNode : function(){
30997 return this.selNode;
31001 * Returns true if the node is selected
31002 * @param {TreeNode} node The node to check
31003 * @return {Boolean}
31005 isSelected : function(node){
31006 return this.selNode == node;
31010 * Selects the node above the selected node in the tree, intelligently walking the nodes
31011 * @return TreeNode The new selection
31013 selectPrevious : function(){
31014 var s = this.selNode || this.lastSelNode;
31018 var ps = s.previousSibling;
31020 if(!ps.isExpanded() || ps.childNodes.length < 1){
31021 return this.select(ps);
31023 var lc = ps.lastChild;
31024 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
31027 return this.select(lc);
31029 } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
31030 return this.select(s.parentNode);
31036 * Selects the node above the selected node in the tree, intelligently walking the nodes
31037 * @return TreeNode The new selection
31039 selectNext : function(){
31040 var s = this.selNode || this.lastSelNode;
31044 if(s.firstChild && s.isExpanded()){
31045 return this.select(s.firstChild);
31046 }else if(s.nextSibling){
31047 return this.select(s.nextSibling);
31048 }else if(s.parentNode){
31050 s.parentNode.bubble(function(){
31051 if(this.nextSibling){
31052 newS = this.getOwnerTree().selModel.select(this.nextSibling);
31061 onKeyDown : function(e){
31062 var s = this.selNode || this.lastSelNode;
31063 // undesirable, but required
31068 var k = e.getKey();
31076 this.selectPrevious();
31079 e.preventDefault();
31080 if(s.hasChildNodes()){
31081 if(!s.isExpanded()){
31083 }else if(s.firstChild){
31084 this.select(s.firstChild, e);
31089 e.preventDefault();
31090 if(s.hasChildNodes() && s.isExpanded()){
31092 }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
31093 this.select(s.parentNode, e);
31101 * @class Roo.tree.MultiSelectionModel
31102 * @extends Roo.util.Observable
31103 * Multi selection for a TreePanel.
31105 Roo.tree.MultiSelectionModel = function(){
31106 this.selNodes = [];
31110 * @event selectionchange
31111 * Fires when the selected nodes change
31112 * @param {MultiSelectionModel} this
31113 * @param {Array} nodes Array of the selected nodes
31115 "selectionchange" : true
31119 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
31120 init : function(tree){
31122 tree.getTreeEl().on("keydown", this.onKeyDown, this);
31123 tree.on("click", this.onNodeClick, this);
31126 onNodeClick : function(node, e){
31127 this.select(node, e, e.ctrlKey);
31132 * @param {TreeNode} node The node to select
31133 * @param {EventObject} e (optional) An event associated with the selection
31134 * @param {Boolean} keepExisting True to retain existing selections
31135 * @return {TreeNode} The selected node
31137 select : function(node, e, keepExisting){
31138 if(keepExisting !== true){
31139 this.clearSelections(true);
31141 if(this.isSelected(node)){
31142 this.lastSelNode = node;
31145 this.selNodes.push(node);
31146 this.selMap[node.id] = node;
31147 this.lastSelNode = node;
31148 node.ui.onSelectedChange(true);
31149 this.fireEvent("selectionchange", this, this.selNodes);
31155 * @param {TreeNode} node The node to unselect
31157 unselect : function(node){
31158 if(this.selMap[node.id]){
31159 node.ui.onSelectedChange(false);
31160 var sn = this.selNodes;
31163 index = sn.indexOf(node);
31165 for(var i = 0, len = sn.length; i < len; i++){
31173 this.selNodes.splice(index, 1);
31175 delete this.selMap[node.id];
31176 this.fireEvent("selectionchange", this, this.selNodes);
31181 * Clear all selections
31183 clearSelections : function(suppressEvent){
31184 var sn = this.selNodes;
31186 for(var i = 0, len = sn.length; i < len; i++){
31187 sn[i].ui.onSelectedChange(false);
31189 this.selNodes = [];
31191 if(suppressEvent !== true){
31192 this.fireEvent("selectionchange", this, this.selNodes);
31198 * Returns true if the node is selected
31199 * @param {TreeNode} node The node to check
31200 * @return {Boolean}
31202 isSelected : function(node){
31203 return this.selMap[node.id] ? true : false;
31207 * Returns an array of the selected nodes
31210 getSelectedNodes : function(){
31211 return this.selNodes;
31214 onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
31216 selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
31218 selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
31221 * Ext JS Library 1.1.1
31222 * Copyright(c) 2006-2007, Ext JS, LLC.
31224 * Originally Released Under LGPL - original licence link has changed is not relivant.
31227 * <script type="text/javascript">
31231 * @class Roo.tree.TreeNode
31232 * @extends Roo.data.Node
31233 * @cfg {String} text The text for this node
31234 * @cfg {Boolean} expanded true to start the node expanded
31235 * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
31236 * @cfg {Boolean} allowDrop false if this node cannot be drop on
31237 * @cfg {Boolean} disabled true to start the node disabled
31238 * @cfg {String} icon The path to an icon for the node. The preferred way to do this
31239 * is to use the cls or iconCls attributes and add the icon via a CSS background image.
31240 * @cfg {String} cls A css class to be added to the node
31241 * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
31242 * @cfg {String} href URL of the link used for the node (defaults to #)
31243 * @cfg {String} hrefTarget target frame for the link
31244 * @cfg {String} qtip An Ext QuickTip for the node
31245 * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
31246 * @cfg {Boolean} singleClickExpand True for single click expand on this node
31247 * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
31248 * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
31249 * (defaults to undefined with no checkbox rendered)
31251 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
31253 Roo.tree.TreeNode = function(attributes){
31254 attributes = attributes || {};
31255 if(typeof attributes == "string"){
31256 attributes = {text: attributes};
31258 this.childrenRendered = false;
31259 this.rendered = false;
31260 Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
31261 this.expanded = attributes.expanded === true;
31262 this.isTarget = attributes.isTarget !== false;
31263 this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
31264 this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
31267 * Read-only. The text for this node. To change it use setText().
31270 this.text = attributes.text;
31272 * True if this node is disabled.
31275 this.disabled = attributes.disabled === true;
31279 * @event textchange
31280 * Fires when the text for this node is changed
31281 * @param {Node} this This node
31282 * @param {String} text The new text
31283 * @param {String} oldText The old text
31285 "textchange" : true,
31287 * @event beforeexpand
31288 * Fires before this node is expanded, return false to cancel.
31289 * @param {Node} this This node
31290 * @param {Boolean} deep
31291 * @param {Boolean} anim
31293 "beforeexpand" : true,
31295 * @event beforecollapse
31296 * Fires before this node is collapsed, return false to cancel.
31297 * @param {Node} this This node
31298 * @param {Boolean} deep
31299 * @param {Boolean} anim
31301 "beforecollapse" : true,
31304 * Fires when this node is expanded
31305 * @param {Node} this This node
31309 * @event disabledchange
31310 * Fires when the disabled status of this node changes
31311 * @param {Node} this This node
31312 * @param {Boolean} disabled
31314 "disabledchange" : true,
31317 * Fires when this node is collapsed
31318 * @param {Node} this This node
31322 * @event beforeclick
31323 * Fires before click processing. Return false to cancel the default action.
31324 * @param {Node} this This node
31325 * @param {Roo.EventObject} e The event object
31327 "beforeclick":true,
31329 * @event checkchange
31330 * Fires when a node with a checkbox's checked property changes
31331 * @param {Node} this This node
31332 * @param {Boolean} checked
31334 "checkchange":true,
31337 * Fires when this node is clicked
31338 * @param {Node} this This node
31339 * @param {Roo.EventObject} e The event object
31344 * Fires when this node is double clicked
31345 * @param {Node} this This node
31346 * @param {Roo.EventObject} e The event object
31350 * @event contextmenu
31351 * Fires when this node is right clicked
31352 * @param {Node} this This node
31353 * @param {Roo.EventObject} e The event object
31355 "contextmenu":true,
31357 * @event beforechildrenrendered
31358 * Fires right before the child nodes for this node are rendered
31359 * @param {Node} this This node
31361 "beforechildrenrendered":true
31364 var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
31367 * Read-only. The UI for this node
31370 this.ui = new uiClass(this);
31372 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
31373 preventHScroll: true,
31375 * Returns true if this node is expanded
31376 * @return {Boolean}
31378 isExpanded : function(){
31379 return this.expanded;
31383 * Returns the UI object for this node
31384 * @return {TreeNodeUI}
31386 getUI : function(){
31390 // private override
31391 setFirstChild : function(node){
31392 var of = this.firstChild;
31393 Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
31394 if(this.childrenRendered && of && node != of){
31395 of.renderIndent(true, true);
31398 this.renderIndent(true, true);
31402 // private override
31403 setLastChild : function(node){
31404 var ol = this.lastChild;
31405 Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
31406 if(this.childrenRendered && ol && node != ol){
31407 ol.renderIndent(true, true);
31410 this.renderIndent(true, true);
31414 // these methods are overridden to provide lazy rendering support
31415 // private override
31416 appendChild : function(){
31417 var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
31418 if(node && this.childrenRendered){
31421 this.ui.updateExpandIcon();
31425 // private override
31426 removeChild : function(node){
31427 this.ownerTree.getSelectionModel().unselect(node);
31428 Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
31429 // if it's been rendered remove dom node
31430 if(this.childrenRendered){
31433 if(this.childNodes.length < 1){
31434 this.collapse(false, false);
31436 this.ui.updateExpandIcon();
31438 if(!this.firstChild) {
31439 this.childrenRendered = false;
31444 // private override
31445 insertBefore : function(node, refNode){
31446 var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
31447 if(newNode && refNode && this.childrenRendered){
31450 this.ui.updateExpandIcon();
31455 * Sets the text for this node
31456 * @param {String} text
31458 setText : function(text){
31459 var oldText = this.text;
31461 this.attributes.text = text;
31462 if(this.rendered){ // event without subscribing
31463 this.ui.onTextChange(this, text, oldText);
31465 this.fireEvent("textchange", this, text, oldText);
31469 * Triggers selection of this node
31471 select : function(){
31472 this.getOwnerTree().getSelectionModel().select(this);
31476 * Triggers deselection of this node
31478 unselect : function(){
31479 this.getOwnerTree().getSelectionModel().unselect(this);
31483 * Returns true if this node is selected
31484 * @return {Boolean}
31486 isSelected : function(){
31487 return this.getOwnerTree().getSelectionModel().isSelected(this);
31491 * Expand this node.
31492 * @param {Boolean} deep (optional) True to expand all children as well
31493 * @param {Boolean} anim (optional) false to cancel the default animation
31494 * @param {Function} callback (optional) A callback to be called when
31495 * expanding this node completes (does not wait for deep expand to complete).
31496 * Called with 1 parameter, this node.
31498 expand : function(deep, anim, callback){
31499 if(!this.expanded){
31500 if(this.fireEvent("beforeexpand", this, deep, anim) === false){
31503 if(!this.childrenRendered){
31504 this.renderChildren();
31506 this.expanded = true;
31507 if(!this.isHiddenRoot() && (this.getOwnerTree().animate && anim !== false) || anim){
31508 this.ui.animExpand(function(){
31509 this.fireEvent("expand", this);
31510 if(typeof callback == "function"){
31514 this.expandChildNodes(true);
31516 }.createDelegate(this));
31520 this.fireEvent("expand", this);
31521 if(typeof callback == "function"){
31526 if(typeof callback == "function"){
31531 this.expandChildNodes(true);
31535 isHiddenRoot : function(){
31536 return this.isRoot && !this.getOwnerTree().rootVisible;
31540 * Collapse this node.
31541 * @param {Boolean} deep (optional) True to collapse all children as well
31542 * @param {Boolean} anim (optional) false to cancel the default animation
31544 collapse : function(deep, anim){
31545 if(this.expanded && !this.isHiddenRoot()){
31546 if(this.fireEvent("beforecollapse", this, deep, anim) === false){
31549 this.expanded = false;
31550 if((this.getOwnerTree().animate && anim !== false) || anim){
31551 this.ui.animCollapse(function(){
31552 this.fireEvent("collapse", this);
31554 this.collapseChildNodes(true);
31556 }.createDelegate(this));
31559 this.ui.collapse();
31560 this.fireEvent("collapse", this);
31564 var cs = this.childNodes;
31565 for(var i = 0, len = cs.length; i < len; i++) {
31566 cs[i].collapse(true, false);
31572 delayedExpand : function(delay){
31573 if(!this.expandProcId){
31574 this.expandProcId = this.expand.defer(delay, this);
31579 cancelExpand : function(){
31580 if(this.expandProcId){
31581 clearTimeout(this.expandProcId);
31583 this.expandProcId = false;
31587 * Toggles expanded/collapsed state of the node
31589 toggle : function(){
31598 * Ensures all parent nodes are expanded
31600 ensureVisible : function(callback){
31601 var tree = this.getOwnerTree();
31602 tree.expandPath(this.parentNode.getPath(), false, function(){
31603 tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
31604 Roo.callback(callback);
31605 }.createDelegate(this));
31609 * Expand all child nodes
31610 * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
31612 expandChildNodes : function(deep){
31613 var cs = this.childNodes;
31614 for(var i = 0, len = cs.length; i < len; i++) {
31615 cs[i].expand(deep);
31620 * Collapse all child nodes
31621 * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
31623 collapseChildNodes : function(deep){
31624 var cs = this.childNodes;
31625 for(var i = 0, len = cs.length; i < len; i++) {
31626 cs[i].collapse(deep);
31631 * Disables this node
31633 disable : function(){
31634 this.disabled = true;
31636 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
31637 this.ui.onDisableChange(this, true);
31639 this.fireEvent("disabledchange", this, true);
31643 * Enables this node
31645 enable : function(){
31646 this.disabled = false;
31647 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
31648 this.ui.onDisableChange(this, false);
31650 this.fireEvent("disabledchange", this, false);
31654 renderChildren : function(suppressEvent){
31655 if(suppressEvent !== false){
31656 this.fireEvent("beforechildrenrendered", this);
31658 var cs = this.childNodes;
31659 for(var i = 0, len = cs.length; i < len; i++){
31660 cs[i].render(true);
31662 this.childrenRendered = true;
31666 sort : function(fn, scope){
31667 Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
31668 if(this.childrenRendered){
31669 var cs = this.childNodes;
31670 for(var i = 0, len = cs.length; i < len; i++){
31671 cs[i].render(true);
31677 render : function(bulkRender){
31678 this.ui.render(bulkRender);
31679 if(!this.rendered){
31680 this.rendered = true;
31682 this.expanded = false;
31683 this.expand(false, false);
31689 renderIndent : function(deep, refresh){
31691 this.ui.childIndent = null;
31693 this.ui.renderIndent();
31694 if(deep === true && this.childrenRendered){
31695 var cs = this.childNodes;
31696 for(var i = 0, len = cs.length; i < len; i++){
31697 cs[i].renderIndent(true, refresh);
31703 * Ext JS Library 1.1.1
31704 * Copyright(c) 2006-2007, Ext JS, LLC.
31706 * Originally Released Under LGPL - original licence link has changed is not relivant.
31709 * <script type="text/javascript">
31713 * @class Roo.tree.AsyncTreeNode
31714 * @extends Roo.tree.TreeNode
31715 * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
31717 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
31719 Roo.tree.AsyncTreeNode = function(config){
31720 this.loaded = false;
31721 this.loading = false;
31722 Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
31724 * @event beforeload
31725 * Fires before this node is loaded, return false to cancel
31726 * @param {Node} this This node
31728 this.addEvents({'beforeload':true, 'load': true});
31731 * Fires when this node is loaded
31732 * @param {Node} this This node
31735 * The loader used by this node (defaults to using the tree's defined loader)
31740 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
31741 expand : function(deep, anim, callback){
31742 if(this.loading){ // if an async load is already running, waiting til it's done
31744 var f = function(){
31745 if(!this.loading){ // done loading
31746 clearInterval(timer);
31747 this.expand(deep, anim, callback);
31749 }.createDelegate(this);
31750 timer = setInterval(f, 200);
31754 if(this.fireEvent("beforeload", this) === false){
31757 this.loading = true;
31758 this.ui.beforeLoad(this);
31759 var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
31761 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
31765 Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
31769 * Returns true if this node is currently loading
31770 * @return {Boolean}
31772 isLoading : function(){
31773 return this.loading;
31776 loadComplete : function(deep, anim, callback){
31777 this.loading = false;
31778 this.loaded = true;
31779 this.ui.afterLoad(this);
31780 this.fireEvent("load", this);
31781 this.expand(deep, anim, callback);
31785 * Returns true if this node has been loaded
31786 * @return {Boolean}
31788 isLoaded : function(){
31789 return this.loaded;
31792 hasChildNodes : function(){
31793 if(!this.isLeaf() && !this.loaded){
31796 return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
31801 * Trigger a reload for this node
31802 * @param {Function} callback
31804 reload : function(callback){
31805 this.collapse(false, false);
31806 while(this.firstChild){
31807 this.removeChild(this.firstChild);
31809 this.childrenRendered = false;
31810 this.loaded = false;
31811 if(this.isHiddenRoot()){
31812 this.expanded = false;
31814 this.expand(false, false, callback);
31818 * Ext JS Library 1.1.1
31819 * Copyright(c) 2006-2007, Ext JS, LLC.
31821 * Originally Released Under LGPL - original licence link has changed is not relivant.
31824 * <script type="text/javascript">
31828 * @class Roo.tree.TreeNodeUI
31830 * @param {Object} node The node to render
31831 * The TreeNode UI implementation is separate from the
31832 * tree implementation. Unless you are customizing the tree UI,
31833 * you should never have to use this directly.
31835 Roo.tree.TreeNodeUI = function(node){
31837 this.rendered = false;
31838 this.animating = false;
31839 this.emptyIcon = Roo.BLANK_IMAGE_URL;
31842 Roo.tree.TreeNodeUI.prototype = {
31843 removeChild : function(node){
31845 this.ctNode.removeChild(node.ui.getEl());
31849 beforeLoad : function(){
31850 this.addClass("x-tree-node-loading");
31853 afterLoad : function(){
31854 this.removeClass("x-tree-node-loading");
31857 onTextChange : function(node, text, oldText){
31859 this.textNode.innerHTML = text;
31863 onDisableChange : function(node, state){
31864 this.disabled = state;
31866 this.addClass("x-tree-node-disabled");
31868 this.removeClass("x-tree-node-disabled");
31872 onSelectedChange : function(state){
31875 this.addClass("x-tree-selected");
31878 this.removeClass("x-tree-selected");
31882 onMove : function(tree, node, oldParent, newParent, index, refNode){
31883 this.childIndent = null;
31885 var targetNode = newParent.ui.getContainer();
31886 if(!targetNode){//target not rendered
31887 this.holder = document.createElement("div");
31888 this.holder.appendChild(this.wrap);
31891 var insertBefore = refNode ? refNode.ui.getEl() : null;
31893 targetNode.insertBefore(this.wrap, insertBefore);
31895 targetNode.appendChild(this.wrap);
31897 this.node.renderIndent(true);
31901 addClass : function(cls){
31903 Roo.fly(this.elNode).addClass(cls);
31907 removeClass : function(cls){
31909 Roo.fly(this.elNode).removeClass(cls);
31913 remove : function(){
31915 this.holder = document.createElement("div");
31916 this.holder.appendChild(this.wrap);
31920 fireEvent : function(){
31921 return this.node.fireEvent.apply(this.node, arguments);
31924 initEvents : function(){
31925 this.node.on("move", this.onMove, this);
31926 var E = Roo.EventManager;
31927 var a = this.anchor;
31929 var el = Roo.fly(a, '_treeui');
31931 if(Roo.isOpera){ // opera render bug ignores the CSS
31932 el.setStyle("text-decoration", "none");
31935 el.on("click", this.onClick, this);
31936 el.on("dblclick", this.onDblClick, this);
31939 Roo.EventManager.on(this.checkbox,
31940 Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
31943 el.on("contextmenu", this.onContextMenu, this);
31945 var icon = Roo.fly(this.iconNode);
31946 icon.on("click", this.onClick, this);
31947 icon.on("dblclick", this.onDblClick, this);
31948 icon.on("contextmenu", this.onContextMenu, this);
31949 E.on(this.ecNode, "click", this.ecClick, this, true);
31951 if(this.node.disabled){
31952 this.addClass("x-tree-node-disabled");
31954 if(this.node.hidden){
31955 this.addClass("x-tree-node-disabled");
31957 var ot = this.node.getOwnerTree();
31958 var dd = ot.enableDD || ot.enableDrag || ot.enableDrop;
31959 if(dd && (!this.node.isRoot || ot.rootVisible)){
31960 Roo.dd.Registry.register(this.elNode, {
31962 handles: this.getDDHandles(),
31968 getDDHandles : function(){
31969 return [this.iconNode, this.textNode];
31974 this.wrap.style.display = "none";
31980 this.wrap.style.display = "";
31984 onContextMenu : function(e){
31985 if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
31986 e.preventDefault();
31988 this.fireEvent("contextmenu", this.node, e);
31992 onClick : function(e){
31997 if(this.fireEvent("beforeclick", this.node, e) !== false){
31998 if(!this.disabled && this.node.attributes.href){
31999 this.fireEvent("click", this.node, e);
32002 e.preventDefault();
32007 if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
32008 this.node.toggle();
32011 this.fireEvent("click", this.node, e);
32017 onDblClick : function(e){
32018 e.preventDefault();
32023 this.toggleCheck();
32025 if(!this.animating && this.node.hasChildNodes()){
32026 this.node.toggle();
32028 this.fireEvent("dblclick", this.node, e);
32031 onCheckChange : function(){
32032 var checked = this.checkbox.checked;
32033 this.node.attributes.checked = checked;
32034 this.fireEvent('checkchange', this.node, checked);
32037 ecClick : function(e){
32038 if(!this.animating && this.node.hasChildNodes()){
32039 this.node.toggle();
32043 startDrop : function(){
32044 this.dropping = true;
32047 // delayed drop so the click event doesn't get fired on a drop
32048 endDrop : function(){
32049 setTimeout(function(){
32050 this.dropping = false;
32051 }.createDelegate(this), 50);
32054 expand : function(){
32055 this.updateExpandIcon();
32056 this.ctNode.style.display = "";
32059 focus : function(){
32060 if(!this.node.preventHScroll){
32061 try{this.anchor.focus();
32063 }else if(!Roo.isIE){
32065 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
32066 var l = noscroll.scrollLeft;
32067 this.anchor.focus();
32068 noscroll.scrollLeft = l;
32073 toggleCheck : function(value){
32074 var cb = this.checkbox;
32076 cb.checked = (value === undefined ? !cb.checked : value);
32082 this.anchor.blur();
32086 animExpand : function(callback){
32087 var ct = Roo.get(this.ctNode);
32089 if(!this.node.hasChildNodes()){
32090 this.updateExpandIcon();
32091 this.ctNode.style.display = "";
32092 Roo.callback(callback);
32095 this.animating = true;
32096 this.updateExpandIcon();
32099 callback : function(){
32100 this.animating = false;
32101 Roo.callback(callback);
32104 duration: this.node.ownerTree.duration || .25
32108 highlight : function(){
32109 var tree = this.node.getOwnerTree();
32110 Roo.fly(this.wrap).highlight(
32111 tree.hlColor || "C3DAF9",
32112 {endColor: tree.hlBaseColor}
32116 collapse : function(){
32117 this.updateExpandIcon();
32118 this.ctNode.style.display = "none";
32121 animCollapse : function(callback){
32122 var ct = Roo.get(this.ctNode);
32123 ct.enableDisplayMode('block');
32126 this.animating = true;
32127 this.updateExpandIcon();
32130 callback : function(){
32131 this.animating = false;
32132 Roo.callback(callback);
32135 duration: this.node.ownerTree.duration || .25
32139 getContainer : function(){
32140 return this.ctNode;
32143 getEl : function(){
32147 appendDDGhost : function(ghostNode){
32148 ghostNode.appendChild(this.elNode.cloneNode(true));
32151 getDDRepairXY : function(){
32152 return Roo.lib.Dom.getXY(this.iconNode);
32155 onRender : function(){
32159 render : function(bulkRender){
32160 var n = this.node, a = n.attributes;
32161 var targetNode = n.parentNode ?
32162 n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
32164 if(!this.rendered){
32165 this.rendered = true;
32167 this.renderElements(n, a, targetNode, bulkRender);
32170 if(this.textNode.setAttributeNS){
32171 this.textNode.setAttributeNS("ext", "qtip", a.qtip);
32173 this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
32176 this.textNode.setAttribute("ext:qtip", a.qtip);
32178 this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
32181 }else if(a.qtipCfg){
32182 a.qtipCfg.target = Roo.id(this.textNode);
32183 Roo.QuickTips.register(a.qtipCfg);
32186 if(!this.node.expanded){
32187 this.updateExpandIcon();
32190 if(bulkRender === true) {
32191 targetNode.appendChild(this.wrap);
32196 renderElements : function(n, a, targetNode, bulkRender){
32197 // add some indent caching, this helps performance when rendering a large tree
32198 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
32199 var t = n.getOwnerTree();
32200 var txt = t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
32201 var tip = t.rendererTip ? t.rendererTip(n.attributes) : txt;
32202 var cb = typeof a.checked == 'boolean';
32203 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
32204 var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
32205 '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
32206 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
32207 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
32208 cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
32209 '<a hidefocus="on" href="',href,'" tabIndex="1" ',
32210 a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "",
32211 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
32212 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
32215 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
32216 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
32217 n.nextSibling.ui.getEl(), buf.join(""));
32219 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
32222 this.elNode = this.wrap.childNodes[0];
32223 this.ctNode = this.wrap.childNodes[1];
32224 var cs = this.elNode.childNodes;
32225 this.indentNode = cs[0];
32226 this.ecNode = cs[1];
32227 this.iconNode = cs[2];
32230 this.checkbox = cs[3];
32233 this.anchor = cs[index];
32234 this.textNode = cs[index].firstChild;
32237 getAnchor : function(){
32238 return this.anchor;
32241 getTextEl : function(){
32242 return this.textNode;
32245 getIconEl : function(){
32246 return this.iconNode;
32249 isChecked : function(){
32250 return this.checkbox ? this.checkbox.checked : false;
32253 updateExpandIcon : function(){
32255 var n = this.node, c1, c2;
32256 var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
32257 var hasChild = n.hasChildNodes();
32261 c1 = "x-tree-node-collapsed";
32262 c2 = "x-tree-node-expanded";
32265 c1 = "x-tree-node-expanded";
32266 c2 = "x-tree-node-collapsed";
32269 this.removeClass("x-tree-node-leaf");
32270 this.wasLeaf = false;
32272 if(this.c1 != c1 || this.c2 != c2){
32273 Roo.fly(this.elNode).replaceClass(c1, c2);
32274 this.c1 = c1; this.c2 = c2;
32278 Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
32281 this.wasLeaf = true;
32284 var ecc = "x-tree-ec-icon "+cls;
32285 if(this.ecc != ecc){
32286 this.ecNode.className = ecc;
32292 getChildIndent : function(){
32293 if(!this.childIndent){
32297 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
32299 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
32301 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
32306 this.childIndent = buf.join("");
32308 return this.childIndent;
32311 renderIndent : function(){
32314 var p = this.node.parentNode;
32316 indent = p.ui.getChildIndent();
32318 if(this.indentMarkup != indent){ // don't rerender if not required
32319 this.indentNode.innerHTML = indent;
32320 this.indentMarkup = indent;
32322 this.updateExpandIcon();
32327 Roo.tree.RootTreeNodeUI = function(){
32328 Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
32330 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
32331 render : function(){
32332 if(!this.rendered){
32333 var targetNode = this.node.ownerTree.innerCt.dom;
32334 this.node.expanded = true;
32335 targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
32336 this.wrap = this.ctNode = targetNode.firstChild;
32339 collapse : function(){
32341 expand : function(){
32345 * Ext JS Library 1.1.1
32346 * Copyright(c) 2006-2007, Ext JS, LLC.
32348 * Originally Released Under LGPL - original licence link has changed is not relivant.
32351 * <script type="text/javascript">
32354 * @class Roo.tree.TreeLoader
32355 * @extends Roo.util.Observable
32356 * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
32357 * nodes from a specified URL. The response must be a javascript Array definition
32358 * who's elements are node definition objects. eg:
32360 [{ 'id': 1, 'text': 'A folder Node', 'leaf': false },
32361 { 'id': 2, 'text': 'A leaf Node', 'leaf': true }]
32364 * A server request is sent, and child nodes are loaded only when a node is expanded.
32365 * The loading node's id is passed to the server under the parameter name "node" to
32366 * enable the server to produce the correct child nodes.
32368 * To pass extra parameters, an event handler may be attached to the "beforeload"
32369 * event, and the parameters specified in the TreeLoader's baseParams property:
32371 myTreeLoader.on("beforeload", function(treeLoader, node) {
32372 this.baseParams.category = node.attributes.category;
32375 * This would pass an HTTP parameter called "category" to the server containing
32376 * the value of the Node's "category" attribute.
32378 * Creates a new Treeloader.
32379 * @param {Object} config A config object containing config properties.
32381 Roo.tree.TreeLoader = function(config){
32382 this.baseParams = {};
32383 this.requestMethod = "POST";
32384 Roo.apply(this, config);
32389 * @event beforeload
32390 * Fires before a network request is made to retrieve the Json text which specifies a node's children.
32391 * @param {Object} This TreeLoader object.
32392 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
32393 * @param {Object} callback The callback function specified in the {@link #load} call.
32398 * Fires when the node has been successfuly loaded.
32399 * @param {Object} This TreeLoader object.
32400 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
32401 * @param {Object} response The response object containing the data from the server.
32405 * @event loadexception
32406 * Fires if the network request failed.
32407 * @param {Object} This TreeLoader object.
32408 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
32409 * @param {Object} response The response object containing the data from the server.
32411 loadexception : true,
32414 * Fires before a node is created, enabling you to return custom Node types
32415 * @param {Object} This TreeLoader object.
32416 * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
32421 Roo.tree.TreeLoader.superclass.constructor.call(this);
32424 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
32426 * @cfg {String} dataUrl The URL from which to request a Json string which
32427 * specifies an array of node definition object representing the child nodes
32431 * @cfg {Object} baseParams (optional) An object containing properties which
32432 * specify HTTP parameters to be passed to each request for child nodes.
32435 * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
32436 * created by this loader. If the attributes sent by the server have an attribute in this object,
32437 * they take priority.
32440 * @cfg {Object} uiProviders (optional) An object containing properties which
32442 * DEPRECIATED - use 'create' event handler to modify attributes - which affect creation.
32443 * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
32444 * <i>uiProvider</i> attribute of a returned child node is a string rather
32445 * than a reference to a TreeNodeUI implementation, this that string value
32446 * is used as a property name in the uiProviders object. You can define the provider named
32447 * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
32452 * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
32453 * child nodes before loading.
32455 clearOnLoad : true,
32458 * @cfg {String} root (optional) Default to false. Use this to read data from an object
32459 * property on loading, rather than expecting an array. (eg. more compatible to a standard
32460 * Grid query { data : [ .....] }
32465 * @cfg {String} queryParam (optional)
32466 * Name of the query as it will be passed on the querystring (defaults to 'node')
32467 * eg. the request will be ?node=[id]
32474 * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
32475 * This is called automatically when a node is expanded, but may be used to reload
32476 * a node (or append new children if the {@link #clearOnLoad} option is false.)
32477 * @param {Roo.tree.TreeNode} node
32478 * @param {Function} callback
32480 load : function(node, callback){
32481 if(this.clearOnLoad){
32482 while(node.firstChild){
32483 node.removeChild(node.firstChild);
32486 if(node.attributes.children){ // preloaded json children
32487 var cs = node.attributes.children;
32488 for(var i = 0, len = cs.length; i < len; i++){
32489 node.appendChild(this.createNode(cs[i]));
32491 if(typeof callback == "function"){
32494 }else if(this.dataUrl){
32495 this.requestData(node, callback);
32499 getParams: function(node){
32500 var buf = [], bp = this.baseParams;
32501 for(var key in bp){
32502 if(typeof bp[key] != "function"){
32503 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
32506 var n = this.queryParam === false ? 'node' : this.queryParam;
32507 buf.push(n + "=", encodeURIComponent(node.id));
32508 return buf.join("");
32511 requestData : function(node, callback){
32512 if(this.fireEvent("beforeload", this, node, callback) !== false){
32513 this.transId = Roo.Ajax.request({
32514 method:this.requestMethod,
32515 url: this.dataUrl||this.url,
32516 success: this.handleResponse,
32517 failure: this.handleFailure,
32519 argument: {callback: callback, node: node},
32520 params: this.getParams(node)
32523 // if the load is cancelled, make sure we notify
32524 // the node that we are done
32525 if(typeof callback == "function"){
32531 isLoading : function(){
32532 return this.transId ? true : false;
32535 abort : function(){
32536 if(this.isLoading()){
32537 Roo.Ajax.abort(this.transId);
32542 createNode : function(attr){
32543 // apply baseAttrs, nice idea Corey!
32544 if(this.baseAttrs){
32545 Roo.applyIf(attr, this.baseAttrs);
32547 if(this.applyLoader !== false){
32548 attr.loader = this;
32550 // uiProvider = depreciated..
32552 if(typeof(attr.uiProvider) == 'string'){
32553 attr.uiProvider = this.uiProviders[attr.uiProvider] ||
32554 /** eval:var:attr */ eval(attr.uiProvider);
32556 if(typeof(this.uiProviders['default']) != 'undefined') {
32557 attr.uiProvider = this.uiProviders['default'];
32560 this.fireEvent('create', this, attr);
32562 attr.leaf = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
32564 new Roo.tree.TreeNode(attr) :
32565 new Roo.tree.AsyncTreeNode(attr));
32568 processResponse : function(response, node, callback){
32569 var json = response.responseText;
32572 var o = /** eval:var:zzzzzzzzzz */ eval("("+json+")");
32573 if (this.root !== false) {
32577 for(var i = 0, len = o.length; i < len; i++){
32578 var n = this.createNode(o[i]);
32580 node.appendChild(n);
32583 if(typeof callback == "function"){
32584 callback(this, node);
32587 this.handleFailure(response);
32591 handleResponse : function(response){
32592 this.transId = false;
32593 var a = response.argument;
32594 this.processResponse(response, a.node, a.callback);
32595 this.fireEvent("load", this, a.node, response);
32598 handleFailure : function(response){
32599 this.transId = false;
32600 var a = response.argument;
32601 this.fireEvent("loadexception", this, a.node, response);
32602 if(typeof a.callback == "function"){
32603 a.callback(this, a.node);
32608 * Ext JS Library 1.1.1
32609 * Copyright(c) 2006-2007, Ext JS, LLC.
32611 * Originally Released Under LGPL - original licence link has changed is not relivant.
32614 * <script type="text/javascript">
32618 * @class Roo.tree.TreeFilter
32619 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
32620 * @param {TreePanel} tree
32621 * @param {Object} config (optional)
32623 Roo.tree.TreeFilter = function(tree, config){
32625 this.filtered = {};
32626 Roo.apply(this, config);
32629 Roo.tree.TreeFilter.prototype = {
32636 * Filter the data by a specific attribute.
32637 * @param {String/RegExp} value Either string that the attribute value
32638 * should start with or a RegExp to test against the attribute
32639 * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
32640 * @param {TreeNode} startNode (optional) The node to start the filter at.
32642 filter : function(value, attr, startNode){
32643 attr = attr || "text";
32645 if(typeof value == "string"){
32646 var vlen = value.length;
32647 // auto clear empty filter
32648 if(vlen == 0 && this.clearBlank){
32652 value = value.toLowerCase();
32654 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
32656 }else if(value.exec){ // regex?
32658 return value.test(n.attributes[attr]);
32661 throw 'Illegal filter type, must be string or regex';
32663 this.filterBy(f, null, startNode);
32667 * Filter by a function. The passed function will be called with each
32668 * node in the tree (or from the startNode). If the function returns true, the node is kept
32669 * otherwise it is filtered. If a node is filtered, its children are also filtered.
32670 * @param {Function} fn The filter function
32671 * @param {Object} scope (optional) The scope of the function (defaults to the current node)
32673 filterBy : function(fn, scope, startNode){
32674 startNode = startNode || this.tree.root;
32675 if(this.autoClear){
32678 var af = this.filtered, rv = this.reverse;
32679 var f = function(n){
32680 if(n == startNode){
32686 var m = fn.call(scope || n, n);
32694 startNode.cascade(f);
32697 if(typeof id != "function"){
32699 if(n && n.parentNode){
32700 n.parentNode.removeChild(n);
32708 * Clears the current filter. Note: with the "remove" option
32709 * set a filter cannot be cleared.
32711 clear : function(){
32713 var af = this.filtered;
32715 if(typeof id != "function"){
32722 this.filtered = {};
32727 * Ext JS Library 1.1.1
32728 * Copyright(c) 2006-2007, Ext JS, LLC.
32730 * Originally Released Under LGPL - original licence link has changed is not relivant.
32733 * <script type="text/javascript">
32738 * @class Roo.tree.TreeSorter
32739 * Provides sorting of nodes in a TreePanel
32741 * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
32742 * @cfg {String} property The named attribute on the node to sort by (defaults to text)
32743 * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
32744 * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
32745 * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
32746 * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
32748 * @param {TreePanel} tree
32749 * @param {Object} config
32751 Roo.tree.TreeSorter = function(tree, config){
32752 Roo.apply(this, config);
32753 tree.on("beforechildrenrendered", this.doSort, this);
32754 tree.on("append", this.updateSort, this);
32755 tree.on("insert", this.updateSort, this);
32757 var dsc = this.dir && this.dir.toLowerCase() == "desc";
32758 var p = this.property || "text";
32759 var sortType = this.sortType;
32760 var fs = this.folderSort;
32761 var cs = this.caseSensitive === true;
32762 var leafAttr = this.leafAttr || 'leaf';
32764 this.sortFn = function(n1, n2){
32766 if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
32769 if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
32773 var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
32774 var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
32776 return dsc ? +1 : -1;
32778 return dsc ? -1 : +1;
32785 Roo.tree.TreeSorter.prototype = {
32786 doSort : function(node){
32787 node.sort(this.sortFn);
32790 compareNodes : function(n1, n2){
32791 return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
32794 updateSort : function(tree, node){
32795 if(node.childrenRendered){
32796 this.doSort.defer(1, this, [node]);
32801 * Ext JS Library 1.1.1
32802 * Copyright(c) 2006-2007, Ext JS, LLC.
32804 * Originally Released Under LGPL - original licence link has changed is not relivant.
32807 * <script type="text/javascript">
32810 if(Roo.dd.DropZone){
32812 Roo.tree.TreeDropZone = function(tree, config){
32813 this.allowParentInsert = false;
32814 this.allowContainerDrop = false;
32815 this.appendOnly = false;
32816 Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
32818 this.lastInsertClass = "x-tree-no-status";
32819 this.dragOverData = {};
32822 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
32823 ddGroup : "TreeDD",
32825 expandDelay : 1000,
32827 expandNode : function(node){
32828 if(node.hasChildNodes() && !node.isExpanded()){
32829 node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
32833 queueExpand : function(node){
32834 this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
32837 cancelExpand : function(){
32838 if(this.expandProcId){
32839 clearTimeout(this.expandProcId);
32840 this.expandProcId = false;
32844 isValidDropPoint : function(n, pt, dd, e, data){
32845 if(!n || !data){ return false; }
32846 var targetNode = n.node;
32847 var dropNode = data.node;
32848 // default drop rules
32849 if(!(targetNode && targetNode.isTarget && pt)){
32852 if(pt == "append" && targetNode.allowChildren === false){
32855 if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
32858 if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
32861 // reuse the object
32862 var overEvent = this.dragOverData;
32863 overEvent.tree = this.tree;
32864 overEvent.target = targetNode;
32865 overEvent.data = data;
32866 overEvent.point = pt;
32867 overEvent.source = dd;
32868 overEvent.rawEvent = e;
32869 overEvent.dropNode = dropNode;
32870 overEvent.cancel = false;
32871 var result = this.tree.fireEvent("nodedragover", overEvent);
32872 return overEvent.cancel === false && result !== false;
32875 getDropPoint : function(e, n, dd){
32878 return tn.allowChildren !== false ? "append" : false; // always append for root
32880 var dragEl = n.ddel;
32881 var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
32882 var y = Roo.lib.Event.getPageY(e);
32883 var noAppend = tn.allowChildren === false || tn.isLeaf();
32884 if(this.appendOnly || tn.parentNode.allowChildren === false){
32885 return noAppend ? false : "append";
32887 var noBelow = false;
32888 if(!this.allowParentInsert){
32889 noBelow = tn.hasChildNodes() && tn.isExpanded();
32891 var q = (b - t) / (noAppend ? 2 : 3);
32892 if(y >= t && y < (t + q)){
32894 }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
32901 onNodeEnter : function(n, dd, e, data){
32902 this.cancelExpand();
32905 onNodeOver : function(n, dd, e, data){
32906 var pt = this.getDropPoint(e, n, dd);
32909 // auto node expand check
32910 if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
32911 this.queueExpand(node);
32912 }else if(pt != "append"){
32913 this.cancelExpand();
32916 // set the insert point style on the target node
32917 var returnCls = this.dropNotAllowed;
32918 if(this.isValidDropPoint(n, pt, dd, e, data)){
32923 returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
32924 cls = "x-tree-drag-insert-above";
32925 }else if(pt == "below"){
32926 returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
32927 cls = "x-tree-drag-insert-below";
32929 returnCls = "x-tree-drop-ok-append";
32930 cls = "x-tree-drag-append";
32932 if(this.lastInsertClass != cls){
32933 Roo.fly(el).replaceClass(this.lastInsertClass, cls);
32934 this.lastInsertClass = cls;
32941 onNodeOut : function(n, dd, e, data){
32942 this.cancelExpand();
32943 this.removeDropIndicators(n);
32946 onNodeDrop : function(n, dd, e, data){
32947 var point = this.getDropPoint(e, n, dd);
32948 var targetNode = n.node;
32949 targetNode.ui.startDrop();
32950 if(!this.isValidDropPoint(n, point, dd, e, data)){
32951 targetNode.ui.endDrop();
32954 // first try to find the drop node
32955 var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
32958 target: targetNode,
32963 dropNode: dropNode,
32966 var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
32967 if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
32968 targetNode.ui.endDrop();
32971 // allow target changing
32972 targetNode = dropEvent.target;
32973 if(point == "append" && !targetNode.isExpanded()){
32974 targetNode.expand(false, null, function(){
32975 this.completeDrop(dropEvent);
32976 }.createDelegate(this));
32978 this.completeDrop(dropEvent);
32983 completeDrop : function(de){
32984 var ns = de.dropNode, p = de.point, t = de.target;
32985 if(!(ns instanceof Array)){
32989 for(var i = 0, len = ns.length; i < len; i++){
32992 t.parentNode.insertBefore(n, t);
32993 }else if(p == "below"){
32994 t.parentNode.insertBefore(n, t.nextSibling);
33000 if(this.tree.hlDrop){
33004 this.tree.fireEvent("nodedrop", de);
33007 afterNodeMoved : function(dd, data, e, targetNode, dropNode){
33008 if(this.tree.hlDrop){
33009 dropNode.ui.focus();
33010 dropNode.ui.highlight();
33012 this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
33015 getTree : function(){
33019 removeDropIndicators : function(n){
33022 Roo.fly(el).removeClass([
33023 "x-tree-drag-insert-above",
33024 "x-tree-drag-insert-below",
33025 "x-tree-drag-append"]);
33026 this.lastInsertClass = "_noclass";
33030 beforeDragDrop : function(target, e, id){
33031 this.cancelExpand();
33035 afterRepair : function(data){
33036 if(data && Roo.enableFx){
33037 data.node.ui.highlight();
33045 * Ext JS Library 1.1.1
33046 * Copyright(c) 2006-2007, Ext JS, LLC.
33048 * Originally Released Under LGPL - original licence link has changed is not relivant.
33051 * <script type="text/javascript">
33055 if(Roo.dd.DragZone){
33056 Roo.tree.TreeDragZone = function(tree, config){
33057 Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
33061 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
33062 ddGroup : "TreeDD",
33064 onBeforeDrag : function(data, e){
33066 return n && n.draggable && !n.disabled;
33069 onInitDrag : function(e){
33070 var data = this.dragData;
33071 this.tree.getSelectionModel().select(data.node);
33072 this.proxy.update("");
33073 data.node.ui.appendDDGhost(this.proxy.ghost.dom);
33074 this.tree.fireEvent("startdrag", this.tree, data.node, e);
33077 getRepairXY : function(e, data){
33078 return data.node.ui.getDDRepairXY();
33081 onEndDrag : function(data, e){
33082 this.tree.fireEvent("enddrag", this.tree, data.node, e);
33085 onValidDrop : function(dd, e, id){
33086 this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
33090 beforeInvalidDrop : function(e, id){
33091 // this scrolls the original position back into view
33092 var sm = this.tree.getSelectionModel();
33093 sm.clearSelections();
33094 sm.select(this.dragData.node);
33099 * Ext JS Library 1.1.1
33100 * Copyright(c) 2006-2007, Ext JS, LLC.
33102 * Originally Released Under LGPL - original licence link has changed is not relivant.
33105 * <script type="text/javascript">
33108 * @class Roo.tree.TreeEditor
33109 * @extends Roo.Editor
33110 * Provides editor functionality for inline tree node editing. Any valid {@link Roo.form.Field} can be used
33111 * as the editor field.
33113 * @param {TreePanel} tree
33114 * @param {Object} config Either a prebuilt {@link Roo.form.Field} instance or a Field config object
33116 Roo.tree.TreeEditor = function(tree, config){
33117 config = config || {};
33118 var field = config.events ? config : new Roo.form.TextField(config);
33119 Roo.tree.TreeEditor.superclass.constructor.call(this, field);
33123 tree.on('beforeclick', this.beforeNodeClick, this);
33124 tree.getTreeEl().on('mousedown', this.hide, this);
33125 this.on('complete', this.updateNode, this);
33126 this.on('beforestartedit', this.fitToTree, this);
33127 this.on('startedit', this.bindScroll, this, {delay:10});
33128 this.on('specialkey', this.onSpecialKey, this);
33131 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
33133 * @cfg {String} alignment
33134 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
33140 * @cfg {Boolean} hideEl
33141 * True to hide the bound element while the editor is displayed (defaults to false)
33145 * @cfg {String} cls
33146 * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
33148 cls: "x-small-editor x-tree-editor",
33150 * @cfg {Boolean} shim
33151 * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
33157 * @cfg {Number} maxWidth
33158 * The maximum width in pixels of the editor field (defaults to 250). Note that if the maxWidth would exceed
33159 * the containing tree element's size, it will be automatically limited for you to the container width, taking
33160 * scroll and client offsets into account prior to each edit.
33167 fitToTree : function(ed, el){
33168 var td = this.tree.getTreeEl().dom, nd = el.dom;
33169 if(td.scrollLeft > nd.offsetLeft){ // ensure the node left point is visible
33170 td.scrollLeft = nd.offsetLeft;
33174 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
33175 this.setSize(w, '');
33179 triggerEdit : function(node){
33180 this.completeEdit();
33181 this.editNode = node;
33182 this.startEdit(node.ui.textNode, node.text);
33186 bindScroll : function(){
33187 this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
33191 beforeNodeClick : function(node, e){
33192 var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
33193 this.lastClick = new Date();
33194 if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
33196 this.triggerEdit(node);
33202 updateNode : function(ed, value){
33203 this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
33204 this.editNode.setText(value);
33208 onHide : function(){
33209 Roo.tree.TreeEditor.superclass.onHide.call(this);
33211 this.editNode.ui.focus();
33216 onSpecialKey : function(field, e){
33217 var k = e.getKey();
33221 }else if(k == e.ENTER && !e.hasModifier()){
33223 this.completeEdit();
33226 });//<Script type="text/javascript">
33229 * Ext JS Library 1.1.1
33230 * Copyright(c) 2006-2007, Ext JS, LLC.
33232 * Originally Released Under LGPL - original licence link has changed is not relivant.
33235 * <script type="text/javascript">
33239 * Not documented??? - probably should be...
33242 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
33243 //focus: Roo.emptyFn, // prevent odd scrolling behavior
33245 renderElements : function(n, a, targetNode, bulkRender){
33246 //consel.log("renderElements?");
33247 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
33249 var t = n.getOwnerTree();
33250 var tid = Pman.Tab.Document_TypesTree.tree.el.id;
33252 var cols = t.columns;
33253 var bw = t.borderWidth;
33255 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
33256 var cb = typeof a.checked == "boolean";
33257 var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
33258 var colcls = 'x-t-' + tid + '-c0';
33260 '<li class="x-tree-node">',
33263 '<div class="x-tree-node-el ', a.cls,'">',
33265 '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
33268 '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
33269 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon " />',
33270 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
33271 (a.icon ? ' x-tree-node-inline-icon' : ''),
33272 (a.iconCls ? ' '+a.iconCls : ''),
33273 '" unselectable="on" />',
33274 (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' +
33275 (a.checked ? 'checked="checked" />' : ' />')) : ''),
33277 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
33278 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
33279 '<span unselectable="on" qtip="' + tx + '">',
33283 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
33284 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
33287 for(var i = 1, len = cols.length; i < len; i++){
33289 colcls = 'x-t-' + tid + '-c' +i;
33290 tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
33291 buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
33292 '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
33298 '<div class="x-clear"></div></div>',
33299 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
33302 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
33303 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
33304 n.nextSibling.ui.getEl(), buf.join(""));
33306 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
33308 var el = this.wrap.firstChild;
33310 this.elNode = el.firstChild;
33311 this.ranchor = el.childNodes[1];
33312 this.ctNode = this.wrap.childNodes[1];
33313 var cs = el.firstChild.childNodes;
33314 this.indentNode = cs[0];
33315 this.ecNode = cs[1];
33316 this.iconNode = cs[2];
33319 this.checkbox = cs[3];
33322 this.anchor = cs[index];
33324 this.textNode = cs[index].firstChild;
33326 //el.on("click", this.onClick, this);
33327 //el.on("dblclick", this.onDblClick, this);
33330 // console.log(this);
33332 initEvents : function(){
33333 Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
33336 var a = this.ranchor;
33338 var el = Roo.get(a);
33340 if(Roo.isOpera){ // opera render bug ignores the CSS
33341 el.setStyle("text-decoration", "none");
33344 el.on("click", this.onClick, this);
33345 el.on("dblclick", this.onDblClick, this);
33346 el.on("contextmenu", this.onContextMenu, this);
33350 /*onSelectedChange : function(state){
33353 this.addClass("x-tree-selected");
33356 this.removeClass("x-tree-selected");
33359 addClass : function(cls){
33361 Roo.fly(this.elRow).addClass(cls);
33367 removeClass : function(cls){
33369 Roo.fly(this.elRow).removeClass(cls);
33375 });//<Script type="text/javascript">
33379 * Ext JS Library 1.1.1
33380 * Copyright(c) 2006-2007, Ext JS, LLC.
33382 * Originally Released Under LGPL - original licence link has changed is not relivant.
33385 * <script type="text/javascript">
33390 * @class Roo.tree.ColumnTree
33391 * @extends Roo.data.TreePanel
33392 * @cfg {Object} columns Including width, header, renderer, cls, dataIndex
33393 * @cfg {int} borderWidth compined right/left border allowance
33395 * @param {String/HTMLElement/Element} el The container element
33396 * @param {Object} config
33398 Roo.tree.ColumnTree = function(el, config)
33400 Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
33404 * Fire this event on a container when it resizes
33405 * @param {int} w Width
33406 * @param {int} h Height
33410 this.on('resize', this.onResize, this);
33413 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
33417 borderWidth: Roo.isBorderBox ? 0 : 2,
33420 render : function(){
33421 // add the header.....
33423 Roo.tree.ColumnTree.superclass.render.apply(this);
33425 this.el.addClass('x-column-tree');
33427 this.headers = this.el.createChild(
33428 {cls:'x-tree-headers'},this.innerCt.dom);
33430 var cols = this.columns, c;
33431 var totalWidth = 0;
33433 var len = cols.length;
33434 for(var i = 0; i < len; i++){
33436 totalWidth += c.width;
33437 this.headEls.push(this.headers.createChild({
33438 cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
33440 cls:'x-tree-hd-text',
33443 style:'width:'+(c.width-this.borderWidth)+'px;'
33446 this.headers.createChild({cls:'x-clear'});
33447 // prevent floats from wrapping when clipped
33448 this.headers.setWidth(totalWidth);
33449 //this.innerCt.setWidth(totalWidth);
33450 this.innerCt.setStyle({ overflow: 'auto' });
33451 this.onResize(this.width, this.height);
33455 onResize : function(w,h)
33460 this.innerCt.setWidth(this.width);
33461 this.innerCt.setHeight(this.height-20);
33464 var cols = this.columns, c;
33465 var totalWidth = 0;
33467 var len = cols.length;
33468 for(var i = 0; i < len; i++){
33470 if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
33471 // it's the expander..
33472 expEl = this.headEls[i];
33475 totalWidth += c.width;
33479 expEl.setWidth( ((w - totalWidth)-this.borderWidth - 20));
33481 this.headers.setWidth(w-20);
33490 * Ext JS Library 1.1.1
33491 * Copyright(c) 2006-2007, Ext JS, LLC.
33493 * Originally Released Under LGPL - original licence link has changed is not relivant.
33496 * <script type="text/javascript">
33500 * @class Roo.menu.Menu
33501 * @extends Roo.util.Observable
33502 * A menu object. This is the container to which you add all other menu items. Menu can also serve a as a base class
33503 * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
33505 * Creates a new Menu
33506 * @param {Object} config Configuration options
33508 Roo.menu.Menu = function(config){
33509 Roo.apply(this, config);
33510 this.id = this.id || Roo.id();
33513 * @event beforeshow
33514 * Fires before this menu is displayed
33515 * @param {Roo.menu.Menu} this
33519 * @event beforehide
33520 * Fires before this menu is hidden
33521 * @param {Roo.menu.Menu} this
33526 * Fires after this menu is displayed
33527 * @param {Roo.menu.Menu} this
33532 * Fires after this menu is hidden
33533 * @param {Roo.menu.Menu} this
33538 * Fires when this menu is clicked (or when the enter key is pressed while it is active)
33539 * @param {Roo.menu.Menu} this
33540 * @param {Roo.menu.Item} menuItem The menu item that was clicked
33541 * @param {Roo.EventObject} e
33546 * Fires when the mouse is hovering over this menu
33547 * @param {Roo.menu.Menu} this
33548 * @param {Roo.EventObject} e
33549 * @param {Roo.menu.Item} menuItem The menu item that was clicked
33554 * Fires when the mouse exits this menu
33555 * @param {Roo.menu.Menu} this
33556 * @param {Roo.EventObject} e
33557 * @param {Roo.menu.Item} menuItem The menu item that was clicked
33562 * Fires when a menu item contained in this menu is clicked
33563 * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
33564 * @param {Roo.EventObject} e
33568 if (this.registerMenu) {
33569 Roo.menu.MenuMgr.register(this);
33572 var mis = this.items;
33573 this.items = new Roo.util.MixedCollection();
33575 this.add.apply(this, mis);
33579 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
33581 * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
33585 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
33586 * for bottom-right shadow (defaults to "sides")
33590 * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
33591 * this menu (defaults to "tl-tr?")
33593 subMenuAlign : "tl-tr?",
33595 * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
33596 * relative to its element of origin (defaults to "tl-bl?")
33598 defaultAlign : "tl-bl?",
33600 * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
33602 allowOtherMenus : false,
33604 * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
33606 registerMenu : true,
33611 render : function(){
33615 var el = this.el = new Roo.Layer({
33617 shadow:this.shadow,
33619 parentEl: this.parentEl || document.body,
33623 this.keyNav = new Roo.menu.MenuNav(this);
33626 el.addClass("x-menu-plain");
33629 el.addClass(this.cls);
33631 // generic focus element
33632 this.focusEl = el.createChild({
33633 tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
33635 var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
33636 ul.on("click", this.onClick, this);
33637 ul.on("mouseover", this.onMouseOver, this);
33638 ul.on("mouseout", this.onMouseOut, this);
33639 this.items.each(function(item){
33640 var li = document.createElement("li");
33641 li.className = "x-menu-list-item";
33642 ul.dom.appendChild(li);
33643 item.render(li, this);
33650 autoWidth : function(){
33651 var el = this.el, ul = this.ul;
33655 var w = this.width;
33658 }else if(Roo.isIE){
33659 el.setWidth(this.minWidth);
33660 var t = el.dom.offsetWidth; // force recalc
33661 el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
33666 delayAutoWidth : function(){
33669 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
33671 this.awTask.delay(20);
33676 findTargetItem : function(e){
33677 var t = e.getTarget(".x-menu-list-item", this.ul, true);
33678 if(t && t.menuItemId){
33679 return this.items.get(t.menuItemId);
33684 onClick : function(e){
33686 if(t = this.findTargetItem(e)){
33688 this.fireEvent("click", this, t, e);
33693 setActiveItem : function(item, autoExpand){
33694 if(item != this.activeItem){
33695 if(this.activeItem){
33696 this.activeItem.deactivate();
33698 this.activeItem = item;
33699 item.activate(autoExpand);
33700 }else if(autoExpand){
33706 tryActivate : function(start, step){
33707 var items = this.items;
33708 for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
33709 var item = items.get(i);
33710 if(!item.disabled && item.canActivate){
33711 this.setActiveItem(item, false);
33719 onMouseOver : function(e){
33721 if(t = this.findTargetItem(e)){
33722 if(t.canActivate && !t.disabled){
33723 this.setActiveItem(t, true);
33726 this.fireEvent("mouseover", this, e, t);
33730 onMouseOut : function(e){
33732 if(t = this.findTargetItem(e)){
33733 if(t == this.activeItem && t.shouldDeactivate(e)){
33734 this.activeItem.deactivate();
33735 delete this.activeItem;
33738 this.fireEvent("mouseout", this, e, t);
33742 * Read-only. Returns true if the menu is currently displayed, else false.
33745 isVisible : function(){
33746 return this.el && !this.hidden;
33750 * Displays this menu relative to another element
33751 * @param {String/HTMLElement/Roo.Element} element The element to align to
33752 * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
33753 * the element (defaults to this.defaultAlign)
33754 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
33756 show : function(el, pos, parentMenu){
33757 this.parentMenu = parentMenu;
33761 this.fireEvent("beforeshow", this);
33762 this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
33766 * Displays this menu at a specific xy position
33767 * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
33768 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
33770 showAt : function(xy, parentMenu, /* private: */_e){
33771 this.parentMenu = parentMenu;
33776 this.fireEvent("beforeshow", this);
33777 xy = this.el.adjustForConstraints(xy);
33781 this.hidden = false;
33783 this.fireEvent("show", this);
33786 focus : function(){
33788 this.doFocus.defer(50, this);
33792 doFocus : function(){
33794 this.focusEl.focus();
33799 * Hides this menu and optionally all parent menus
33800 * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
33802 hide : function(deep){
33803 if(this.el && this.isVisible()){
33804 this.fireEvent("beforehide", this);
33805 if(this.activeItem){
33806 this.activeItem.deactivate();
33807 this.activeItem = null;
33810 this.hidden = true;
33811 this.fireEvent("hide", this);
33813 if(deep === true && this.parentMenu){
33814 this.parentMenu.hide(true);
33819 * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
33820 * Any of the following are valid:
33822 * <li>Any menu item object based on {@link Roo.menu.Item}</li>
33823 * <li>An HTMLElement object which will be converted to a menu item</li>
33824 * <li>A menu item config object that will be created as a new menu item</li>
33825 * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
33826 * it will be converted into a {@link Roo.menu.TextItem} and added</li>
33831 var menu = new Roo.menu.Menu();
33833 // Create a menu item to add by reference
33834 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
33836 // Add a bunch of items at once using different methods.
33837 // Only the last item added will be returned.
33838 var item = menu.add(
33839 menuItem, // add existing item by ref
33840 'Dynamic Item', // new TextItem
33841 '-', // new separator
33842 { text: 'Config Item' } // new item by config
33845 * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
33846 * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
33849 var a = arguments, l = a.length, item;
33850 for(var i = 0; i < l; i++){
33852 if(el.render){ // some kind of Item
33853 item = this.addItem(el);
33854 }else if(typeof el == "string"){ // string
33855 if(el == "separator" || el == "-"){
33856 item = this.addSeparator();
33858 item = this.addText(el);
33860 }else if(el.tagName || el.el){ // element
33861 item = this.addElement(el);
33862 }else if(typeof el == "object"){ // must be menu item config?
33863 item = this.addMenuItem(el);
33870 * Returns this menu's underlying {@link Roo.Element} object
33871 * @return {Roo.Element} The element
33873 getEl : function(){
33881 * Adds a separator bar to the menu
33882 * @return {Roo.menu.Item} The menu item that was added
33884 addSeparator : function(){
33885 return this.addItem(new Roo.menu.Separator());
33889 * Adds an {@link Roo.Element} object to the menu
33890 * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
33891 * @return {Roo.menu.Item} The menu item that was added
33893 addElement : function(el){
33894 return this.addItem(new Roo.menu.BaseItem(el));
33898 * Adds an existing object based on {@link Roo.menu.Item} to the menu
33899 * @param {Roo.menu.Item} item The menu item to add
33900 * @return {Roo.menu.Item} The menu item that was added
33902 addItem : function(item){
33903 this.items.add(item);
33905 var li = document.createElement("li");
33906 li.className = "x-menu-list-item";
33907 this.ul.dom.appendChild(li);
33908 item.render(li, this);
33909 this.delayAutoWidth();
33915 * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
33916 * @param {Object} config A MenuItem config object
33917 * @return {Roo.menu.Item} The menu item that was added
33919 addMenuItem : function(config){
33920 if(!(config instanceof Roo.menu.Item)){
33921 if(typeof config.checked == "boolean"){ // must be check menu item config?
33922 config = new Roo.menu.CheckItem(config);
33924 config = new Roo.menu.Item(config);
33927 return this.addItem(config);
33931 * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
33932 * @param {String} text The text to display in the menu item
33933 * @return {Roo.menu.Item} The menu item that was added
33935 addText : function(text){
33936 return this.addItem(new Roo.menu.TextItem(text));
33940 * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
33941 * @param {Number} index The index in the menu's list of current items where the new item should be inserted
33942 * @param {Roo.menu.Item} item The menu item to add
33943 * @return {Roo.menu.Item} The menu item that was added
33945 insert : function(index, item){
33946 this.items.insert(index, item);
33948 var li = document.createElement("li");
33949 li.className = "x-menu-list-item";
33950 this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
33951 item.render(li, this);
33952 this.delayAutoWidth();
33958 * Removes an {@link Roo.menu.Item} from the menu and destroys the object
33959 * @param {Roo.menu.Item} item The menu item to remove
33961 remove : function(item){
33962 this.items.removeKey(item.id);
33967 * Removes and destroys all items in the menu
33969 removeAll : function(){
33971 while(f = this.items.first()){
33977 // MenuNav is a private utility class used internally by the Menu
33978 Roo.menu.MenuNav = function(menu){
33979 Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
33980 this.scope = this.menu = menu;
33983 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
33984 doRelay : function(e, h){
33985 var k = e.getKey();
33986 if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
33987 this.menu.tryActivate(0, 1);
33990 return h.call(this.scope || this, e, this.menu);
33993 up : function(e, m){
33994 if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
33995 m.tryActivate(m.items.length-1, -1);
33999 down : function(e, m){
34000 if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
34001 m.tryActivate(0, 1);
34005 right : function(e, m){
34007 m.activeItem.expandMenu(true);
34011 left : function(e, m){
34013 if(m.parentMenu && m.parentMenu.activeItem){
34014 m.parentMenu.activeItem.activate();
34018 enter : function(e, m){
34020 e.stopPropagation();
34021 m.activeItem.onClick(e);
34022 m.fireEvent("click", this, m.activeItem);
34028 * Ext JS Library 1.1.1
34029 * Copyright(c) 2006-2007, Ext JS, LLC.
34031 * Originally Released Under LGPL - original licence link has changed is not relivant.
34034 * <script type="text/javascript">
34038 * @class Roo.menu.MenuMgr
34039 * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
34042 Roo.menu.MenuMgr = function(){
34043 var menus, active, groups = {}, attached = false, lastShow = new Date();
34045 // private - called when first menu is created
34048 active = new Roo.util.MixedCollection();
34049 Roo.get(document).addKeyListener(27, function(){
34050 if(active.length > 0){
34057 function hideAll(){
34058 if(active && active.length > 0){
34059 var c = active.clone();
34060 c.each(function(m){
34067 function onHide(m){
34069 if(active.length < 1){
34070 Roo.get(document).un("mousedown", onMouseDown);
34076 function onShow(m){
34077 var last = active.last();
34078 lastShow = new Date();
34081 Roo.get(document).on("mousedown", onMouseDown);
34085 m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
34086 m.parentMenu.activeChild = m;
34087 }else if(last && last.isVisible()){
34088 m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
34093 function onBeforeHide(m){
34095 m.activeChild.hide();
34097 if(m.autoHideTimer){
34098 clearTimeout(m.autoHideTimer);
34099 delete m.autoHideTimer;
34104 function onBeforeShow(m){
34105 var pm = m.parentMenu;
34106 if(!pm && !m.allowOtherMenus){
34108 }else if(pm && pm.activeChild && active != m){
34109 pm.activeChild.hide();
34114 function onMouseDown(e){
34115 if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
34121 function onBeforeCheck(mi, state){
34123 var g = groups[mi.group];
34124 for(var i = 0, l = g.length; i < l; i++){
34126 g[i].setChecked(false);
34135 * Hides all menus that are currently visible
34137 hideAll : function(){
34142 register : function(menu){
34146 menus[menu.id] = menu;
34147 menu.on("beforehide", onBeforeHide);
34148 menu.on("hide", onHide);
34149 menu.on("beforeshow", onBeforeShow);
34150 menu.on("show", onShow);
34151 var g = menu.group;
34152 if(g && menu.events["checkchange"]){
34156 groups[g].push(menu);
34157 menu.on("checkchange", onCheck);
34162 * Returns a {@link Roo.menu.Menu} object
34163 * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
34164 * be used to generate and return a new Menu instance.
34166 get : function(menu){
34167 if(typeof menu == "string"){ // menu id
34168 return menus[menu];
34169 }else if(menu.events){ // menu instance
34171 }else if(typeof menu.length == 'number'){ // array of menu items?
34172 return new Roo.menu.Menu({items:menu});
34173 }else{ // otherwise, must be a config
34174 return new Roo.menu.Menu(menu);
34179 unregister : function(menu){
34180 delete menus[menu.id];
34181 menu.un("beforehide", onBeforeHide);
34182 menu.un("hide", onHide);
34183 menu.un("beforeshow", onBeforeShow);
34184 menu.un("show", onShow);
34185 var g = menu.group;
34186 if(g && menu.events["checkchange"]){
34187 groups[g].remove(menu);
34188 menu.un("checkchange", onCheck);
34193 registerCheckable : function(menuItem){
34194 var g = menuItem.group;
34199 groups[g].push(menuItem);
34200 menuItem.on("beforecheckchange", onBeforeCheck);
34205 unregisterCheckable : function(menuItem){
34206 var g = menuItem.group;
34208 groups[g].remove(menuItem);
34209 menuItem.un("beforecheckchange", onBeforeCheck);
34215 * Ext JS Library 1.1.1
34216 * Copyright(c) 2006-2007, Ext JS, LLC.
34218 * Originally Released Under LGPL - original licence link has changed is not relivant.
34221 * <script type="text/javascript">
34226 * @class Roo.menu.BaseItem
34227 * @extends Roo.Component
34228 * The base class for all items that render into menus. BaseItem provides default rendering, activated state
34229 * management and base configuration options shared by all menu components.
34231 * Creates a new BaseItem
34232 * @param {Object} config Configuration options
34234 Roo.menu.BaseItem = function(config){
34235 Roo.menu.BaseItem.superclass.constructor.call(this, config);
34240 * Fires when this item is clicked
34241 * @param {Roo.menu.BaseItem} this
34242 * @param {Roo.EventObject} e
34247 * Fires when this item is activated
34248 * @param {Roo.menu.BaseItem} this
34252 * @event deactivate
34253 * Fires when this item is deactivated
34254 * @param {Roo.menu.BaseItem} this
34260 this.on("click", this.handler, this.scope, true);
34264 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
34266 * @cfg {Function} handler
34267 * A function that will handle the click event of this menu item (defaults to undefined)
34270 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
34272 canActivate : false,
34274 * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
34276 activeClass : "x-menu-item-active",
34278 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
34280 hideOnClick : true,
34282 * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
34287 ctype: "Roo.menu.BaseItem",
34290 actionMode : "container",
34293 render : function(container, parentMenu){
34294 this.parentMenu = parentMenu;
34295 Roo.menu.BaseItem.superclass.render.call(this, container);
34296 this.container.menuItemId = this.id;
34300 onRender : function(container, position){
34301 this.el = Roo.get(this.el);
34302 container.dom.appendChild(this.el.dom);
34306 onClick : function(e){
34307 if(!this.disabled && this.fireEvent("click", this, e) !== false
34308 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
34309 this.handleClick(e);
34316 activate : function(){
34320 var li = this.container;
34321 li.addClass(this.activeClass);
34322 this.region = li.getRegion().adjust(2, 2, -2, -2);
34323 this.fireEvent("activate", this);
34328 deactivate : function(){
34329 this.container.removeClass(this.activeClass);
34330 this.fireEvent("deactivate", this);
34334 shouldDeactivate : function(e){
34335 return !this.region || !this.region.contains(e.getPoint());
34339 handleClick : function(e){
34340 if(this.hideOnClick){
34341 this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
34346 expandMenu : function(autoActivate){
34351 hideMenu : function(){
34356 * Ext JS Library 1.1.1
34357 * Copyright(c) 2006-2007, Ext JS, LLC.
34359 * Originally Released Under LGPL - original licence link has changed is not relivant.
34362 * <script type="text/javascript">
34366 * @class Roo.menu.Adapter
34367 * @extends Roo.menu.BaseItem
34368 * A base utility class that adapts a non-menu component so that it can be wrapped by a menu item and added to a menu.
34369 * It provides basic rendering, activation management and enable/disable logic required to work in menus.
34371 * Creates a new Adapter
34372 * @param {Object} config Configuration options
34374 Roo.menu.Adapter = function(component, config){
34375 Roo.menu.Adapter.superclass.constructor.call(this, config);
34376 this.component = component;
34378 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
34380 canActivate : true,
34383 onRender : function(container, position){
34384 this.component.render(container);
34385 this.el = this.component.getEl();
34389 activate : function(){
34393 this.component.focus();
34394 this.fireEvent("activate", this);
34399 deactivate : function(){
34400 this.fireEvent("deactivate", this);
34404 disable : function(){
34405 this.component.disable();
34406 Roo.menu.Adapter.superclass.disable.call(this);
34410 enable : function(){
34411 this.component.enable();
34412 Roo.menu.Adapter.superclass.enable.call(this);
34416 * Ext JS Library 1.1.1
34417 * Copyright(c) 2006-2007, Ext JS, LLC.
34419 * Originally Released Under LGPL - original licence link has changed is not relivant.
34422 * <script type="text/javascript">
34426 * @class Roo.menu.TextItem
34427 * @extends Roo.menu.BaseItem
34428 * Adds a static text string to a menu, usually used as either a heading or group separator.
34430 * Creates a new TextItem
34431 * @param {String} text The text to display
34433 Roo.menu.TextItem = function(text){
34435 Roo.menu.TextItem.superclass.constructor.call(this);
34438 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
34440 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
34442 hideOnClick : false,
34444 * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
34446 itemCls : "x-menu-text",
34449 onRender : function(){
34450 var s = document.createElement("span");
34451 s.className = this.itemCls;
34452 s.innerHTML = this.text;
34454 Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
34458 * Ext JS Library 1.1.1
34459 * Copyright(c) 2006-2007, Ext JS, LLC.
34461 * Originally Released Under LGPL - original licence link has changed is not relivant.
34464 * <script type="text/javascript">
34468 * @class Roo.menu.Separator
34469 * @extends Roo.menu.BaseItem
34470 * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
34471 * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
34473 * @param {Object} config Configuration options
34475 Roo.menu.Separator = function(config){
34476 Roo.menu.Separator.superclass.constructor.call(this, config);
34479 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
34481 * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
34483 itemCls : "x-menu-sep",
34485 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
34487 hideOnClick : false,
34490 onRender : function(li){
34491 var s = document.createElement("span");
34492 s.className = this.itemCls;
34493 s.innerHTML = " ";
34495 li.addClass("x-menu-sep-li");
34496 Roo.menu.Separator.superclass.onRender.apply(this, arguments);
34500 * Ext JS Library 1.1.1
34501 * Copyright(c) 2006-2007, Ext JS, LLC.
34503 * Originally Released Under LGPL - original licence link has changed is not relivant.
34506 * <script type="text/javascript">
34509 * @class Roo.menu.Item
34510 * @extends Roo.menu.BaseItem
34511 * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
34512 * display items. Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
34513 * activation and click handling.
34515 * Creates a new Item
34516 * @param {Object} config Configuration options
34518 Roo.menu.Item = function(config){
34519 Roo.menu.Item.superclass.constructor.call(this, config);
34521 this.menu = Roo.menu.MenuMgr.get(this.menu);
34524 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
34526 * @cfg {String} icon
34527 * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
34530 * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
34532 itemCls : "x-menu-item",
34534 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
34536 canActivate : true,
34538 * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
34541 // doc'd in BaseItem
34545 ctype: "Roo.menu.Item",
34548 onRender : function(container, position){
34549 var el = document.createElement("a");
34550 el.hideFocus = true;
34551 el.unselectable = "on";
34552 el.href = this.href || "#";
34553 if(this.hrefTarget){
34554 el.target = this.hrefTarget;
34556 el.className = this.itemCls + (this.menu ? " x-menu-item-arrow" : "") + (this.cls ? " " + this.cls : "");
34557 el.innerHTML = String.format(
34558 '<img src="{0}" class="x-menu-item-icon {2}" />{1}',
34559 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || '');
34561 Roo.menu.Item.superclass.onRender.call(this, container, position);
34565 * Sets the text to display in this menu item
34566 * @param {String} text The text to display
34568 setText : function(text){
34571 this.el.update(String.format(
34572 '<img src="{0}" class="x-menu-item-icon {2}">{1}',
34573 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
34574 this.parentMenu.autoWidth();
34579 handleClick : function(e){
34580 if(!this.href){ // if no link defined, stop the event automatically
34583 Roo.menu.Item.superclass.handleClick.apply(this, arguments);
34587 activate : function(autoExpand){
34588 if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
34598 shouldDeactivate : function(e){
34599 if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
34600 if(this.menu && this.menu.isVisible()){
34601 return !this.menu.getEl().getRegion().contains(e.getPoint());
34609 deactivate : function(){
34610 Roo.menu.Item.superclass.deactivate.apply(this, arguments);
34615 expandMenu : function(autoActivate){
34616 if(!this.disabled && this.menu){
34617 clearTimeout(this.hideTimer);
34618 delete this.hideTimer;
34619 if(!this.menu.isVisible() && !this.showTimer){
34620 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
34621 }else if (this.menu.isVisible() && autoActivate){
34622 this.menu.tryActivate(0, 1);
34628 deferExpand : function(autoActivate){
34629 delete this.showTimer;
34630 this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
34632 this.menu.tryActivate(0, 1);
34637 hideMenu : function(){
34638 clearTimeout(this.showTimer);
34639 delete this.showTimer;
34640 if(!this.hideTimer && this.menu && this.menu.isVisible()){
34641 this.hideTimer = this.deferHide.defer(this.hideDelay, this);
34646 deferHide : function(){
34647 delete this.hideTimer;
34652 * Ext JS Library 1.1.1
34653 * Copyright(c) 2006-2007, Ext JS, LLC.
34655 * Originally Released Under LGPL - original licence link has changed is not relivant.
34658 * <script type="text/javascript">
34662 * @class Roo.menu.CheckItem
34663 * @extends Roo.menu.Item
34664 * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
34666 * Creates a new CheckItem
34667 * @param {Object} config Configuration options
34669 Roo.menu.CheckItem = function(config){
34670 Roo.menu.CheckItem.superclass.constructor.call(this, config);
34673 * @event beforecheckchange
34674 * Fires before the checked value is set, providing an opportunity to cancel if needed
34675 * @param {Roo.menu.CheckItem} this
34676 * @param {Boolean} checked The new checked value that will be set
34678 "beforecheckchange" : true,
34680 * @event checkchange
34681 * Fires after the checked value has been set
34682 * @param {Roo.menu.CheckItem} this
34683 * @param {Boolean} checked The checked value that was set
34685 "checkchange" : true
34687 if(this.checkHandler){
34688 this.on('checkchange', this.checkHandler, this.scope);
34691 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
34693 * @cfg {String} group
34694 * All check items with the same group name will automatically be grouped into a single-select
34695 * radio button group (defaults to '')
34698 * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
34700 itemCls : "x-menu-item x-menu-check-item",
34702 * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
34704 groupClass : "x-menu-group-item",
34707 * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false). Note that
34708 * if this checkbox is part of a radio group (group = true) only the last item in the group that is
34709 * initialized with checked = true will be rendered as checked.
34714 ctype: "Roo.menu.CheckItem",
34717 onRender : function(c){
34718 Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
34720 this.el.addClass(this.groupClass);
34722 Roo.menu.MenuMgr.registerCheckable(this);
34724 this.checked = false;
34725 this.setChecked(true, true);
34730 destroy : function(){
34732 Roo.menu.MenuMgr.unregisterCheckable(this);
34734 Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
34738 * Set the checked state of this item
34739 * @param {Boolean} checked The new checked value
34740 * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
34742 setChecked : function(state, suppressEvent){
34743 if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
34744 if(this.container){
34745 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
34747 this.checked = state;
34748 if(suppressEvent !== true){
34749 this.fireEvent("checkchange", this, state);
34755 handleClick : function(e){
34756 if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
34757 this.setChecked(!this.checked);
34759 Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
34763 * Ext JS Library 1.1.1
34764 * Copyright(c) 2006-2007, Ext JS, LLC.
34766 * Originally Released Under LGPL - original licence link has changed is not relivant.
34769 * <script type="text/javascript">
34773 * @class Roo.menu.DateItem
34774 * @extends Roo.menu.Adapter
34775 * A menu item that wraps the {@link Roo.DatPicker} component.
34777 * Creates a new DateItem
34778 * @param {Object} config Configuration options
34780 Roo.menu.DateItem = function(config){
34781 Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
34782 /** The Roo.DatePicker object @type Roo.DatePicker */
34783 this.picker = this.component;
34784 this.addEvents({select: true});
34786 this.picker.on("render", function(picker){
34787 picker.getEl().swallowEvent("click");
34788 picker.container.addClass("x-menu-date-item");
34791 this.picker.on("select", this.onSelect, this);
34794 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
34796 onSelect : function(picker, date){
34797 this.fireEvent("select", this, date, picker);
34798 Roo.menu.DateItem.superclass.handleClick.call(this);
34802 * Ext JS Library 1.1.1
34803 * Copyright(c) 2006-2007, Ext JS, LLC.
34805 * Originally Released Under LGPL - original licence link has changed is not relivant.
34808 * <script type="text/javascript">
34812 * @class Roo.menu.ColorItem
34813 * @extends Roo.menu.Adapter
34814 * A menu item that wraps the {@link Roo.ColorPalette} component.
34816 * Creates a new ColorItem
34817 * @param {Object} config Configuration options
34819 Roo.menu.ColorItem = function(config){
34820 Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
34821 /** The Roo.ColorPalette object @type Roo.ColorPalette */
34822 this.palette = this.component;
34823 this.relayEvents(this.palette, ["select"]);
34824 if(this.selectHandler){
34825 this.on('select', this.selectHandler, this.scope);
34828 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
34830 * Ext JS Library 1.1.1
34831 * Copyright(c) 2006-2007, Ext JS, LLC.
34833 * Originally Released Under LGPL - original licence link has changed is not relivant.
34836 * <script type="text/javascript">
34841 * @class Roo.menu.DateMenu
34842 * @extends Roo.menu.Menu
34843 * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
34845 * Creates a new DateMenu
34846 * @param {Object} config Configuration options
34848 Roo.menu.DateMenu = function(config){
34849 Roo.menu.DateMenu.superclass.constructor.call(this, config);
34851 var di = new Roo.menu.DateItem(config);
34854 * The {@link Roo.DatePicker} instance for this DateMenu
34857 this.picker = di.picker;
34860 * @param {DatePicker} picker
34861 * @param {Date} date
34863 this.relayEvents(di, ["select"]);
34865 this.on('beforeshow', function(){
34867 this.picker.hideMonthPicker(true);
34871 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
34875 * Ext JS Library 1.1.1
34876 * Copyright(c) 2006-2007, Ext JS, LLC.
34878 * Originally Released Under LGPL - original licence link has changed is not relivant.
34881 * <script type="text/javascript">
34886 * @class Roo.menu.ColorMenu
34887 * @extends Roo.menu.Menu
34888 * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
34890 * Creates a new ColorMenu
34891 * @param {Object} config Configuration options
34893 Roo.menu.ColorMenu = function(config){
34894 Roo.menu.ColorMenu.superclass.constructor.call(this, config);
34896 var ci = new Roo.menu.ColorItem(config);
34899 * The {@link Roo.ColorPalette} instance for this ColorMenu
34900 * @type ColorPalette
34902 this.palette = ci.palette;
34905 * @param {ColorPalette} palette
34906 * @param {String} color
34908 this.relayEvents(ci, ["select"]);
34910 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
34912 * Ext JS Library 1.1.1
34913 * Copyright(c) 2006-2007, Ext JS, LLC.
34915 * Originally Released Under LGPL - original licence link has changed is not relivant.
34918 * <script type="text/javascript">
34922 * @class Roo.form.Field
34923 * @extends Roo.BoxComponent
34924 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
34926 * Creates a new Field
34927 * @param {Object} config Configuration options
34929 Roo.form.Field = function(config){
34930 Roo.form.Field.superclass.constructor.call(this, config);
34933 Roo.extend(Roo.form.Field, Roo.BoxComponent, {
34935 * @cfg {String} fieldLabel Label to use when rendering a form.
34938 * @cfg {String} qtip Mouse over tip
34942 * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
34944 invalidClass : "x-form-invalid",
34946 * @cfg {String} invalidText The error text to use when marking a field invalid and no message is provided (defaults to "The value in this field is invalid")
34948 invalidText : "The value in this field is invalid",
34950 * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
34952 focusClass : "x-form-focus",
34954 * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
34955 automatic validation (defaults to "keyup").
34957 validationEvent : "keyup",
34959 * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
34961 validateOnBlur : true,
34963 * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
34965 validationDelay : 250,
34967 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
34968 * {tag: "input", type: "text", size: "20", autocomplete: "off"})
34970 defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "off"},
34972 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
34974 fieldClass : "x-form-field",
34976 * @cfg {String} msgTarget The location where error text should display. Should be one of the following values (defaults to 'qtip'):
34979 ----------- ----------------------------------------------------------------------
34980 qtip Display a quick tip when the user hovers over the field
34981 title Display a default browser title attribute popup
34982 under Add a block div beneath the field containing the error text
34983 side Add an error icon to the right of the field with a popup on hover
34984 [element id] Add the error text directly to the innerHTML of the specified element
34987 msgTarget : 'qtip',
34989 * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
34994 * @cfg {Boolean} readOnly True to mark the field as readOnly in HTML (defaults to false) -- Note: this only sets the element's readOnly DOM attribute.
34999 * @cfg {Boolean} disabled True to disable the field (defaults to false).
35004 * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
35006 inputType : undefined,
35009 * @cfg {Number} tabIndex The tabIndex for this field. Note this only applies to fields that are rendered, not those which are built via applyTo (defaults to undefined).
35011 tabIndex : undefined,
35014 isFormField : true,
35019 * @property {Roo.Element} fieldEl
35020 * Element Containing the rendered Field (with label etc.)
35023 * @cfg {Mixed} value A value to initialize this field with.
35028 * @cfg {String} name The field's HTML name attribute.
35031 * @cfg {String} cls A CSS class to apply to the field's underlying element.
35035 initComponent : function(){
35036 Roo.form.Field.superclass.initComponent.call(this);
35040 * Fires when this field receives input focus.
35041 * @param {Roo.form.Field} this
35046 * Fires when this field loses input focus.
35047 * @param {Roo.form.Field} this
35051 * @event specialkey
35052 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
35053 * {@link Roo.EventObject#getKey} to determine which key was pressed.
35054 * @param {Roo.form.Field} this
35055 * @param {Roo.EventObject} e The event object
35060 * Fires just before the field blurs if the field value has changed.
35061 * @param {Roo.form.Field} this
35062 * @param {Mixed} newValue The new value
35063 * @param {Mixed} oldValue The original value
35068 * Fires after the field has been marked as invalid.
35069 * @param {Roo.form.Field} this
35070 * @param {String} msg The validation message
35075 * Fires after the field has been validated with no errors.
35076 * @param {Roo.form.Field} this
35083 * Returns the name attribute of the field if available
35084 * @return {String} name The field name
35086 getName: function(){
35087 return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
35091 onRender : function(ct, position){
35092 Roo.form.Field.superclass.onRender.call(this, ct, position);
35094 var cfg = this.getAutoCreate();
35096 cfg.name = this.name || this.id;
35098 if(this.inputType){
35099 cfg.type = this.inputType;
35101 this.el = ct.createChild(cfg, position);
35103 var type = this.el.dom.type;
35105 if(type == 'password'){
35108 this.el.addClass('x-form-'+type);
35111 this.el.dom.readOnly = true;
35113 if(this.tabIndex !== undefined){
35114 this.el.dom.setAttribute('tabIndex', this.tabIndex);
35117 this.el.addClass([this.fieldClass, this.cls]);
35122 * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
35123 * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
35124 * @return {Roo.form.Field} this
35126 applyTo : function(target){
35127 this.allowDomMove = false;
35128 this.el = Roo.get(target);
35129 this.render(this.el.dom.parentNode);
35134 initValue : function(){
35135 if(this.value !== undefined){
35136 this.setValue(this.value);
35137 }else if(this.el.dom.value.length > 0){
35138 this.setValue(this.el.dom.value);
35143 * Returns true if this field has been changed since it was originally loaded and is not disabled.
35145 isDirty : function() {
35146 if(this.disabled) {
35149 return String(this.getValue()) !== String(this.originalValue);
35153 afterRender : function(){
35154 Roo.form.Field.superclass.afterRender.call(this);
35159 fireKey : function(e){
35160 if(e.isNavKeyPress()){
35161 this.fireEvent("specialkey", this, e);
35166 * Resets the current field value to the originally loaded value and clears any validation messages
35168 reset : function(){
35169 this.setValue(this.originalValue);
35170 this.clearInvalid();
35174 initEvents : function(){
35175 this.el.on(Roo.isIE ? "keydown" : "keypress", this.fireKey, this);
35176 this.el.on("focus", this.onFocus, this);
35177 this.el.on("blur", this.onBlur, this);
35179 // reference to original value for reset
35180 this.originalValue = this.getValue();
35184 onFocus : function(){
35185 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
35186 this.el.addClass(this.focusClass);
35188 if(!this.hasFocus){
35189 this.hasFocus = true;
35190 this.startValue = this.getValue();
35191 this.fireEvent("focus", this);
35195 beforeBlur : Roo.emptyFn,
35198 onBlur : function(){
35200 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
35201 this.el.removeClass(this.focusClass);
35203 this.hasFocus = false;
35204 if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
35207 var v = this.getValue();
35208 if(String(v) !== String(this.startValue)){
35209 this.fireEvent('change', this, v, this.startValue);
35211 this.fireEvent("blur", this);
35215 * Returns whether or not the field value is currently valid
35216 * @param {Boolean} preventMark True to disable marking the field invalid
35217 * @return {Boolean} True if the value is valid, else false
35219 isValid : function(preventMark){
35223 var restore = this.preventMark;
35224 this.preventMark = preventMark === true;
35225 var v = this.validateValue(this.processValue(this.getRawValue()));
35226 this.preventMark = restore;
35231 * Validates the field value
35232 * @return {Boolean} True if the value is valid, else false
35234 validate : function(){
35235 if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
35236 this.clearInvalid();
35242 processValue : function(value){
35247 // Subclasses should provide the validation implementation by overriding this
35248 validateValue : function(value){
35253 * Mark this field as invalid
35254 * @param {String} msg The validation message
35256 markInvalid : function(msg){
35257 if(!this.rendered || this.preventMark){ // not rendered
35260 this.el.addClass(this.invalidClass);
35261 msg = msg || this.invalidText;
35262 switch(this.msgTarget){
35264 this.el.dom.qtip = msg;
35265 this.el.dom.qclass = 'x-form-invalid-tip';
35266 if(Roo.QuickTips){ // fix for floating editors interacting with DND
35267 Roo.QuickTips.enable();
35271 this.el.dom.title = msg;
35275 var elp = this.el.findParent('.x-form-element', 5, true);
35276 this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
35277 this.errorEl.setWidth(elp.getWidth(true)-20);
35279 this.errorEl.update(msg);
35280 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
35283 if(!this.errorIcon){
35284 var elp = this.el.findParent('.x-form-element', 5, true);
35285 this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
35287 this.alignErrorIcon();
35288 this.errorIcon.dom.qtip = msg;
35289 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
35290 this.errorIcon.show();
35291 this.on('resize', this.alignErrorIcon, this);
35294 var t = Roo.getDom(this.msgTarget);
35296 t.style.display = this.msgDisplay;
35299 this.fireEvent('invalid', this, msg);
35303 alignErrorIcon : function(){
35304 this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
35308 * Clear any invalid styles/messages for this field
35310 clearInvalid : function(){
35311 if(!this.rendered || this.preventMark){ // not rendered
35314 this.el.removeClass(this.invalidClass);
35315 switch(this.msgTarget){
35317 this.el.dom.qtip = '';
35320 this.el.dom.title = '';
35324 Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
35328 if(this.errorIcon){
35329 this.errorIcon.dom.qtip = '';
35330 this.errorIcon.hide();
35331 this.un('resize', this.alignErrorIcon, this);
35335 var t = Roo.getDom(this.msgTarget);
35337 t.style.display = 'none';
35340 this.fireEvent('valid', this);
35344 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
35345 * @return {Mixed} value The field value
35347 getRawValue : function(){
35348 var v = this.el.getValue();
35349 if(v === this.emptyText){
35356 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
35357 * @return {Mixed} value The field value
35359 getValue : function(){
35360 var v = this.el.getValue();
35361 if(v === this.emptyText || v === undefined){
35368 * Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
35369 * @param {Mixed} value The value to set
35371 setRawValue : function(v){
35372 return this.el.dom.value = (v === null || v === undefined ? '' : v);
35376 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
35377 * @param {Mixed} value The value to set
35379 setValue : function(v){
35382 this.el.dom.value = (v === null || v === undefined ? '' : v);
35387 adjustSize : function(w, h){
35388 var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
35389 s.width = this.adjustWidth(this.el.dom.tagName, s.width);
35393 adjustWidth : function(tag, w){
35394 tag = tag.toLowerCase();
35395 if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
35396 if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
35397 if(tag == 'input'){
35400 if(tag = 'textarea'){
35403 }else if(Roo.isOpera){
35404 if(tag == 'input'){
35407 if(tag = 'textarea'){
35417 // anything other than normal should be considered experimental
35418 Roo.form.Field.msgFx = {
35420 show: function(msgEl, f){
35421 msgEl.setDisplayed('block');
35424 hide : function(msgEl, f){
35425 msgEl.setDisplayed(false).update('');
35430 show: function(msgEl, f){
35431 msgEl.slideIn('t', {stopFx:true});
35434 hide : function(msgEl, f){
35435 msgEl.slideOut('t', {stopFx:true,useDisplay:true});
35440 show: function(msgEl, f){
35441 msgEl.fixDisplay();
35442 msgEl.alignTo(f.el, 'tl-tr');
35443 msgEl.slideIn('l', {stopFx:true});
35446 hide : function(msgEl, f){
35447 msgEl.slideOut('l', {stopFx:true,useDisplay:true});
35452 * Ext JS Library 1.1.1
35453 * Copyright(c) 2006-2007, Ext JS, LLC.
35455 * Originally Released Under LGPL - original licence link has changed is not relivant.
35458 * <script type="text/javascript">
35463 * @class Roo.form.TextField
35464 * @extends Roo.form.Field
35465 * Basic text field. Can be used as a direct replacement for traditional text inputs, or as the base
35466 * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
35468 * Creates a new TextField
35469 * @param {Object} config Configuration options
35471 Roo.form.TextField = function(config){
35472 Roo.form.TextField.superclass.constructor.call(this, config);
35476 * Fires when the autosize function is triggered. The field may or may not have actually changed size
35477 * according to the default logic, but this event provides a hook for the developer to apply additional
35478 * logic at runtime to resize the field if needed.
35479 * @param {Roo.form.Field} this This text field
35480 * @param {Number} width The new field width
35486 Roo.extend(Roo.form.TextField, Roo.form.Field, {
35488 * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
35492 * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
35496 * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
35500 * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
35504 * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
35508 * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
35510 disableKeyFilter : false,
35512 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
35516 * @cfg {Number} minLength Minimum input field length required (defaults to 0)
35520 * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
35522 maxLength : Number.MAX_VALUE,
35524 * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
35526 minLengthText : "The minimum length for this field is {0}",
35528 * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
35530 maxLengthText : "The maximum length for this field is {0}",
35532 * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
35534 selectOnFocus : false,
35536 * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
35538 blankText : "This field is required",
35540 * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
35541 * If available, this function will be called only after the basic validators all return true, and will be passed the
35542 * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
35546 * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
35547 * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
35548 * current field value. If the test fails, the field will be marked invalid using {@link #regexText}.
35552 * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
35556 * @cfg {String} emptyText The default text to display in an empty field (defaults to null).
35560 * @cfg {String} emptyClass The CSS class to apply to an empty field to style the {@link #emptyText} (defaults to
35561 * 'x-form-empty-field'). This class is automatically added and removed as needed depending on the current field value.
35563 emptyClass : 'x-form-empty-field',
35566 initEvents : function(){
35567 Roo.form.TextField.superclass.initEvents.call(this);
35568 if(this.validationEvent == 'keyup'){
35569 this.validationTask = new Roo.util.DelayedTask(this.validate, this);
35570 this.el.on('keyup', this.filterValidation, this);
35572 else if(this.validationEvent !== false){
35573 this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
35575 if(this.selectOnFocus || this.emptyText){
35576 this.on("focus", this.preFocus, this);
35577 if(this.emptyText){
35578 this.on('blur', this.postBlur, this);
35579 this.applyEmptyText();
35582 if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
35583 this.el.on("keypress", this.filterKeys, this);
35586 this.el.on("keyup", this.onKeyUp, this, {buffer:50});
35587 this.el.on("click", this.autoSize, this);
35591 processValue : function(value){
35592 if(this.stripCharsRe){
35593 var newValue = value.replace(this.stripCharsRe, '');
35594 if(newValue !== value){
35595 this.setRawValue(newValue);
35602 filterValidation : function(e){
35603 if(!e.isNavKeyPress()){
35604 this.validationTask.delay(this.validationDelay);
35609 onKeyUp : function(e){
35610 if(!e.isNavKeyPress()){
35616 * Resets the current field value to the originally-loaded value and clears any validation messages.
35617 * Also adds emptyText and emptyClass if the original value was blank.
35619 reset : function(){
35620 Roo.form.TextField.superclass.reset.call(this);
35621 this.applyEmptyText();
35624 applyEmptyText : function(){
35625 if(this.rendered && this.emptyText && this.getRawValue().length < 1){
35626 this.setRawValue(this.emptyText);
35627 this.el.addClass(this.emptyClass);
35632 preFocus : function(){
35633 if(this.emptyText){
35634 if(this.el.dom.value == this.emptyText){
35635 this.setRawValue('');
35637 this.el.removeClass(this.emptyClass);
35639 if(this.selectOnFocus){
35640 this.el.dom.select();
35645 postBlur : function(){
35646 this.applyEmptyText();
35650 filterKeys : function(e){
35651 var k = e.getKey();
35652 if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
35655 var c = e.getCharCode(), cc = String.fromCharCode(c);
35656 if(Roo.isIE && (e.isSpecialKey() || !cc)){
35659 if(!this.maskRe.test(cc)){
35664 setValue : function(v){
35665 if(this.emptyText && this.el && v !== undefined && v !== null && v !== ''){
35666 this.el.removeClass(this.emptyClass);
35668 Roo.form.TextField.superclass.setValue.apply(this, arguments);
35669 this.applyEmptyText();
35674 * Validates a value according to the field's validation rules and marks the field as invalid
35675 * if the validation fails
35676 * @param {Mixed} value The value to validate
35677 * @return {Boolean} True if the value is valid, else false
35679 validateValue : function(value){
35680 if(value.length < 1 || value === this.emptyText){ // if it's blank
35681 if(this.allowBlank){
35682 this.clearInvalid();
35685 this.markInvalid(this.blankText);
35689 if(value.length < this.minLength){
35690 this.markInvalid(String.format(this.minLengthText, this.minLength));
35693 if(value.length > this.maxLength){
35694 this.markInvalid(String.format(this.maxLengthText, this.maxLength));
35698 var vt = Roo.form.VTypes;
35699 if(!vt[this.vtype](value, this)){
35700 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
35704 if(typeof this.validator == "function"){
35705 var msg = this.validator(value);
35707 this.markInvalid(msg);
35711 if(this.regex && !this.regex.test(value)){
35712 this.markInvalid(this.regexText);
35719 * Selects text in this field
35720 * @param {Number} start (optional) The index where the selection should start (defaults to 0)
35721 * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
35723 selectText : function(start, end){
35724 var v = this.getRawValue();
35726 start = start === undefined ? 0 : start;
35727 end = end === undefined ? v.length : end;
35728 var d = this.el.dom;
35729 if(d.setSelectionRange){
35730 d.setSelectionRange(start, end);
35731 }else if(d.createTextRange){
35732 var range = d.createTextRange();
35733 range.moveStart("character", start);
35734 range.moveEnd("character", v.length-end);
35741 * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
35742 * This only takes effect if grow = true, and fires the autosize event.
35744 autoSize : function(){
35745 if(!this.grow || !this.rendered){
35749 this.metrics = Roo.util.TextMetrics.createInstance(this.el);
35752 var v = el.dom.value;
35753 var d = document.createElement('div');
35754 d.appendChild(document.createTextNode(v));
35758 var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
35759 this.el.setWidth(w);
35760 this.fireEvent("autosize", this, w);
35764 * Ext JS Library 1.1.1
35765 * Copyright(c) 2006-2007, Ext JS, LLC.
35767 * Originally Released Under LGPL - original licence link has changed is not relivant.
35770 * <script type="text/javascript">
35774 * @class Roo.form.Hidden
35775 * @extends Roo.form.TextField
35776 * Simple Hidden element used on forms
35778 * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
35781 * Creates a new Hidden form element.
35782 * @param {Object} config Configuration options
35787 // easy hidden field...
35788 Roo.form.Hidden = function(config){
35789 Roo.form.Hidden.superclass.constructor.call(this, config);
35792 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
35794 inputType: 'hidden',
35797 labelSeparator: '',
35799 itemCls : 'x-form-item-display-none'
35807 * Ext JS Library 1.1.1
35808 * Copyright(c) 2006-2007, Ext JS, LLC.
35810 * Originally Released Under LGPL - original licence link has changed is not relivant.
35813 * <script type="text/javascript">
35817 * @class Roo.form.TriggerField
35818 * @extends Roo.form.TextField
35819 * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
35820 * The trigger has no default action, so you must assign a function to implement the trigger click handler by
35821 * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
35822 * for which you can provide a custom implementation. For example:
35824 var trigger = new Roo.form.TriggerField();
35825 trigger.onTriggerClick = myTriggerFn;
35826 trigger.applyTo('my-field');
35829 * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
35830 * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
35831 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
35832 * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
35834 * Create a new TriggerField.
35835 * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
35836 * to the base TextField)
35838 Roo.form.TriggerField = function(config){
35839 this.mimicing = false;
35840 Roo.form.TriggerField.superclass.constructor.call(this, config);
35843 Roo.extend(Roo.form.TriggerField, Roo.form.TextField, {
35845 * @cfg {String} triggerClass A CSS class to apply to the trigger
35848 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
35849 * {tag: "input", type: "text", size: "16", autocomplete: "off"})
35851 defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "off"},
35853 * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
35857 /** @cfg {Boolean} grow @hide */
35858 /** @cfg {Number} growMin @hide */
35859 /** @cfg {Number} growMax @hide */
35865 autoSize: Roo.emptyFn,
35869 deferHeight : true,
35872 actionMode : 'wrap',
35874 onResize : function(w, h){
35875 Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
35876 if(typeof w == 'number'){
35877 this.el.setWidth(this.adjustWidth('input', w - this.trigger.getWidth()));
35882 adjustSize : Roo.BoxComponent.prototype.adjustSize,
35885 getResizeEl : function(){
35890 getPositionEl : function(){
35895 alignErrorIcon : function(){
35896 this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
35900 onRender : function(ct, position){
35901 Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
35902 this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
35903 this.trigger = this.wrap.createChild(this.triggerConfig ||
35904 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
35905 if(this.hideTrigger){
35906 this.trigger.setDisplayed(false);
35908 this.initTrigger();
35910 this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
35915 initTrigger : function(){
35916 this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
35917 this.trigger.addClassOnOver('x-form-trigger-over');
35918 this.trigger.addClassOnClick('x-form-trigger-click');
35922 onDestroy : function(){
35924 this.trigger.removeAllListeners();
35925 this.trigger.remove();
35928 this.wrap.remove();
35930 Roo.form.TriggerField.superclass.onDestroy.call(this);
35934 onFocus : function(){
35935 Roo.form.TriggerField.superclass.onFocus.call(this);
35936 if(!this.mimicing){
35937 this.wrap.addClass('x-trigger-wrap-focus');
35938 this.mimicing = true;
35939 Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
35940 if(this.monitorTab){
35941 this.el.on("keydown", this.checkTab, this);
35947 checkTab : function(e){
35948 if(e.getKey() == e.TAB){
35949 this.triggerBlur();
35954 onBlur : function(){
35959 mimicBlur : function(e, t){
35960 if(!this.wrap.contains(t) && this.validateBlur()){
35961 this.triggerBlur();
35966 triggerBlur : function(){
35967 this.mimicing = false;
35968 Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
35969 if(this.monitorTab){
35970 this.el.un("keydown", this.checkTab, this);
35972 this.wrap.removeClass('x-trigger-wrap-focus');
35973 Roo.form.TriggerField.superclass.onBlur.call(this);
35977 // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
35978 validateBlur : function(e, t){
35983 onDisable : function(){
35984 Roo.form.TriggerField.superclass.onDisable.call(this);
35986 this.wrap.addClass('x-item-disabled');
35991 onEnable : function(){
35992 Roo.form.TriggerField.superclass.onEnable.call(this);
35994 this.wrap.removeClass('x-item-disabled');
35999 onShow : function(){
36000 var ae = this.getActionEl();
36003 ae.dom.style.display = '';
36004 ae.dom.style.visibility = 'visible';
36010 onHide : function(){
36011 var ae = this.getActionEl();
36012 ae.dom.style.display = 'none';
36016 * The function that should handle the trigger's click event. This method does nothing by default until overridden
36017 * by an implementing function.
36019 * @param {EventObject} e
36021 onTriggerClick : Roo.emptyFn
36024 // TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class
36025 // to be extended by an implementing class. For an example of implementing this class, see the custom
36026 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
36027 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
36028 initComponent : function(){
36029 Roo.form.TwinTriggerField.superclass.initComponent.call(this);
36031 this.triggerConfig = {
36032 tag:'span', cls:'x-form-twin-triggers', cn:[
36033 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
36034 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
36038 getTrigger : function(index){
36039 return this.triggers[index];
36042 initTrigger : function(){
36043 var ts = this.trigger.select('.x-form-trigger', true);
36044 this.wrap.setStyle('overflow', 'hidden');
36045 var triggerField = this;
36046 ts.each(function(t, all, index){
36047 t.hide = function(){
36048 var w = triggerField.wrap.getWidth();
36049 this.dom.style.display = 'none';
36050 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
36052 t.show = function(){
36053 var w = triggerField.wrap.getWidth();
36054 this.dom.style.display = '';
36055 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
36057 var triggerIndex = 'Trigger'+(index+1);
36059 if(this['hide'+triggerIndex]){
36060 t.dom.style.display = 'none';
36062 t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
36063 t.addClassOnOver('x-form-trigger-over');
36064 t.addClassOnClick('x-form-trigger-click');
36066 this.triggers = ts.elements;
36069 onTrigger1Click : Roo.emptyFn,
36070 onTrigger2Click : Roo.emptyFn
36073 * Ext JS Library 1.1.1
36074 * Copyright(c) 2006-2007, Ext JS, LLC.
36076 * Originally Released Under LGPL - original licence link has changed is not relivant.
36079 * <script type="text/javascript">
36083 * @class Roo.form.TextArea
36084 * @extends Roo.form.TextField
36085 * Multiline text field. Can be used as a direct replacement for traditional textarea fields, plus adds
36086 * support for auto-sizing.
36088 * Creates a new TextArea
36089 * @param {Object} config Configuration options
36091 Roo.form.TextArea = function(config){
36092 Roo.form.TextArea.superclass.constructor.call(this, config);
36093 // these are provided exchanges for backwards compat
36094 // minHeight/maxHeight were replaced by growMin/growMax to be
36095 // compatible with TextField growing config values
36096 if(this.minHeight !== undefined){
36097 this.growMin = this.minHeight;
36099 if(this.maxHeight !== undefined){
36100 this.growMax = this.maxHeight;
36104 Roo.extend(Roo.form.TextArea, Roo.form.TextField, {
36106 * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
36110 * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
36114 * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
36115 * in the field (equivalent to setting overflow: hidden, defaults to false)
36117 preventScrollbars: false,
36119 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
36120 * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
36124 onRender : function(ct, position){
36126 this.defaultAutoCreate = {
36128 style:"width:300px;height:60px;",
36129 autocomplete: "off"
36132 Roo.form.TextArea.superclass.onRender.call(this, ct, position);
36134 this.textSizeEl = Roo.DomHelper.append(document.body, {
36135 tag: "pre", cls: "x-form-grow-sizer"
36137 if(this.preventScrollbars){
36138 this.el.setStyle("overflow", "hidden");
36140 this.el.setHeight(this.growMin);
36144 onDestroy : function(){
36145 if(this.textSizeEl){
36146 this.textSizeEl.parentNode.removeChild(this.textSizeEl);
36148 Roo.form.TextArea.superclass.onDestroy.call(this);
36152 onKeyUp : function(e){
36153 if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
36159 * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
36160 * This only takes effect if grow = true, and fires the autosize event if the height changes.
36162 autoSize : function(){
36163 if(!this.grow || !this.textSizeEl){
36167 var v = el.dom.value;
36168 var ts = this.textSizeEl;
36171 ts.appendChild(document.createTextNode(v));
36174 Roo.fly(ts).setWidth(this.el.getWidth());
36176 v = "  ";
36179 v = v.replace(/\n/g, '<p> </p>');
36181 v += " \n ";
36184 var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
36185 if(h != this.lastHeight){
36186 this.lastHeight = h;
36187 this.el.setHeight(h);
36188 this.fireEvent("autosize", this, h);
36193 * Ext JS Library 1.1.1
36194 * Copyright(c) 2006-2007, Ext JS, LLC.
36196 * Originally Released Under LGPL - original licence link has changed is not relivant.
36199 * <script type="text/javascript">
36204 * @class Roo.form.NumberField
36205 * @extends Roo.form.TextField
36206 * Numeric text field that provides automatic keystroke filtering and numeric validation.
36208 * Creates a new NumberField
36209 * @param {Object} config Configuration options
36211 Roo.form.NumberField = function(config){
36212 Roo.form.NumberField.superclass.constructor.call(this, config);
36215 Roo.extend(Roo.form.NumberField, Roo.form.TextField, {
36217 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
36219 fieldClass: "x-form-field x-form-num-field",
36221 * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
36223 allowDecimals : true,
36225 * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
36227 decimalSeparator : ".",
36229 * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
36231 decimalPrecision : 2,
36233 * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
36235 allowNegative : true,
36237 * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
36239 minValue : Number.NEGATIVE_INFINITY,
36241 * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
36243 maxValue : Number.MAX_VALUE,
36245 * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
36247 minText : "The minimum value for this field is {0}",
36249 * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
36251 maxText : "The maximum value for this field is {0}",
36253 * @cfg {String} nanText Error text to display if the value is not a valid number. For example, this can happen
36254 * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
36256 nanText : "{0} is not a valid number",
36259 initEvents : function(){
36260 Roo.form.NumberField.superclass.initEvents.call(this);
36261 var allowed = "0123456789";
36262 if(this.allowDecimals){
36263 allowed += this.decimalSeparator;
36265 if(this.allowNegative){
36268 this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
36269 var keyPress = function(e){
36270 var k = e.getKey();
36271 if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
36274 var c = e.getCharCode();
36275 if(allowed.indexOf(String.fromCharCode(c)) === -1){
36279 this.el.on("keypress", keyPress, this);
36283 validateValue : function(value){
36284 if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
36287 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
36290 var num = this.parseValue(value);
36292 this.markInvalid(String.format(this.nanText, value));
36295 if(num < this.minValue){
36296 this.markInvalid(String.format(this.minText, this.minValue));
36299 if(num > this.maxValue){
36300 this.markInvalid(String.format(this.maxText, this.maxValue));
36306 getValue : function(){
36307 return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
36311 parseValue : function(value){
36312 value = parseFloat(String(value).replace(this.decimalSeparator, "."));
36313 return isNaN(value) ? '' : value;
36317 fixPrecision : function(value){
36318 var nan = isNaN(value);
36319 if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
36320 return nan ? '' : value;
36322 return parseFloat(value).toFixed(this.decimalPrecision);
36325 setValue : function(v){
36326 Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
36330 decimalPrecisionFcn : function(v){
36331 return Math.floor(v);
36334 beforeBlur : function(){
36335 var v = this.parseValue(this.getRawValue());
36337 this.setValue(this.fixPrecision(v));
36342 * Ext JS Library 1.1.1
36343 * Copyright(c) 2006-2007, Ext JS, LLC.
36345 * Originally Released Under LGPL - original licence link has changed is not relivant.
36348 * <script type="text/javascript">
36352 * @class Roo.form.DateField
36353 * @extends Roo.form.TriggerField
36354 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
36356 * Create a new DateField
36357 * @param {Object} config
36359 Roo.form.DateField = function(config){
36360 Roo.form.DateField.superclass.constructor.call(this, config);
36366 * Fires when a date is selected
36367 * @param {Roo.form.DateField} combo This combo box
36368 * @param {Date} date The date selected
36375 if(typeof this.minValue == "string") this.minValue = this.parseDate(this.minValue);
36376 if(typeof this.maxValue == "string") this.maxValue = this.parseDate(this.maxValue);
36377 this.ddMatch = null;
36378 if(this.disabledDates){
36379 var dd = this.disabledDates;
36381 for(var i = 0; i < dd.length; i++){
36383 if(i != dd.length-1) re += "|";
36385 this.ddMatch = new RegExp(re + ")");
36389 Roo.extend(Roo.form.DateField, Roo.form.TriggerField, {
36391 * @cfg {String} format
36392 * The default date format string which can be overriden for localization support. The format must be
36393 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
36397 * @cfg {String} altFormats
36398 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
36399 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
36401 altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
36403 * @cfg {Array} disabledDays
36404 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
36406 disabledDays : null,
36408 * @cfg {String} disabledDaysText
36409 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
36411 disabledDaysText : "Disabled",
36413 * @cfg {Array} disabledDates
36414 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
36415 * expression so they are very powerful. Some examples:
36417 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
36418 * <li>["03/08", "09/16"] would disable those days for every year</li>
36419 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
36420 * <li>["03/../2006"] would disable every day in March 2006</li>
36421 * <li>["^03"] would disable every day in every March</li>
36423 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
36424 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
36426 disabledDates : null,
36428 * @cfg {String} disabledDatesText
36429 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
36431 disabledDatesText : "Disabled",
36433 * @cfg {Date/String} minValue
36434 * The minimum allowed date. Can be either a Javascript date object or a string date in a
36435 * valid format (defaults to null).
36439 * @cfg {Date/String} maxValue
36440 * The maximum allowed date. Can be either a Javascript date object or a string date in a
36441 * valid format (defaults to null).
36445 * @cfg {String} minText
36446 * The error text to display when the date in the cell is before minValue (defaults to
36447 * 'The date in this field must be after {minValue}').
36449 minText : "The date in this field must be equal to or after {0}",
36451 * @cfg {String} maxText
36452 * The error text to display when the date in the cell is after maxValue (defaults to
36453 * 'The date in this field must be before {maxValue}').
36455 maxText : "The date in this field must be equal to or before {0}",
36457 * @cfg {String} invalidText
36458 * The error text to display when the date in the field is invalid (defaults to
36459 * '{value} is not a valid date - it must be in the format {format}').
36461 invalidText : "{0} is not a valid date - it must be in the format {1}",
36463 * @cfg {String} triggerClass
36464 * An additional CSS class used to style the trigger button. The trigger will always get the
36465 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
36466 * which displays a calendar icon).
36468 triggerClass : 'x-form-date-trigger',
36472 * @cfg {bool} useIso
36473 * if enabled, then the date field will use a hidden field to store the
36474 * real value as iso formated date. default (false)
36478 * @cfg {String/Object} autoCreate
36479 * A DomHelper element spec, or true for a default element spec (defaults to
36480 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
36483 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
36486 hiddenField: false,
36488 onRender : function(ct, position)
36490 Roo.form.DateField.superclass.onRender.call(this, ct, position);
36492 this.el.dom.removeAttribute('name');
36493 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
36495 this.hiddenField.value = this.formatDate(this.value, 'Y-m-d');
36496 // prevent input submission
36497 this.hiddenName = this.name;
36504 validateValue : function(value)
36506 value = this.formatDate(value);
36507 if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
36510 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
36513 var svalue = value;
36514 value = this.parseDate(value);
36516 this.markInvalid(String.format(this.invalidText, svalue, this.format));
36519 var time = value.getTime();
36520 if(this.minValue && time < this.minValue.getTime()){
36521 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
36524 if(this.maxValue && time > this.maxValue.getTime()){
36525 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
36528 if(this.disabledDays){
36529 var day = value.getDay();
36530 for(var i = 0; i < this.disabledDays.length; i++) {
36531 if(day === this.disabledDays[i]){
36532 this.markInvalid(this.disabledDaysText);
36537 var fvalue = this.formatDate(value);
36538 if(this.ddMatch && this.ddMatch.test(fvalue)){
36539 this.markInvalid(String.format(this.disabledDatesText, fvalue));
36546 // Provides logic to override the default TriggerField.validateBlur which just returns true
36547 validateBlur : function(){
36548 return !this.menu || !this.menu.isVisible();
36552 * Returns the current date value of the date field.
36553 * @return {Date} The date value
36555 getValue : function(){
36557 return this.hiddenField ? this.hiddenField.value : this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
36561 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
36562 * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
36563 * (the default format used is "m/d/y").
36566 //All of these calls set the same date value (May 4, 2006)
36568 //Pass a date object:
36569 var dt = new Date('5/4/06');
36570 dateField.setValue(dt);
36572 //Pass a date string (default format):
36573 dateField.setValue('5/4/06');
36575 //Pass a date string (custom format):
36576 dateField.format = 'Y-m-d';
36577 dateField.setValue('2006-5-4');
36579 * @param {String/Date} date The date or valid date string
36581 setValue : function(date){
36582 if (this.hiddenField) {
36583 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
36585 Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
36589 parseDate : function(value){
36590 if(!value || value instanceof Date){
36593 var v = Date.parseDate(value, this.format);
36594 if(!v && this.altFormats){
36595 if(!this.altFormatsArray){
36596 this.altFormatsArray = this.altFormats.split("|");
36598 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
36599 v = Date.parseDate(value, this.altFormatsArray[i]);
36606 formatDate : function(date, fmt){
36607 return (!date || !(date instanceof Date)) ?
36608 date : date.dateFormat(fmt || this.format);
36613 select: function(m, d){
36615 this.fireEvent('select', this, d);
36617 show : function(){ // retain focus styling
36621 this.focus.defer(10, this);
36622 var ml = this.menuListeners;
36623 this.menu.un("select", ml.select, this);
36624 this.menu.un("show", ml.show, this);
36625 this.menu.un("hide", ml.hide, this);
36630 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
36631 onTriggerClick : function(){
36635 if(this.menu == null){
36636 this.menu = new Roo.menu.DateMenu();
36638 Roo.apply(this.menu.picker, {
36639 showClear: this.allowBlank,
36640 minDate : this.minValue,
36641 maxDate : this.maxValue,
36642 disabledDatesRE : this.ddMatch,
36643 disabledDatesText : this.disabledDatesText,
36644 disabledDays : this.disabledDays,
36645 disabledDaysText : this.disabledDaysText,
36646 format : this.format,
36647 minText : String.format(this.minText, this.formatDate(this.minValue)),
36648 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
36650 this.menu.on(Roo.apply({}, this.menuListeners, {
36653 this.menu.picker.setValue(this.getValue() || new Date());
36654 this.menu.show(this.el, "tl-bl?");
36657 beforeBlur : function(){
36658 var v = this.parseDate(this.getRawValue());
36664 /** @cfg {Boolean} grow @hide */
36665 /** @cfg {Number} growMin @hide */
36666 /** @cfg {Number} growMax @hide */
36673 * Ext JS Library 1.1.1
36674 * Copyright(c) 2006-2007, Ext JS, LLC.
36676 * Originally Released Under LGPL - original licence link has changed is not relivant.
36679 * <script type="text/javascript">
36684 * @class Roo.form.ComboBox
36685 * @extends Roo.form.TriggerField
36686 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
36688 * Create a new ComboBox.
36689 * @param {Object} config Configuration options
36691 Roo.form.ComboBox = function(config){
36692 Roo.form.ComboBox.superclass.constructor.call(this, config);
36696 * Fires when the dropdown list is expanded
36697 * @param {Roo.form.ComboBox} combo This combo box
36702 * Fires when the dropdown list is collapsed
36703 * @param {Roo.form.ComboBox} combo This combo box
36707 * @event beforeselect
36708 * Fires before a list item is selected. Return false to cancel the selection.
36709 * @param {Roo.form.ComboBox} combo This combo box
36710 * @param {Roo.data.Record} record The data record returned from the underlying store
36711 * @param {Number} index The index of the selected item in the dropdown list
36713 'beforeselect' : true,
36716 * Fires when a list item is selected
36717 * @param {Roo.form.ComboBox} combo This combo box
36718 * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
36719 * @param {Number} index The index of the selected item in the dropdown list
36723 * @event beforequery
36724 * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
36725 * The event object passed has these properties:
36726 * @param {Roo.form.ComboBox} combo This combo box
36727 * @param {String} query The query
36728 * @param {Boolean} forceAll true to force "all" query
36729 * @param {Boolean} cancel true to cancel the query
36730 * @param {Object} e The query event object
36732 'beforequery': true
36734 if(this.transform){
36735 this.allowDomMove = false;
36736 var s = Roo.getDom(this.transform);
36737 if(!this.hiddenName){
36738 this.hiddenName = s.name;
36741 this.mode = 'local';
36742 var d = [], opts = s.options;
36743 for(var i = 0, len = opts.length;i < len; i++){
36745 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
36747 this.value = value;
36749 d.push([value, o.text]);
36751 this.store = new Roo.data.SimpleStore({
36753 fields: ['value', 'text'],
36756 this.valueField = 'value';
36757 this.displayField = 'text';
36759 s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
36760 if(!this.lazyRender){
36761 this.target = true;
36762 this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
36763 s.parentNode.removeChild(s); // remove it
36764 this.render(this.el.parentNode);
36766 s.parentNode.removeChild(s); // remove it
36771 this.store = Roo.factory(this.store, Roo.data);
36774 this.selectedIndex = -1;
36775 if(this.mode == 'local'){
36776 if(config.queryDelay === undefined){
36777 this.queryDelay = 10;
36779 if(config.minChars === undefined){
36785 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
36787 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
36790 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
36791 * rendering into an Roo.Editor, defaults to false)
36794 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
36795 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
36798 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
36801 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
36802 * the dropdown list (defaults to undefined, with no header element)
36806 * @cfg {String/Roo.Template} tpl The template to use to render the output
36810 defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
36812 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
36814 listWidth: undefined,
36816 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
36817 * mode = 'remote' or 'text' if mode = 'local')
36819 displayField: undefined,
36821 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
36822 * mode = 'remote' or 'value' if mode = 'local').
36823 * Note: use of a valueField requires the user make a selection
36824 * in order for a value to be mapped.
36826 valueField: undefined,
36828 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
36829 * field's data value (defaults to the underlying DOM element's name)
36831 hiddenName: undefined,
36833 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
36837 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
36839 selectedClass: 'x-combo-selected',
36841 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
36842 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
36843 * which displays a downward arrow icon).
36845 triggerClass : 'x-form-arrow-trigger',
36847 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
36851 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
36852 * anchor positions (defaults to 'tl-bl')
36854 listAlign: 'tl-bl?',
36856 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
36860 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
36861 * query specified by the allQuery config option (defaults to 'query')
36863 triggerAction: 'query',
36865 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
36866 * (defaults to 4, does not apply if editable = false)
36870 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
36871 * delay (typeAheadDelay) if it matches a known value (defaults to false)
36875 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
36876 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
36880 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
36881 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
36885 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
36886 * when editable = true (defaults to false)
36888 selectOnFocus:false,
36890 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
36892 queryParam: 'query',
36894 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
36895 * when mode = 'remote' (defaults to 'Loading...')
36897 loadingText: 'Loading...',
36899 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
36903 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
36907 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
36908 * traditional select (defaults to true)
36912 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
36916 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
36920 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
36921 * listWidth has a higher value)
36925 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
36926 * allow the user to set arbitrary text into the field (defaults to false)
36928 forceSelection:false,
36930 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
36931 * if typeAhead = true (defaults to 250)
36933 typeAheadDelay : 250,
36935 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
36936 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
36938 valueNotFoundText : undefined,
36940 * @cfg {bool} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
36942 blockFocus : false,
36945 * @cfg {bool} disableClear Disable showing of clear button.
36947 disableClear : false,
36950 onRender : function(ct, position){
36951 Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
36952 if(this.hiddenName){
36953 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
36955 this.hiddenField.value =
36956 this.hiddenValue !== undefined ? this.hiddenValue :
36957 this.value !== undefined ? this.value : '';
36959 // prevent input submission
36960 this.el.dom.removeAttribute('name');
36963 this.el.dom.setAttribute('autocomplete', 'off');
36966 var cls = 'x-combo-list';
36968 this.list = new Roo.Layer({
36969 shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
36972 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
36973 this.list.setWidth(lw);
36974 this.list.swallowEvent('mousewheel');
36975 this.assetHeight = 0;
36978 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
36979 this.assetHeight += this.header.getHeight();
36982 this.innerList = this.list.createChild({cls:cls+'-inner'});
36983 this.innerList.on('mouseover', this.onViewOver, this);
36984 this.innerList.on('mousemove', this.onViewMove, this);
36985 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
36987 if(this.allowBlank && !this.pageSize && !this.disableClear){
36988 this.footer = this.list.createChild({cls:cls+'-ft'});
36989 this.pageTb = new Roo.Toolbar(this.footer);
36993 this.footer = this.list.createChild({cls:cls+'-ft'});
36994 this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
36995 {pageSize: this.pageSize});
36999 if (this.pageTb && this.allowBlank && !this.disableClear) {
37001 this.pageTb.add(new Roo.Toolbar.Fill(), {
37002 cls: 'x-btn-icon x-btn-clear',
37004 handler: function()
37007 _this.clearValue();
37008 _this.onSelect(false, -1);
37013 this.assetHeight += this.footer.getHeight();
37018 this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
37021 this.view = new Roo.View(this.innerList, this.tpl, {
37022 singleSelect:true, store: this.store, selectedClass: this.selectedClass
37025 this.view.on('click', this.onViewClick, this);
37027 this.store.on('beforeload', this.onBeforeLoad, this);
37028 this.store.on('load', this.onLoad, this);
37029 this.store.on('loadexception', this.collapse, this);
37031 if(this.resizable){
37032 this.resizer = new Roo.Resizable(this.list, {
37033 pinned:true, handles:'se'
37035 this.resizer.on('resize', function(r, w, h){
37036 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
37037 this.listWidth = w;
37038 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
37039 this.restrictHeight();
37041 this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
37043 if(!this.editable){
37044 this.editable = true;
37045 this.setEditable(false);
37050 initEvents : function(){
37051 Roo.form.ComboBox.superclass.initEvents.call(this);
37053 this.keyNav = new Roo.KeyNav(this.el, {
37054 "up" : function(e){
37055 this.inKeyMode = true;
37059 "down" : function(e){
37060 if(!this.isExpanded()){
37061 this.onTriggerClick();
37063 this.inKeyMode = true;
37068 "enter" : function(e){
37069 this.onViewClick();
37073 "esc" : function(e){
37077 "tab" : function(e){
37078 this.onViewClick(false);
37084 doRelay : function(foo, bar, hname){
37085 if(hname == 'down' || this.scope.isExpanded()){
37086 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
37093 this.queryDelay = Math.max(this.queryDelay || 10,
37094 this.mode == 'local' ? 10 : 250);
37095 this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
37096 if(this.typeAhead){
37097 this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
37099 if(this.editable !== false){
37100 this.el.on("keyup", this.onKeyUp, this);
37102 if(this.forceSelection){
37103 this.on('blur', this.doForce, this);
37107 onDestroy : function(){
37109 this.view.setStore(null);
37110 this.view.el.removeAllListeners();
37111 this.view.el.remove();
37112 this.view.purgeListeners();
37115 this.list.destroy();
37118 this.store.un('beforeload', this.onBeforeLoad, this);
37119 this.store.un('load', this.onLoad, this);
37120 this.store.un('loadexception', this.collapse, this);
37122 Roo.form.ComboBox.superclass.onDestroy.call(this);
37126 fireKey : function(e){
37127 if(e.isNavKeyPress() && !this.list.isVisible()){
37128 this.fireEvent("specialkey", this, e);
37133 onResize: function(w, h){
37134 Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
37135 if(this.list && this.listWidth === undefined){
37136 var lw = Math.max(w, this.minListWidth);
37137 this.list.setWidth(lw);
37138 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
37143 * Allow or prevent the user from directly editing the field text. If false is passed,
37144 * the user will only be able to select from the items defined in the dropdown list. This method
37145 * is the runtime equivalent of setting the 'editable' config option at config time.
37146 * @param {Boolean} value True to allow the user to directly edit the field text
37148 setEditable : function(value){
37149 if(value == this.editable){
37152 this.editable = value;
37154 this.el.dom.setAttribute('readOnly', true);
37155 this.el.on('mousedown', this.onTriggerClick, this);
37156 this.el.addClass('x-combo-noedit');
37158 this.el.dom.setAttribute('readOnly', false);
37159 this.el.un('mousedown', this.onTriggerClick, this);
37160 this.el.removeClass('x-combo-noedit');
37165 onBeforeLoad : function(){
37166 if(!this.hasFocus){
37169 this.innerList.update(this.loadingText ?
37170 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
37171 this.restrictHeight();
37172 this.selectedIndex = -1;
37176 onLoad : function(){
37177 if(!this.hasFocus){
37180 if(this.store.getCount() > 0){
37182 this.restrictHeight();
37183 if(this.lastQuery == this.allQuery){
37185 this.el.dom.select();
37187 if(!this.selectByValue(this.value, true)){
37188 this.select(0, true);
37192 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
37193 this.taTask.delay(this.typeAheadDelay);
37197 this.onEmptyResults();
37203 onTypeAhead : function(){
37204 if(this.store.getCount() > 0){
37205 var r = this.store.getAt(0);
37206 var newValue = r.data[this.displayField];
37207 var len = newValue.length;
37208 var selStart = this.getRawValue().length;
37209 if(selStart != len){
37210 this.setRawValue(newValue);
37211 this.selectText(selStart, newValue.length);
37217 onSelect : function(record, index){
37218 if(this.fireEvent('beforeselect', this, record, index) !== false){
37219 this.setFromData(index > -1 ? record.data : false);
37221 this.fireEvent('select', this, record, index);
37226 * Returns the currently selected field value or empty string if no value is set.
37227 * @return {String} value The selected value
37229 getValue : function(){
37230 if(this.valueField){
37231 return typeof this.value != 'undefined' ? this.value : '';
37233 return Roo.form.ComboBox.superclass.getValue.call(this);
37238 * Clears any text/value currently set in the field
37240 clearValue : function(){
37241 if(this.hiddenField){
37242 this.hiddenField.value = '';
37245 this.setRawValue('');
37246 this.lastSelectionText = '';
37247 this.applyEmptyText();
37251 * Sets the specified value into the field. If the value finds a match, the corresponding record text
37252 * will be displayed in the field. If the value does not match the data value of an existing item,
37253 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
37254 * Otherwise the field will be blank (although the value will still be set).
37255 * @param {String} value The value to match
37257 setValue : function(v){
37259 if(this.valueField){
37260 var r = this.findRecord(this.valueField, v);
37262 text = r.data[this.displayField];
37263 }else if(this.valueNotFoundText !== undefined){
37264 text = this.valueNotFoundText;
37267 this.lastSelectionText = text;
37268 if(this.hiddenField){
37269 this.hiddenField.value = v;
37271 Roo.form.ComboBox.superclass.setValue.call(this, text);
37275 * @property {Object} the last set data for the element
37280 * Sets the value of the field based on a object which is related to the record format for the store.
37281 * @param {Object} value the value to set as. or false on reset?
37283 setFromData : function(o){
37284 var dv = ''; // display value
37285 var vv = ''; // value value..
37287 if (this.displayField) {
37288 dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
37290 // this is an error condition!!!
37291 console.log('no value field set for '+ this.name);
37294 if(this.valueField){
37295 vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
37297 if(this.hiddenField){
37298 this.hiddenField.value = vv;
37300 this.lastSelectionText = dv;
37301 Roo.form.ComboBox.superclass.setValue.call(this, dv);
37305 // no hidden field.. - we store the value in 'value', but still display
37306 // display field!!!!
37307 this.lastSelectionText = dv;
37308 Roo.form.ComboBox.superclass.setValue.call(this, dv);
37314 reset : function(){
37315 // overridden so that last data is reset..
37316 this.setValue(this.originalValue);
37317 this.clearInvalid();
37318 this.lastData = false;
37321 findRecord : function(prop, value){
37323 if(this.store.getCount() > 0){
37324 this.store.each(function(r){
37325 if(r.data[prop] == value){
37335 onViewMove : function(e, t){
37336 this.inKeyMode = false;
37340 onViewOver : function(e, t){
37341 if(this.inKeyMode){ // prevent key nav and mouse over conflicts
37344 var item = this.view.findItemFromChild(t);
37346 var index = this.view.indexOf(item);
37347 this.select(index, false);
37352 onViewClick : function(doFocus){
37353 var index = this.view.getSelectedIndexes()[0];
37354 var r = this.store.getAt(index);
37356 this.onSelect(r, index);
37358 if(doFocus !== false && !this.blockFocus){
37364 restrictHeight : function(){
37365 this.innerList.dom.style.height = '';
37366 var inner = this.innerList.dom;
37367 var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
37368 this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
37369 this.list.beginUpdate();
37370 this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
37371 this.list.alignTo(this.el, this.listAlign);
37372 this.list.endUpdate();
37376 onEmptyResults : function(){
37381 * Returns true if the dropdown list is expanded, else false.
37383 isExpanded : function(){
37384 return this.list.isVisible();
37388 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
37389 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
37390 * @param {String} value The data value of the item to select
37391 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
37392 * selected item if it is not currently in view (defaults to true)
37393 * @return {Boolean} True if the value matched an item in the list, else false
37395 selectByValue : function(v, scrollIntoView){
37396 if(v !== undefined && v !== null){
37397 var r = this.findRecord(this.valueField || this.displayField, v);
37399 this.select(this.store.indexOf(r), scrollIntoView);
37407 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
37408 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
37409 * @param {Number} index The zero-based index of the list item to select
37410 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
37411 * selected item if it is not currently in view (defaults to true)
37413 select : function(index, scrollIntoView){
37414 this.selectedIndex = index;
37415 this.view.select(index);
37416 if(scrollIntoView !== false){
37417 var el = this.view.getNode(index);
37419 this.innerList.scrollChildIntoView(el, false);
37425 selectNext : function(){
37426 var ct = this.store.getCount();
37428 if(this.selectedIndex == -1){
37430 }else if(this.selectedIndex < ct-1){
37431 this.select(this.selectedIndex+1);
37437 selectPrev : function(){
37438 var ct = this.store.getCount();
37440 if(this.selectedIndex == -1){
37442 }else if(this.selectedIndex != 0){
37443 this.select(this.selectedIndex-1);
37449 onKeyUp : function(e){
37450 if(this.editable !== false && !e.isSpecialKey()){
37451 this.lastKey = e.getKey();
37452 this.dqTask.delay(this.queryDelay);
37457 validateBlur : function(){
37458 return !this.list || !this.list.isVisible();
37462 initQuery : function(){
37463 this.doQuery(this.getRawValue());
37467 doForce : function(){
37468 if(this.el.dom.value.length > 0){
37469 this.el.dom.value =
37470 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
37471 this.applyEmptyText();
37476 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
37477 * query allowing the query action to be canceled if needed.
37478 * @param {String} query The SQL query to execute
37479 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
37480 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
37481 * saved in the current store (defaults to false)
37483 doQuery : function(q, forceAll){
37484 if(q === undefined || q === null){
37489 forceAll: forceAll,
37493 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
37497 forceAll = qe.forceAll;
37498 if(forceAll === true || (q.length >= this.minChars)){
37499 if(this.lastQuery != q){
37500 this.lastQuery = q;
37501 if(this.mode == 'local'){
37502 this.selectedIndex = -1;
37504 this.store.clearFilter();
37506 this.store.filter(this.displayField, q);
37510 this.store.baseParams[this.queryParam] = q;
37512 params: this.getParams(q)
37517 this.selectedIndex = -1;
37524 getParams : function(q){
37526 //p[this.queryParam] = q;
37529 p.limit = this.pageSize;
37535 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
37537 collapse : function(){
37538 if(!this.isExpanded()){
37542 Roo.get(document).un('mousedown', this.collapseIf, this);
37543 Roo.get(document).un('mousewheel', this.collapseIf, this);
37544 this.fireEvent('collapse', this);
37548 collapseIf : function(e){
37549 if(!e.within(this.wrap) && !e.within(this.list)){
37555 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
37557 expand : function(){
37558 if(this.isExpanded() || !this.hasFocus){
37561 this.list.alignTo(this.el, this.listAlign);
37563 Roo.get(document).on('mousedown', this.collapseIf, this);
37564 Roo.get(document).on('mousewheel', this.collapseIf, this);
37565 this.fireEvent('expand', this);
37569 // Implements the default empty TriggerField.onTriggerClick function
37570 onTriggerClick : function(){
37574 if(this.isExpanded()){
37576 if (!this.blockFocus) {
37581 this.hasFocus = true;
37582 if(this.triggerAction == 'all') {
37583 this.doQuery(this.allQuery, true);
37585 this.doQuery(this.getRawValue());
37587 if (!this.blockFocus) {
37594 * @cfg {Boolean} grow
37598 * @cfg {Number} growMin
37602 * @cfg {Number} growMax
37611 * Ext JS Library 1.1.1
37612 * Copyright(c) 2006-2007, Ext JS, LLC.
37614 * Originally Released Under LGPL - original licence link has changed is not relivant.
37617 * <script type="text/javascript">
37620 * @class Roo.form.Checkbox
37621 * @extends Roo.form.Field
37622 * Single checkbox field. Can be used as a direct replacement for traditional checkbox fields.
37624 * Creates a new Checkbox
37625 * @param {Object} config Configuration options
37627 Roo.form.Checkbox = function(config){
37628 Roo.form.Checkbox.superclass.constructor.call(this, config);
37632 * Fires when the checkbox is checked or unchecked.
37633 * @param {Roo.form.Checkbox} this This checkbox
37634 * @param {Boolean} checked The new checked value
37640 Roo.extend(Roo.form.Checkbox, Roo.form.Field, {
37642 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
37644 focusClass : undefined,
37646 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
37648 fieldClass: "x-form-field",
37650 * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
37654 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
37655 * {tag: "input", type: "checkbox", autocomplete: "off"})
37657 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
37659 * @cfg {String} boxLabel The text that appears beside the checkbox
37663 * @cfg {String} inputValue The value that should go into the generated input element's value attribute
37667 * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
37669 valueOff: '0', // value when not checked..
37671 actionMode : 'viewEl',
37674 itemCls : 'x-menu-check-item x-form-item',
37675 groupClass : 'x-menu-group-item',
37676 inputType : 'hidden',
37679 inSetChecked: false, // check that we are not calling self...
37681 inputElement: false, // real input element?
37682 basedOn: false, // ????
37684 isFormField: true, // not sure where this is needed!!!!
37686 onResize : function(){
37687 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
37688 if(!this.boxLabel){
37689 this.el.alignTo(this.wrap, 'c-c');
37693 initEvents : function(){
37694 Roo.form.Checkbox.superclass.initEvents.call(this);
37695 this.el.on("click", this.onClick, this);
37696 this.el.on("change", this.onClick, this);
37700 getResizeEl : function(){
37704 getPositionEl : function(){
37709 onRender : function(ct, position){
37710 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
37712 if(this.inputValue !== undefined){
37713 this.el.dom.value = this.inputValue;
37716 //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
37717 this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
37718 var viewEl = this.wrap.createChild({
37719 tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
37720 this.viewEl = viewEl;
37721 this.wrap.on('click', this.onClick, this);
37723 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
37724 this.el.on('propertychange', this.setFromHidden, this); //ie
37729 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
37730 // viewEl.on('click', this.onClick, this);
37732 //if(this.checked){
37733 this.setChecked(this.checked);
37735 //this.checked = this.el.dom;
37741 initValue : Roo.emptyFn,
37744 * Returns the checked state of the checkbox.
37745 * @return {Boolean} True if checked, else false
37747 getValue : function(){
37749 return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
37751 return this.valueOff;
37756 onClick : function(){
37757 this.setChecked(!this.checked);
37759 //if(this.el.dom.checked != this.checked){
37760 // this.setValue(this.el.dom.checked);
37765 * Sets the checked state of the checkbox.
37766 * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
37768 setValue : function(v,suppressEvent){
37769 //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
37770 //if(this.el && this.el.dom){
37771 // this.el.dom.checked = this.checked;
37772 // this.el.dom.defaultChecked = this.checked;
37774 this.setChecked(v === this.inputValue);
37775 //this.fireEvent("check", this, this.checked);
37778 setChecked : function(state,suppressEvent)
37780 if (this.inSetChecked) {
37781 this.checked = state;
37787 this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
37789 this.checked = state;
37790 if(suppressEvent !== true){
37791 this.fireEvent('checkchange', this, state);
37793 this.inSetChecked = true;
37794 this.el.dom.value = state ? this.inputValue : this.valueOff;
37795 this.inSetChecked = false;
37798 // handle setting of hidden value by some other method!!?!?
37799 setFromHidden: function()
37804 //console.log("SET FROM HIDDEN");
37805 //alert('setFrom hidden');
37806 this.setValue(this.el.dom.value);
37809 onDestroy : function()
37812 Roo.get(this.viewEl).remove();
37815 Roo.form.Checkbox.superclass.onDestroy.call(this);
37820 * Ext JS Library 1.1.1
37821 * Copyright(c) 2006-2007, Ext JS, LLC.
37823 * Originally Released Under LGPL - original licence link has changed is not relivant.
37826 * <script type="text/javascript">
37830 * @class Roo.form.Radio
37831 * @extends Roo.form.Checkbox
37832 * Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type.
37833 * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
37835 * Creates a new Radio
37836 * @param {Object} config Configuration options
37838 Roo.form.Radio = function(){
37839 Roo.form.Radio.superclass.constructor.apply(this, arguments);
37841 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
37842 inputType: 'radio',
37845 * If this radio is part of a group, it will return the selected value
37848 getGroupValue : function(){
37849 return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
37851 });//<script type="text/javascript">
37854 * Ext JS Library 1.1.1
37855 * Copyright(c) 2006-2007, Ext JS, LLC.
37856 * licensing@extjs.com
37858 * http://www.extjs.com/license
37864 * Default CSS appears to render it as fixed text by default (should really be Sans-Serif)
37865 * - IE ? - no idea how much works there.
37873 * @class Ext.form.HtmlEditor
37874 * @extends Ext.form.Field
37875 * Provides a lightweight HTML Editor component.
37876 * WARNING - THIS CURRENTlY ONLY WORKS ON FIREFOX - USE FCKeditor for a cross platform version
37878 * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
37879 * supported by this editor.</b><br/><br/>
37880 * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
37881 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
37883 Roo.form.HtmlEditor = Roo.extend(Roo.form.Field, {
37885 * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
37889 * @cfg {String} createLinkText The default text for the create link prompt
37891 createLinkText : 'Please enter the URL for the link:',
37893 * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
37895 defaultLinkValue : 'http:/'+'/',
37901 // private properties
37902 validationEvent : false,
37904 initialized : false,
37906 sourceEditMode : false,
37907 onFocus : Roo.emptyFn,
37909 hideMode:'offsets',
37910 defaultAutoCreate : {
37912 style:"width:500px;height:300px;",
37913 autocomplete: "off"
37917 initComponent : function(){
37920 * @event initialize
37921 * Fires when the editor is fully initialized (including the iframe)
37922 * @param {HtmlEditor} this
37927 * Fires when the editor is first receives the focus. Any insertion must wait
37928 * until after this event.
37929 * @param {HtmlEditor} this
37933 * @event beforesync
37934 * Fires before the textarea is updated with content from the editor iframe. Return false
37935 * to cancel the sync.
37936 * @param {HtmlEditor} this
37937 * @param {String} html
37941 * @event beforepush
37942 * Fires before the iframe editor is updated with content from the textarea. Return false
37943 * to cancel the push.
37944 * @param {HtmlEditor} this
37945 * @param {String} html
37950 * Fires when the textarea is updated with content from the editor iframe.
37951 * @param {HtmlEditor} this
37952 * @param {String} html
37957 * Fires when the iframe editor is updated with content from the textarea.
37958 * @param {HtmlEditor} this
37959 * @param {String} html
37963 * @event editmodechange
37964 * Fires when the editor switches edit modes
37965 * @param {HtmlEditor} this
37966 * @param {Boolean} sourceEdit True if source edit, false if standard editing.
37968 editmodechange: true,
37970 * @event editorevent
37971 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
37972 * @param {HtmlEditor} this
37979 * Protected method that will not generally be called directly. It
37980 * is called when the editor creates its toolbar. Override this method if you need to
37981 * add custom toolbar buttons.
37982 * @param {HtmlEditor} editor
37984 createToolbar : function(editor){
37985 if (!editor.toolbars || !editor.toolbars.length) {
37986 editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
37989 for (var i =0 ; i < editor.toolbars.length;i++) {
37990 editor.toolbars[i].init(editor);
37997 * Protected method that will not generally be called directly. It
37998 * is called when the editor initializes the iframe with HTML contents. Override this method if you
37999 * want to change the initialization markup of the iframe (e.g. to add stylesheets).
38001 getDocMarkup : function(){
38002 return '<html><head><style type="text/css">body{border:0;margin:0;padding:3px;height:98%;cursor:text;}</style></head><body></body></html>';
38006 onRender : function(ct, position){
38007 Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
38008 this.el.dom.style.border = '0 none';
38009 this.el.dom.setAttribute('tabIndex', -1);
38010 this.el.addClass('x-hidden');
38011 if(Roo.isIE){ // fix IE 1px bogus margin
38012 this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
38014 this.wrap = this.el.wrap({
38015 cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
38018 this.frameId = Roo.id();
38019 this.createToolbar(this);
38026 var iframe = this.wrap.createChild({
38029 name: this.frameId,
38030 frameBorder : 'no',
38031 'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL : "javascript:false"
38034 // console.log(iframe);
38035 //this.wrap.dom.appendChild(iframe);
38037 this.iframe = iframe.dom;
38039 this.assignDocWin();
38041 this.doc.designMode = 'on';
38044 this.doc.write(this.getDocMarkup());
38048 var task = { // must defer to wait for browser to be ready
38050 //console.log("run task?" + this.doc.readyState);
38051 this.assignDocWin();
38052 if(this.doc.body || this.doc.readyState == 'complete'){
38056 this.doc.designMode="on";
38060 Roo.TaskMgr.stop(task);
38061 this.initEditor.defer(10, this);
38068 Roo.TaskMgr.start(task);
38071 this.setSize(this.el.getSize());
38076 onResize : function(w, h){
38077 Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
38078 if(this.el && this.iframe){
38079 if(typeof w == 'number'){
38080 var aw = w - this.wrap.getFrameWidth('lr');
38081 this.el.setWidth(this.adjustWidth('textarea', aw));
38082 this.iframe.style.width = aw + 'px';
38084 if(typeof h == 'number'){
38086 for (var i =0; i < this.toolbars.length;i++) {
38087 // fixme - ask toolbars for heights?
38088 tbh += this.toolbars[i].tb.el.getHeight();
38094 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
38095 this.el.setHeight(this.adjustWidth('textarea', ah));
38096 this.iframe.style.height = ah + 'px';
38098 (this.doc.body || this.doc.documentElement).style.height = (ah - (this.iframePad*2)) + 'px';
38105 * Toggles the editor between standard and source edit mode.
38106 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
38108 toggleSourceEdit : function(sourceEditMode){
38110 this.sourceEditMode = sourceEditMode === true;
38112 if(this.sourceEditMode){
38115 this.iframe.className = 'x-hidden';
38116 this.el.removeClass('x-hidden');
38117 this.el.dom.removeAttribute('tabIndex');
38122 this.iframe.className = '';
38123 this.el.addClass('x-hidden');
38124 this.el.dom.setAttribute('tabIndex', -1);
38127 this.setSize(this.wrap.getSize());
38128 this.fireEvent('editmodechange', this, this.sourceEditMode);
38131 // private used internally
38132 createLink : function(){
38133 var url = prompt(this.createLinkText, this.defaultLinkValue);
38134 if(url && url != 'http:/'+'/'){
38135 this.relayCmd('createlink', url);
38139 // private (for BoxComponent)
38140 adjustSize : Roo.BoxComponent.prototype.adjustSize,
38142 // private (for BoxComponent)
38143 getResizeEl : function(){
38147 // private (for BoxComponent)
38148 getPositionEl : function(){
38153 initEvents : function(){
38154 this.originalValue = this.getValue();
38158 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
38161 markInvalid : Roo.emptyFn,
38163 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
38166 clearInvalid : Roo.emptyFn,
38168 setValue : function(v){
38169 Roo.form.HtmlEditor.superclass.setValue.call(this, v);
38174 * Protected method that will not generally be called directly. If you need/want
38175 * custom HTML cleanup, this is the method you should override.
38176 * @param {String} html The HTML to be cleaned
38177 * return {String} The cleaned HTML
38179 cleanHtml : function(html){
38180 html = String(html);
38181 if(html.length > 5){
38182 if(Roo.isSafari){ // strip safari nonsense
38183 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
38186 if(html == ' '){
38193 * Protected method that will not generally be called directly. Syncs the contents
38194 * of the editor iframe with the textarea.
38196 syncValue : function(){
38197 if(this.initialized){
38198 var bd = (this.doc.body || this.doc.documentElement);
38199 var html = bd.innerHTML;
38201 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
38202 var m = bs.match(/text-align:(.*?);/i);
38204 html = '<div style="'+m[0]+'">' + html + '</div>';
38207 html = this.cleanHtml(html);
38208 if(this.fireEvent('beforesync', this, html) !== false){
38209 this.el.dom.value = html;
38210 this.fireEvent('sync', this, html);
38216 * Protected method that will not generally be called directly. Pushes the value of the textarea
38217 * into the iframe editor.
38219 pushValue : function(){
38220 if(this.initialized){
38221 var v = this.el.dom.value;
38225 if(this.fireEvent('beforepush', this, v) !== false){
38226 (this.doc.body || this.doc.documentElement).innerHTML = v;
38227 this.fireEvent('push', this, v);
38233 deferFocus : function(){
38234 this.focus.defer(10, this);
38238 focus : function(){
38239 if(this.win && !this.sourceEditMode){
38246 assignDocWin: function()
38248 var iframe = this.iframe;
38251 this.doc = iframe.contentWindow.document;
38252 this.win = iframe.contentWindow;
38254 this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
38255 this.win = Roo.get(this.frameId).dom.contentWindow;
38260 initEditor : function(){
38261 //console.log("INIT EDITOR");
38262 this.assignDocWin();
38266 this.doc.designMode="on";
38268 this.doc.write(this.getDocMarkup());
38271 var dbody = (this.doc.body || this.doc.documentElement);
38272 //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
38273 // this copies styles from the containing element into thsi one..
38274 // not sure why we need all of this..
38275 var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
38276 ss['background-attachment'] = 'fixed'; // w3c
38277 dbody.bgProperties = 'fixed'; // ie
38278 Roo.DomHelper.applyStyles(dbody, ss);
38279 Roo.EventManager.on(this.doc, {
38280 'mousedown': this.onEditorEvent,
38281 'dblclick': this.onEditorEvent,
38282 'click': this.onEditorEvent,
38283 'keyup': this.onEditorEvent,
38288 Roo.EventManager.on(this.doc, 'keypress', this.applyCommand, this);
38290 if(Roo.isIE || Roo.isSafari || Roo.isOpera){
38291 Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
38293 this.initialized = true;
38295 this.fireEvent('initialize', this);
38300 onDestroy : function(){
38306 for (var i =0; i < this.toolbars.length;i++) {
38307 // fixme - ask toolbars for heights?
38308 this.toolbars[i].onDestroy();
38311 this.wrap.dom.innerHTML = '';
38312 this.wrap.remove();
38317 onFirstFocus : function(){
38319 this.assignDocWin();
38322 this.activated = true;
38323 for (var i =0; i < this.toolbars.length;i++) {
38324 this.toolbars[i].onFirstFocus();
38327 if(Roo.isGecko){ // prevent silly gecko errors
38329 var s = this.win.getSelection();
38330 if(!s.focusNode || s.focusNode.nodeType != 3){
38331 var r = s.getRangeAt(0);
38332 r.selectNodeContents((this.doc.body || this.doc.documentElement));
38337 this.execCmd('useCSS', true);
38338 this.execCmd('styleWithCSS', false);
38341 this.fireEvent('activate', this);
38345 adjustFont: function(btn){
38346 var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
38347 //if(Roo.isSafari){ // safari
38350 var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
38351 if(Roo.isSafari){ // safari
38352 var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
38353 v = (v < 10) ? 10 : v;
38354 v = (v > 48) ? 48 : v;
38355 v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
38360 v = Math.max(1, v+adjust);
38362 this.execCmd('FontSize', v );
38365 onEditorEvent : function(e){
38366 this.fireEvent('editorevent', this, e);
38367 // this.updateToolbar();
38371 insertTag : function(tg)
38373 // could be a bit smarter... -> wrap the current selected tRoo..
38375 this.execCmd("formatblock", tg);
38379 insertText : function(txt)
38383 range = this.createRange();
38384 range.deleteContents();
38385 //alert(Sender.getAttribute('label'));
38387 range.insertNode(this.doc.createTextNode(txt));
38391 relayBtnCmd : function(btn){
38392 this.relayCmd(btn.cmd);
38396 * Executes a Midas editor command on the editor document and performs necessary focus and
38397 * toolbar updates. <b>This should only be called after the editor is initialized.</b>
38398 * @param {String} cmd The Midas command
38399 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
38401 relayCmd : function(cmd, value){
38403 this.execCmd(cmd, value);
38404 this.fireEvent('editorevent', this);
38405 //this.updateToolbar();
38410 * Executes a Midas editor command directly on the editor document.
38411 * For visual commands, you should use {@link #relayCmd} instead.
38412 * <b>This should only be called after the editor is initialized.</b>
38413 * @param {String} cmd The Midas command
38414 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
38416 execCmd : function(cmd, value){
38417 this.doc.execCommand(cmd, false, value === undefined ? null : value);
38422 applyCommand : function(e){
38424 var c = e.getCharCode(), cmd;
38426 c = String.fromCharCode(c);
38442 e.preventDefault();
38449 * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
38451 * @param {String} text
38453 insertAtCursor : function(text){
38454 if(!this.activated){
38459 var r = this.doc.selection.createRange();
38466 }else if(Roo.isGecko || Roo.isOpera){
38468 this.execCmd('InsertHTML', text);
38470 }else if(Roo.isSafari){
38471 this.execCmd('InsertText', text);
38477 fixKeys : function(){ // load time branching for fastest keydown performance
38479 return function(e){
38480 var k = e.getKey(), r;
38483 r = this.doc.selection.createRange();
38486 r.pasteHTML('    ');
38489 }else if(k == e.ENTER){
38490 r = this.doc.selection.createRange();
38492 var target = r.parentElement();
38493 if(!target || target.tagName.toLowerCase() != 'li'){
38495 r.pasteHTML('<br />');
38502 }else if(Roo.isOpera){
38503 return function(e){
38504 var k = e.getKey();
38508 this.execCmd('InsertHTML','    ');
38512 }else if(Roo.isSafari){
38513 return function(e){
38514 var k = e.getKey();
38517 this.execCmd('InsertText','\t');
38524 getAllAncestors: function()
38526 var p = this.getSelectedNode();
38529 a.push(p); // push blank onto stack..
38530 p = this.getParentElement();
38534 while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
38538 a.push(this.doc.body);
38542 lastSelNode : false,
38545 getSelection : function()
38547 this.assignDocWin();
38548 return Roo.isIE ? this.doc.selection : this.win.getSelection();
38551 getSelectedNode: function()
38553 // this may only work on Gecko!!!
38555 // should we cache this!!!!
38560 var range = this.createRange(this.getSelection());
38563 var parent = range.parentElement();
38565 var testRange = range.duplicate();
38566 testRange.moveToElementText(parent);
38567 if (testRange.inRange(range)) {
38570 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
38573 parent = parent.parentElement;
38579 var ar = range.endContainer.childNodes;
38581 ar = range.commonAncestorContainer.childNodes;
38582 //alert(ar.length);
38585 var other_nodes = [];
38586 var has_other_nodes = false;
38587 for (var i=0;i<ar.length;i++) {
38588 if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ?
38591 // fullly contained node.
38593 if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
38598 // probably selected..
38599 if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
38600 other_nodes.push(ar[i]);
38603 if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0)) {
38608 has_other_nodes = true;
38610 if (!nodes.length && other_nodes.length) {
38611 nodes= other_nodes;
38613 if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
38619 createRange: function(sel)
38621 // this has strange effects when using with
38622 // top toolbar - not sure if it's a great idea.
38623 //this.editor.contentWindow.focus();
38624 if (typeof sel != "undefined") {
38626 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
38628 return this.doc.createRange();
38631 return this.doc.createRange();
38634 getParentElement: function()
38637 this.assignDocWin();
38638 var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
38640 var range = this.createRange(sel);
38643 var p = range.commonAncestorContainer;
38644 while (p.nodeType == 3) { // text node
38656 // BC Hacks - cause I cant work out what i was trying to do..
38657 rangeIntersectsNode : function(range, node)
38659 var nodeRange = node.ownerDocument.createRange();
38661 nodeRange.selectNode(node);
38664 nodeRange.selectNodeContents(node);
38667 return range.compareBoundaryPoints(Range.END_TO_START, nodeRange) == -1 &&
38668 range.compareBoundaryPoints(Range.START_TO_END, nodeRange) == 1;
38670 rangeCompareNode : function(range, node) {
38671 var nodeRange = node.ownerDocument.createRange();
38673 nodeRange.selectNode(node);
38675 nodeRange.selectNodeContents(node);
38677 var nodeIsBefore = range.compareBoundaryPoints(Range.START_TO_START, nodeRange) == 1;
38678 var nodeIsAfter = range.compareBoundaryPoints(Range.END_TO_END, nodeRange) == -1;
38680 if (nodeIsBefore && !nodeIsAfter)
38682 if (!nodeIsBefore && nodeIsAfter)
38684 if (nodeIsBefore && nodeIsAfter)
38692 // hide stuff that is not compatible
38706 * @event specialkey
38710 * @cfg {String} fieldClass @hide
38713 * @cfg {String} focusClass @hide
38716 * @cfg {String} autoCreate @hide
38719 * @cfg {String} inputType @hide
38722 * @cfg {String} invalidClass @hide
38725 * @cfg {String} invalidText @hide
38728 * @cfg {String} msgFx @hide
38731 * @cfg {String} validateOnBlur @hide
38733 });// <script type="text/javascript">
38736 * Ext JS Library 1.1.1
38737 * Copyright(c) 2006-2007, Ext JS, LLC.
38743 * @class Roo.form.HtmlEditorToolbar1
38748 new Roo.form.HtmlEditor({
38751 new Roo.form.HtmlEditorToolbar1({
38752 disable : { fonts: 1 , format: 1, ..., ... , ...],
38758 * @cfg {Object} disable List of elements to disable..
38759 * @cfg {Array} btns List of additional buttons.
38763 * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
38766 Roo.form.HtmlEditor.ToolbarStandard = function(config)
38769 Roo.apply(this, config);
38770 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
38771 // dont call parent... till later.
38774 Roo.apply(Roo.form.HtmlEditor.ToolbarStandard.prototype, {
38782 * @cfg {Object} disable List of toolbar elements to disable
38787 * @cfg {Array} fontFamilies An array of available font families
38805 // "á" , ?? a acute?
38810 "°" // , // degrees
38812 // "é" , // e ecute
38813 // "ú" , // u ecute?
38816 "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password",
38817 "input:submit", "input:button", "select", "textarea", "label" ],
38820 ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"],
38822 ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"]
38825 * @cfg {String} defaultFont default font to use.
38827 defaultFont: 'tahoma',
38829 fontSelect : false,
38832 formatCombo : false,
38834 init : function(editor)
38836 this.editor = editor;
38839 var fid = editor.frameId;
38841 function btn(id, toggle, handler){
38842 var xid = fid + '-'+ id ;
38846 cls : 'x-btn-icon x-edit-'+id,
38847 enableToggle:toggle !== false,
38848 scope: editor, // was editor...
38849 handler:handler||editor.relayBtnCmd,
38850 clickEvent:'mousedown',
38851 tooltip: etb.buttonTips[id] || undefined, ///tips ???
38858 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
38860 // stop form submits
38861 tb.el.on('click', function(e){
38862 e.preventDefault(); // what does this do?
38865 if(!this.disable.font && !Roo.isSafari){
38866 /* why no safari for fonts
38867 editor.fontSelect = tb.el.createChild({
38870 cls:'x-font-select',
38871 html: editor.createFontOptions()
38873 editor.fontSelect.on('change', function(){
38874 var font = editor.fontSelect.dom.value;
38875 editor.relayCmd('fontname', font);
38876 editor.deferFocus();
38879 editor.fontSelect.dom,
38884 if(!this.disable.formats){
38885 this.formatCombo = new Roo.form.ComboBox({
38886 store: new Roo.data.SimpleStore({
38889 data : this.formats // from states.js
38892 //autoCreate : {tag: "div", size: "20"},
38893 displayField:'tag',
38897 triggerAction: 'all',
38898 emptyText:'Add tag',
38899 selectOnFocus:true,
38902 'select': function(c, r, i) {
38903 editor.insertTag(r.get('tag'));
38909 tb.addField(this.formatCombo);
38913 if(!this.disable.format){
38920 if(!this.disable.fontSize){
38925 btn('increasefontsize', false, editor.adjustFont),
38926 btn('decreasefontsize', false, editor.adjustFont)
38931 if(this.disable.colors){
38934 id:editor.frameId +'-forecolor',
38935 cls:'x-btn-icon x-edit-forecolor',
38936 clickEvent:'mousedown',
38937 tooltip: this.buttonTips['forecolor'] || undefined,
38939 menu : new Roo.menu.ColorMenu({
38940 allowReselect: true,
38941 focus: Roo.emptyFn,
38944 selectHandler: function(cp, color){
38945 editor.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
38946 editor.deferFocus();
38949 clickEvent:'mousedown'
38952 id:editor.frameId +'backcolor',
38953 cls:'x-btn-icon x-edit-backcolor',
38954 clickEvent:'mousedown',
38955 tooltip: this.buttonTips['backcolor'] || undefined,
38957 menu : new Roo.menu.ColorMenu({
38958 focus: Roo.emptyFn,
38961 allowReselect: true,
38962 selectHandler: function(cp, color){
38964 editor.execCmd('useCSS', false);
38965 editor.execCmd('hilitecolor', color);
38966 editor.execCmd('useCSS', true);
38967 editor.deferFocus();
38969 editor.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor',
38970 Roo.isSafari || Roo.isIE ? '#'+color : color);
38971 editor.deferFocus();
38975 clickEvent:'mousedown'
38980 // now add all the items...
38983 if(!this.disable.alignments){
38986 btn('justifyleft'),
38987 btn('justifycenter'),
38988 btn('justifyright')
38992 //if(!Roo.isSafari){
38993 if(!this.disable.links){
38996 btn('createlink', false, editor.createLink) /// MOVE TO HERE?!!?!?!?!
39000 if(!this.disable.lists){
39003 btn('insertorderedlist'),
39004 btn('insertunorderedlist')
39007 if(!this.disable.sourceEdit){
39010 btn('sourceedit', true, function(btn){
39011 this.toggleSourceEdit(btn.pressed);
39018 // special menu.. - needs to be tidied up..
39019 if (!this.disable.special) {
39022 cls: 'x-edit-none',
39027 for (var i =0; i < this.specialChars.length; i++) {
39028 smenu.menu.items.push({
39030 text: this.specialChars[i],
39031 handler: function(a,b) {
39032 editor.insertAtCursor(String.fromCharCode(a.text.replace('&#','').replace(';', '')));
39044 for(var i =0; i< this.btns.length;i++) {
39045 var b = this.btns[i];
39046 b.cls = 'x-edit-none';
39055 // disable everything...
39057 this.tb.items.each(function(item){
39058 if(item.id != editor.frameId+ '-sourceedit'){
39062 this.rendered = true;
39064 // the all the btns;
39065 editor.on('editorevent', this.updateToolbar, this);
39066 // other toolbars need to implement this..
39067 //editor.on('editmodechange', this.updateToolbar, this);
39073 * Protected method that will not generally be called directly. It triggers
39074 * a toolbar update by reading the markup state of the current selection in the editor.
39076 updateToolbar: function(){
39078 if(!this.editor.activated){
39079 this.editor.onFirstFocus();
39083 var btns = this.tb.items.map,
39084 doc = this.editor.doc,
39085 frameId = this.editor.frameId;
39087 if(!this.disable.font && !Roo.isSafari){
39089 var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
39090 if(name != this.fontSelect.dom.value){
39091 this.fontSelect.dom.value = name;
39095 if(!this.disable.format){
39096 btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
39097 btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
39098 btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
39100 if(!this.disable.alignments){
39101 btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
39102 btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
39103 btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
39105 if(!Roo.isSafari && !this.disable.lists){
39106 btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
39107 btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
39110 var ans = this.editor.getAllAncestors();
39111 if (this.formatCombo) {
39114 var store = this.formatCombo.store;
39115 this.formatCombo.setValue("");
39116 for (var i =0; i < ans.length;i++) {
39117 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), true).length) {
39119 this.formatCombo.setValue(ans[i].tagName.toLowerCase());
39127 // hides menus... - so this cant be on a menu...
39128 Roo.menu.MenuMgr.hideAll();
39130 //this.editorsyncValue();
39134 createFontOptions : function(){
39135 var buf = [], fs = this.fontFamilies, ff, lc;
39136 for(var i = 0, len = fs.length; i< len; i++){
39138 lc = ff.toLowerCase();
39140 '<option value="',lc,'" style="font-family:',ff,';"',
39141 (this.defaultFont == lc ? ' selected="true">' : '>'),
39146 return buf.join('');
39149 toggleSourceEdit : function(sourceEditMode){
39150 if(sourceEditMode === undefined){
39151 sourceEditMode = !this.sourceEditMode;
39153 this.sourceEditMode = sourceEditMode === true;
39154 var btn = this.tb.items.get(this.editor.frameId +'-sourceedit');
39155 // just toggle the button?
39156 if(btn.pressed !== this.editor.sourceEditMode){
39157 btn.toggle(this.editor.sourceEditMode);
39161 if(this.sourceEditMode){
39162 this.tb.items.each(function(item){
39163 if(item.cmd != 'sourceedit'){
39169 if(this.initialized){
39170 this.tb.items.each(function(item){
39176 // tell the editor that it's been pressed..
39177 this.editor.toggleSourceEdit(sourceEditMode);
39181 * Object collection of toolbar tooltips for the buttons in the editor. The key
39182 * is the command id associated with that button and the value is a valid QuickTips object.
39187 title: 'Bold (Ctrl+B)',
39188 text: 'Make the selected text bold.',
39189 cls: 'x-html-editor-tip'
39192 title: 'Italic (Ctrl+I)',
39193 text: 'Make the selected text italic.',
39194 cls: 'x-html-editor-tip'
39202 title: 'Bold (Ctrl+B)',
39203 text: 'Make the selected text bold.',
39204 cls: 'x-html-editor-tip'
39207 title: 'Italic (Ctrl+I)',
39208 text: 'Make the selected text italic.',
39209 cls: 'x-html-editor-tip'
39212 title: 'Underline (Ctrl+U)',
39213 text: 'Underline the selected text.',
39214 cls: 'x-html-editor-tip'
39216 increasefontsize : {
39217 title: 'Grow Text',
39218 text: 'Increase the font size.',
39219 cls: 'x-html-editor-tip'
39221 decreasefontsize : {
39222 title: 'Shrink Text',
39223 text: 'Decrease the font size.',
39224 cls: 'x-html-editor-tip'
39227 title: 'Text Highlight Color',
39228 text: 'Change the background color of the selected text.',
39229 cls: 'x-html-editor-tip'
39232 title: 'Font Color',
39233 text: 'Change the color of the selected text.',
39234 cls: 'x-html-editor-tip'
39237 title: 'Align Text Left',
39238 text: 'Align text to the left.',
39239 cls: 'x-html-editor-tip'
39242 title: 'Center Text',
39243 text: 'Center text in the editor.',
39244 cls: 'x-html-editor-tip'
39247 title: 'Align Text Right',
39248 text: 'Align text to the right.',
39249 cls: 'x-html-editor-tip'
39251 insertunorderedlist : {
39252 title: 'Bullet List',
39253 text: 'Start a bulleted list.',
39254 cls: 'x-html-editor-tip'
39256 insertorderedlist : {
39257 title: 'Numbered List',
39258 text: 'Start a numbered list.',
39259 cls: 'x-html-editor-tip'
39262 title: 'Hyperlink',
39263 text: 'Make the selected text a hyperlink.',
39264 cls: 'x-html-editor-tip'
39267 title: 'Source Edit',
39268 text: 'Switch to source editing mode.',
39269 cls: 'x-html-editor-tip'
39273 onDestroy : function(){
39276 this.tb.items.each(function(item){
39278 item.menu.removeAll();
39280 item.menu.el.destroy();
39288 onFirstFocus: function() {
39289 this.tb.items.each(function(item){
39298 // <script type="text/javascript">
39301 * Ext JS Library 1.1.1
39302 * Copyright(c) 2006-2007, Ext JS, LLC.
39309 * @class Roo.form.HtmlEditor.ToolbarContext
39314 new Roo.form.HtmlEditor({
39317 new Roo.form.HtmlEditor.ToolbarStandard(),
39318 new Roo.form.HtmlEditor.ToolbarContext()
39323 * @config : {Object} disable List of elements to disable.. (not done yet.)
39328 Roo.form.HtmlEditor.ToolbarContext = function(config)
39331 Roo.apply(this, config);
39332 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
39333 // dont call parent... till later.
39335 Roo.form.HtmlEditor.ToolbarContext.types = {
39347 opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
39409 opts : [[""],[ "left"],[ "center"],[ "right"],[ "justify"],[ "char"]],
39414 opts : [[""],[ "top"],[ "middle"],[ "bottom"],[ "baseline"]],
39478 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype, {
39486 * @cfg {Object} disable List of toolbar elements to disable
39495 init : function(editor)
39497 this.editor = editor;
39500 var fid = editor.frameId;
39502 function btn(id, toggle, handler){
39503 var xid = fid + '-'+ id ;
39507 cls : 'x-btn-icon x-edit-'+id,
39508 enableToggle:toggle !== false,
39509 scope: editor, // was editor...
39510 handler:handler||editor.relayBtnCmd,
39511 clickEvent:'mousedown',
39512 tooltip: etb.buttonTips[id] || undefined, ///tips ???
39516 // create a new element.
39517 var wdiv = editor.wrap.createChild({
39519 }, editor.wrap.dom.firstChild.nextSibling, true);
39521 // can we do this more than once??
39523 // stop form submits
39526 // disable everything...
39527 var ty= Roo.form.HtmlEditor.ToolbarContext.types;
39528 this.toolbars = {};
39530 for (var i in ty) {
39531 this.toolbars[i] = this.buildToolbar(ty[i],i);
39533 this.tb = this.toolbars.BODY;
39537 this.rendered = true;
39539 // the all the btns;
39540 editor.on('editorevent', this.updateToolbar, this);
39541 // other toolbars need to implement this..
39542 //editor.on('editmodechange', this.updateToolbar, this);
39548 * Protected method that will not generally be called directly. It triggers
39549 * a toolbar update by reading the markup state of the current selection in the editor.
39551 updateToolbar: function(){
39553 if(!this.editor.activated){
39554 this.editor.onFirstFocus();
39559 var ans = this.editor.getAllAncestors();
39562 var ty= Roo.form.HtmlEditor.ToolbarContext.types;
39563 var sel = ans.length ? (ans[0] ? ans[0] : ans[1]) : this.editor.doc.body;
39564 sel = sel ? sel : this.editor.doc.body;
39565 sel = sel.tagName.length ? sel : this.editor.doc.body;
39566 var tn = sel.tagName.toUpperCase();
39567 sel = typeof(ty[tn]) != 'undefined' ? sel : this.editor.doc.body;
39568 tn = sel.tagName.toUpperCase();
39569 if (this.tb.name == tn) {
39570 return; // no change
39573 ///console.log("show: " + tn);
39574 this.tb = this.toolbars[tn];
39576 this.tb.fields.each(function(e) {
39577 e.setValue(sel.getAttribute(e.name));
39579 this.tb.selectedNode = sel;
39582 Roo.menu.MenuMgr.hideAll();
39584 //this.editorsyncValue();
39589 onDestroy : function(){
39592 this.tb.items.each(function(item){
39594 item.menu.removeAll();
39596 item.menu.el.destroy();
39604 onFirstFocus: function() {
39605 // need to do this for all the toolbars..
39606 this.tb.items.each(function(item){
39610 buildToolbar: function(tlist, nm)
39612 var editor = this.editor;
39613 // create a new element.
39614 var wdiv = editor.wrap.createChild({
39616 }, editor.wrap.dom.firstChild.nextSibling, true);
39619 var tb = new Roo.Toolbar(wdiv);
39620 tb.add(nm+ ": ");
39621 for (var i in tlist) {
39622 var item = tlist[i];
39623 tb.add(item.title + ": ");
39628 tb.addField( new Roo.form.ComboBox({
39629 store: new Roo.data.SimpleStore({
39632 data : item.opts // from states.js
39635 displayField:'val',
39639 triggerAction: 'all',
39640 emptyText:'Select',
39641 selectOnFocus:true,
39642 width: item.width ? item.width : 130,
39644 'select': function(c, r, i) {
39645 tb.selectedNode.setAttribute(c.name, r.get('val'));
39656 tb.addField( new Roo.form.TextField({
39659 //allowBlank:false,
39664 tb.addField( new Roo.form.TextField({
39670 'change' : function(f, nv, ov) {
39671 tb.selectedNode.setAttribute(f.name, nv);
39677 tb.el.on('click', function(e){
39678 e.preventDefault(); // what does this do?
39680 tb.el.setVisibilityMode( Roo.Element.DISPLAY);
39683 // dont need to disable them... as they will get hidden
39700 * Ext JS Library 1.1.1
39701 * Copyright(c) 2006-2007, Ext JS, LLC.
39703 * Originally Released Under LGPL - original licence link has changed is not relivant.
39706 * <script type="text/javascript">
39710 * @class Roo.form.BasicForm
39711 * @extends Roo.util.Observable
39712 * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
39714 * @param {String/HTMLElement/Roo.Element} el The form element or its id
39715 * @param {Object} config Configuration options
39717 Roo.form.BasicForm = function(el, config){
39718 this.allItems = [];
39719 this.childForms = [];
39720 Roo.apply(this, config);
39722 * The Roo.form.Field items in this form.
39723 * @type MixedCollection
39727 this.items = new Roo.util.MixedCollection(false, function(o){
39728 return o.id || (o.id = Roo.id());
39732 * @event beforeaction
39733 * Fires before any action is performed. Return false to cancel the action.
39734 * @param {Form} this
39735 * @param {Action} action The action to be performed
39737 beforeaction: true,
39739 * @event actionfailed
39740 * Fires when an action fails.
39741 * @param {Form} this
39742 * @param {Action} action The action that failed
39744 actionfailed : true,
39746 * @event actioncomplete
39747 * Fires when an action is completed.
39748 * @param {Form} this
39749 * @param {Action} action The action that completed
39751 actioncomplete : true
39756 Roo.form.BasicForm.superclass.constructor.call(this);
39759 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
39761 * @cfg {String} method
39762 * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
39765 * @cfg {DataReader} reader
39766 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
39767 * This is optional as there is built-in support for processing JSON.
39770 * @cfg {DataReader} errorReader
39771 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
39772 * This is completely optional as there is built-in support for processing JSON.
39775 * @cfg {String} url
39776 * The URL to use for form actions if one isn't supplied in the action options.
39779 * @cfg {Boolean} fileUpload
39780 * Set to true if this form is a file upload.
39783 * @cfg {Object} baseParams
39784 * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
39787 * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
39792 activeAction : null,
39795 * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
39796 * or setValues() data instead of when the form was first created.
39798 trackResetOnLoad : false,
39802 * childForms - used for multi-tab forms
39805 childForms : false,
39808 * allItems - full list of fields.
39814 * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
39815 * element by passing it or its id or mask the form itself by passing in true.
39818 waitMsgTarget : undefined,
39821 initEl : function(el){
39822 this.el = Roo.get(el);
39823 this.id = this.el.id || Roo.id();
39824 this.el.on('submit', this.onSubmit, this);
39825 this.el.addClass('x-form');
39829 onSubmit : function(e){
39834 * Returns true if client-side validation on the form is successful.
39837 isValid : function(){
39839 this.items.each(function(f){
39848 * Returns true if any fields in this form have changed since their original load.
39851 isDirty : function(){
39853 this.items.each(function(f){
39863 * Performs a predefined action (submit or load) or custom actions you define on this form.
39864 * @param {String} actionName The name of the action type
39865 * @param {Object} options (optional) The options to pass to the action. All of the config options listed
39866 * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
39867 * accept other config options):
39869 Property Type Description
39870 ---------------- --------------- ----------------------------------------------------------------------------------
39871 url String The url for the action (defaults to the form's url)
39872 method String The form method to use (defaults to the form's method, or POST if not defined)
39873 params String/Object The params to pass (defaults to the form's baseParams, or none if not defined)
39874 clientValidation Boolean Applies to submit only. Pass true to call form.isValid() prior to posting to
39875 validate the form on the client (defaults to false)
39877 * @return {BasicForm} this
39879 doAction : function(action, options){
39880 if(typeof action == 'string'){
39881 action = new Roo.form.Action.ACTION_TYPES[action](this, options);
39883 if(this.fireEvent('beforeaction', this, action) !== false){
39884 this.beforeAction(action);
39885 action.run.defer(100, action);
39891 * Shortcut to do a submit action.
39892 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
39893 * @return {BasicForm} this
39895 submit : function(options){
39896 this.doAction('submit', options);
39901 * Shortcut to do a load action.
39902 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
39903 * @return {BasicForm} this
39905 load : function(options){
39906 this.doAction('load', options);
39911 * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
39912 * @param {Record} record The record to edit
39913 * @return {BasicForm} this
39915 updateRecord : function(record){
39916 record.beginEdit();
39917 var fs = record.fields;
39918 fs.each(function(f){
39919 var field = this.findField(f.name);
39921 record.set(f.name, field.getValue());
39929 * Loads an Roo.data.Record into this form.
39930 * @param {Record} record The record to load
39931 * @return {BasicForm} this
39933 loadRecord : function(record){
39934 this.setValues(record.data);
39939 beforeAction : function(action){
39940 var o = action.options;
39942 if(this.waitMsgTarget === true){
39943 this.el.mask(o.waitMsg, 'x-mask-loading');
39944 }else if(this.waitMsgTarget){
39945 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
39946 this.waitMsgTarget.mask(o.waitMsg, 'x-mask-loading');
39948 Roo.MessageBox.wait(o.waitMsg, o.waitTitle || this.waitTitle || 'Please Wait...');
39954 afterAction : function(action, success){
39955 this.activeAction = null;
39956 var o = action.options;
39958 if(this.waitMsgTarget === true){
39960 }else if(this.waitMsgTarget){
39961 this.waitMsgTarget.unmask();
39963 Roo.MessageBox.updateProgress(1);
39964 Roo.MessageBox.hide();
39971 Roo.callback(o.success, o.scope, [this, action]);
39972 this.fireEvent('actioncomplete', this, action);
39974 Roo.callback(o.failure, o.scope, [this, action]);
39975 this.fireEvent('actionfailed', this, action);
39980 * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
39981 * @param {String} id The value to search for
39984 findField : function(id){
39985 var field = this.items.get(id);
39987 this.items.each(function(f){
39988 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
39994 return field || null;
39998 * Add a secondary form to this one,
39999 * Used to provide tabbed forms. One form is primary, with hidden values
40000 * which mirror the elements from the other forms.
40002 * @param {Roo.form.Form} form to add.
40005 addForm : function(form){
40007 this.childForms.push(form);
40008 Roo.each(form.allItems, function (fe) {
40010 if (this.findField(fe.name)) { // already added..
40013 var add = new Roo.form.Hidden({
40016 add.render(this.el);
40023 * Mark fields in this form invalid in bulk.
40024 * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
40025 * @return {BasicForm} this
40027 markInvalid : function(errors){
40028 if(errors instanceof Array){
40029 for(var i = 0, len = errors.length; i < len; i++){
40030 var fieldError = errors[i];
40031 var f = this.findField(fieldError.id);
40033 f.markInvalid(fieldError.msg);
40039 if(typeof errors[id] != 'function' && (field = this.findField(id))){
40040 field.markInvalid(errors[id]);
40044 Roo.each(this.childForms || [], function (f) {
40045 f.markInvalid(errors);
40052 * Set values for fields in this form in bulk.
40053 * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
40054 * @return {BasicForm} this
40056 setValues : function(values){
40057 if(values instanceof Array){ // array of objects
40058 for(var i = 0, len = values.length; i < len; i++){
40060 var f = this.findField(v.id);
40062 f.setValue(v.value);
40063 if(this.trackResetOnLoad){
40064 f.originalValue = f.getValue();
40068 }else{ // object hash
40071 if(typeof values[id] != 'function' && (field = this.findField(id))){
40073 if (field.setFromData &&
40074 field.valueField &&
40075 field.displayField &&
40076 // combos' with local stores can
40077 // be queried via setValue()
40078 // to set their value..
40079 (field.store && !field.store.isLocal)
40083 sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
40084 sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
40085 field.setFromData(sd);
40088 field.setValue(values[id]);
40092 if(this.trackResetOnLoad){
40093 field.originalValue = field.getValue();
40099 Roo.each(this.childForms || [], function (f) {
40100 f.setValues(values);
40107 * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
40108 * they are returned as an array.
40109 * @param {Boolean} asString
40112 getValues : function(asString){
40113 if (this.childForms) {
40114 // copy values from the child forms
40115 Roo.each(this.childForms, function (f) {
40117 Roo.each(f.allFields, function (e) {
40118 if (e.name && e.getValue && this.findField(e.name)) {
40119 this.findField(e.name).setValue(e.getValue());
40128 var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
40129 if(asString === true){
40132 return Roo.urlDecode(fs);
40136 * Clears all invalid messages in this form.
40137 * @return {BasicForm} this
40139 clearInvalid : function(){
40140 this.items.each(function(f){
40144 Roo.each(this.childForms || [], function (f) {
40153 * Resets this form.
40154 * @return {BasicForm} this
40156 reset : function(){
40157 this.items.each(function(f){
40161 Roo.each(this.childForms || [], function (f) {
40170 * Add Roo.form components to this form.
40171 * @param {Field} field1
40172 * @param {Field} field2 (optional)
40173 * @param {Field} etc (optional)
40174 * @return {BasicForm} this
40177 this.items.addAll(Array.prototype.slice.call(arguments, 0));
40183 * Removes a field from the items collection (does NOT remove its markup).
40184 * @param {Field} field
40185 * @return {BasicForm} this
40187 remove : function(field){
40188 this.items.remove(field);
40193 * Looks at the fields in this form, checks them for an id attribute,
40194 * and calls applyTo on the existing dom element with that id.
40195 * @return {BasicForm} this
40197 render : function(){
40198 this.items.each(function(f){
40199 if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
40207 * Calls {@link Ext#apply} for all fields in this form with the passed object.
40208 * @param {Object} values
40209 * @return {BasicForm} this
40211 applyToFields : function(o){
40212 this.items.each(function(f){
40219 * Calls {@link Ext#applyIf} for all field in this form with the passed object.
40220 * @param {Object} values
40221 * @return {BasicForm} this
40223 applyIfToFields : function(o){
40224 this.items.each(function(f){
40232 Roo.BasicForm = Roo.form.BasicForm;/*
40234 * Ext JS Library 1.1.1
40235 * Copyright(c) 2006-2007, Ext JS, LLC.
40237 * Originally Released Under LGPL - original licence link has changed is not relivant.
40240 * <script type="text/javascript">
40244 * @class Roo.form.Form
40245 * @extends Roo.form.BasicForm
40246 * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
40248 * @param {Object} config Configuration options
40250 Roo.form.Form = function(config){
40252 if (config.items) {
40253 xitems = config.items;
40254 delete config.items;
40258 Roo.form.Form.superclass.constructor.call(this, null, config);
40259 this.url = this.url || this.action;
40261 this.root = new Roo.form.Layout(Roo.applyIf({
40265 this.active = this.root;
40267 * Array of all the buttons that have been added to this form via {@link addButton}
40271 this.allItems = [];
40274 * @event clientvalidation
40275 * If the monitorValid config option is true, this event fires repetitively to notify of valid state
40276 * @param {Form} this
40277 * @param {Boolean} valid true if the form has passed client-side validation
40279 clientvalidation: true,
40282 * Fires when the form is rendered
40283 * @param {Roo.form.Form} form
40288 Roo.each(xitems, this.addxtype, this);
40294 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
40296 * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
40299 * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
40302 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
40304 buttonAlign:'center',
40307 * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
40312 * @cfg {String} labelAlign Valid values are "left," "top" and "right" (defaults to "left").
40313 * This property cascades to child containers if not set.
40318 * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
40319 * fires a looping event with that state. This is required to bind buttons to the valid
40320 * state using the config value formBind:true on the button.
40322 monitorValid : false,
40325 * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
40331 * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
40332 * fields are added and the column is closed. If no fields are passed the column remains open
40333 * until end() is called.
40334 * @param {Object} config The config to pass to the column
40335 * @param {Field} field1 (optional)
40336 * @param {Field} field2 (optional)
40337 * @param {Field} etc (optional)
40338 * @return Column The column container object
40340 column : function(c){
40341 var col = new Roo.form.Column(c);
40343 if(arguments.length > 1){ // duplicate code required because of Opera
40344 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
40351 * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
40352 * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
40353 * until end() is called.
40354 * @param {Object} config The config to pass to the fieldset
40355 * @param {Field} field1 (optional)
40356 * @param {Field} field2 (optional)
40357 * @param {Field} etc (optional)
40358 * @return FieldSet The fieldset container object
40360 fieldset : function(c){
40361 var fs = new Roo.form.FieldSet(c);
40363 if(arguments.length > 1){ // duplicate code required because of Opera
40364 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
40371 * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
40372 * fields are added and the container is closed. If no fields are passed the container remains open
40373 * until end() is called.
40374 * @param {Object} config The config to pass to the Layout
40375 * @param {Field} field1 (optional)
40376 * @param {Field} field2 (optional)
40377 * @param {Field} etc (optional)
40378 * @return Layout The container object
40380 container : function(c){
40381 var l = new Roo.form.Layout(c);
40383 if(arguments.length > 1){ // duplicate code required because of Opera
40384 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
40391 * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
40392 * @param {Object} container A Roo.form.Layout or subclass of Layout
40393 * @return {Form} this
40395 start : function(c){
40396 // cascade label info
40397 Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
40398 this.active.stack.push(c);
40399 c.ownerCt = this.active;
40405 * Closes the current open container
40406 * @return {Form} this
40409 if(this.active == this.root){
40412 this.active = this.active.ownerCt;
40417 * Add Roo.form components to the current open container (e.g. column, fieldset, etc.). Fields added via this method
40418 * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
40419 * as the label of the field.
40420 * @param {Field} field1
40421 * @param {Field} field2 (optional)
40422 * @param {Field} etc. (optional)
40423 * @return {Form} this
40426 this.active.stack.push.apply(this.active.stack, arguments);
40427 this.allItems.push.apply(this.allItems,arguments);
40429 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
40430 if(a[i].isFormField){
40435 Roo.form.Form.superclass.add.apply(this, r);
40445 * Find any element that has been added to a form, using it's ID or name
40446 * This can include framesets, columns etc. along with regular fields..
40447 * @param {String} id - id or name to find.
40449 * @return {Element} e - or false if nothing found.
40451 findbyId : function(id)
40457 Ext.each(this.allItems, function(f){
40458 if (f.id == id || f.name == id ){
40469 * Render this form into the passed container. This should only be called once!
40470 * @param {String/HTMLElement/Element} container The element this component should be rendered into
40471 * @return {Form} this
40473 render : function(ct){
40475 var o = this.autoCreate || {
40477 method : this.method || 'POST',
40478 id : this.id || Roo.id()
40480 this.initEl(ct.createChild(o));
40482 this.root.render(this.el);
40484 this.items.each(function(f){
40485 f.render('x-form-el-'+f.id);
40488 if(this.buttons.length > 0){
40489 // tables are required to maintain order and for correct IE layout
40490 var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
40491 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
40492 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
40494 var tr = tb.getElementsByTagName('tr')[0];
40495 for(var i = 0, len = this.buttons.length; i < len; i++) {
40496 var b = this.buttons[i];
40497 var td = document.createElement('td');
40498 td.className = 'x-form-btn-td';
40499 b.render(tr.appendChild(td));
40502 if(this.monitorValid){ // initialize after render
40503 this.startMonitoring();
40505 this.fireEvent('rendered', this);
40510 * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
40511 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
40512 * object or a valid Roo.DomHelper element config
40513 * @param {Function} handler The function called when the button is clicked
40514 * @param {Object} scope (optional) The scope of the handler function
40515 * @return {Roo.Button}
40517 addButton : function(config, handler, scope){
40521 minWidth: this.minButtonWidth,
40524 if(typeof config == "string"){
40527 Roo.apply(bc, config);
40529 var btn = new Roo.Button(null, bc);
40530 this.buttons.push(btn);
40535 * Adds a series of form elements (using the xtype property as the factory method.
40536 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
40537 * @param {Object} config
40540 addxtype : function()
40542 var ar = Array.prototype.slice.call(arguments, 0);
40544 for(var i = 0; i < ar.length; i++) {
40546 continue; // skip -- if this happends something invalid got sent, we
40547 // should ignore it, as basically that interface element will not show up
40548 // and that should be pretty obvious!!
40551 if (Roo.form[ar[i].xtype]) {
40553 var fe = Roo.factory(ar[i], Roo.form);
40559 fe.store.form = this;
40564 this.allItems.push(fe);
40565 if (fe.items && fe.addxtype) {
40566 fe.addxtype.apply(fe, fe.items);
40576 // console.log('adding ' + ar[i].xtype);
40578 if (ar[i].xtype == 'Button') {
40579 //console.log('adding button');
40580 //console.log(ar[i]);
40581 this.addButton(ar[i]);
40582 this.allItems.push(fe);
40586 if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
40587 alert('end is not supported on xtype any more, use items');
40589 // //console.log('adding end');
40597 * Starts monitoring of the valid state of this form. Usually this is done by passing the config
40598 * option "monitorValid"
40600 startMonitoring : function(){
40603 Roo.TaskMgr.start({
40604 run : this.bindHandler,
40605 interval : this.monitorPoll || 200,
40612 * Stops monitoring of the valid state of this form
40614 stopMonitoring : function(){
40615 this.bound = false;
40619 bindHandler : function(){
40621 return false; // stops binding
40624 this.items.each(function(f){
40625 if(!f.isValid(true)){
40630 for(var i = 0, len = this.buttons.length; i < len; i++){
40631 var btn = this.buttons[i];
40632 if(btn.formBind === true && btn.disabled === valid){
40633 btn.setDisabled(!valid);
40636 this.fireEvent('clientvalidation', this, valid);
40650 Roo.Form = Roo.form.Form;
40653 * Ext JS Library 1.1.1
40654 * Copyright(c) 2006-2007, Ext JS, LLC.
40656 * Originally Released Under LGPL - original licence link has changed is not relivant.
40659 * <script type="text/javascript">
40663 * @class Roo.form.Action
40664 * Internal Class used to handle form actions
40666 * @param {Roo.form.BasicForm} el The form element or its id
40667 * @param {Object} config Configuration options
40671 // define the action interface
40672 Roo.form.Action = function(form, options){
40674 this.options = options || {};
40677 * Client Validation Failed
40680 Roo.form.Action.CLIENT_INVALID = 'client';
40682 * Server Validation Failed
40685 Roo.form.Action.SERVER_INVALID = 'server';
40687 * Connect to Server Failed
40690 Roo.form.Action.CONNECT_FAILURE = 'connect';
40692 * Reading Data from Server Failed
40695 Roo.form.Action.LOAD_FAILURE = 'load';
40697 Roo.form.Action.prototype = {
40699 failureType : undefined,
40700 response : undefined,
40701 result : undefined,
40703 // interface method
40704 run : function(options){
40708 // interface method
40709 success : function(response){
40713 // interface method
40714 handleResponse : function(response){
40718 // default connection failure
40719 failure : function(response){
40720 this.response = response;
40721 this.failureType = Roo.form.Action.CONNECT_FAILURE;
40722 this.form.afterAction(this, false);
40725 processResponse : function(response){
40726 this.response = response;
40727 if(!response.responseText){
40730 this.result = this.handleResponse(response);
40731 return this.result;
40734 // utility functions used internally
40735 getUrl : function(appendParams){
40736 var url = this.options.url || this.form.url || this.form.el.dom.action;
40738 var p = this.getParams();
40740 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
40746 getMethod : function(){
40747 return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
40750 getParams : function(){
40751 var bp = this.form.baseParams;
40752 var p = this.options.params;
40754 if(typeof p == "object"){
40755 p = Roo.urlEncode(Roo.applyIf(p, bp));
40756 }else if(typeof p == 'string' && bp){
40757 p += '&' + Roo.urlEncode(bp);
40760 p = Roo.urlEncode(bp);
40765 createCallback : function(){
40767 success: this.success,
40768 failure: this.failure,
40770 timeout: (this.form.timeout*1000),
40771 upload: this.form.fileUpload ? this.success : undefined
40776 Roo.form.Action.Submit = function(form, options){
40777 Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
40780 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
40784 var o = this.options;
40785 var method = this.getMethod();
40786 var isPost = method == 'POST';
40787 if(o.clientValidation === false || this.form.isValid()){
40788 Roo.Ajax.request(Roo.apply(this.createCallback(), {
40789 form:this.form.el.dom,
40790 url:this.getUrl(!isPost),
40792 params:isPost ? this.getParams() : null,
40793 isUpload: this.form.fileUpload
40796 }else if (o.clientValidation !== false){ // client validation failed
40797 this.failureType = Roo.form.Action.CLIENT_INVALID;
40798 this.form.afterAction(this, false);
40802 success : function(response){
40803 var result = this.processResponse(response);
40804 if(result === true || result.success){
40805 this.form.afterAction(this, true);
40809 this.form.markInvalid(result.errors);
40810 this.failureType = Roo.form.Action.SERVER_INVALID;
40812 this.form.afterAction(this, false);
40815 handleResponse : function(response){
40816 if(this.form.errorReader){
40817 var rs = this.form.errorReader.read(response);
40820 for(var i = 0, len = rs.records.length; i < len; i++) {
40821 var r = rs.records[i];
40822 errors[i] = r.data;
40825 if(errors.length < 1){
40829 success : rs.success,
40835 ret = Roo.decode(response.responseText);
40839 errorMsg: "Failed to read server message: " + response.responseText,
40849 Roo.form.Action.Load = function(form, options){
40850 Roo.form.Action.Load.superclass.constructor.call(this, form, options);
40851 this.reader = this.form.reader;
40854 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
40858 Roo.Ajax.request(Roo.apply(
40859 this.createCallback(), {
40860 method:this.getMethod(),
40861 url:this.getUrl(false),
40862 params:this.getParams()
40866 success : function(response){
40867 var result = this.processResponse(response);
40868 if(result === true || !result.success || !result.data){
40869 this.failureType = Roo.form.Action.LOAD_FAILURE;
40870 this.form.afterAction(this, false);
40873 this.form.clearInvalid();
40874 this.form.setValues(result.data);
40875 this.form.afterAction(this, true);
40878 handleResponse : function(response){
40879 if(this.form.reader){
40880 var rs = this.form.reader.read(response);
40881 var data = rs.records && rs.records[0] ? rs.records[0].data : null;
40883 success : rs.success,
40887 return Roo.decode(response.responseText);
40891 Roo.form.Action.ACTION_TYPES = {
40892 'load' : Roo.form.Action.Load,
40893 'submit' : Roo.form.Action.Submit
40896 * Ext JS Library 1.1.1
40897 * Copyright(c) 2006-2007, Ext JS, LLC.
40899 * Originally Released Under LGPL - original licence link has changed is not relivant.
40902 * <script type="text/javascript">
40906 * @class Roo.form.Layout
40907 * @extends Roo.Component
40908 * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
40910 * @param {Object} config Configuration options
40912 Roo.form.Layout = function(config){
40914 if (config.items) {
40915 xitems = config.items;
40916 delete config.items;
40918 Roo.form.Layout.superclass.constructor.call(this, config);
40920 Roo.each(xitems, this.addxtype, this);
40924 Roo.extend(Roo.form.Layout, Roo.Component, {
40926 * @cfg {String/Object} autoCreate
40927 * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
40930 * @cfg {String/Object/Function} style
40931 * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
40932 * a function which returns such a specification.
40935 * @cfg {String} labelAlign
40936 * Valid values are "left," "top" and "right" (defaults to "left")
40939 * @cfg {Number} labelWidth
40940 * Fixed width in pixels of all field labels (defaults to undefined)
40943 * @cfg {Boolean} clear
40944 * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
40948 * @cfg {String} labelSeparator
40949 * The separator to use after field labels (defaults to ':')
40951 labelSeparator : ':',
40953 * @cfg {Boolean} hideLabels
40954 * True to suppress the display of field labels in this layout (defaults to false)
40956 hideLabels : false,
40959 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
40964 onRender : function(ct, position){
40965 if(this.el){ // from markup
40966 this.el = Roo.get(this.el);
40967 }else { // generate
40968 var cfg = this.getAutoCreate();
40969 this.el = ct.createChild(cfg, position);
40972 this.el.applyStyles(this.style);
40974 if(this.labelAlign){
40975 this.el.addClass('x-form-label-'+this.labelAlign);
40977 if(this.hideLabels){
40978 this.labelStyle = "display:none";
40979 this.elementStyle = "padding-left:0;";
40981 if(typeof this.labelWidth == 'number'){
40982 this.labelStyle = "width:"+this.labelWidth+"px;";
40983 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
40985 if(this.labelAlign == 'top'){
40986 this.labelStyle = "width:auto;";
40987 this.elementStyle = "padding-left:0;";
40990 var stack = this.stack;
40991 var slen = stack.length;
40993 if(!this.fieldTpl){
40994 var t = new Roo.Template(
40995 '<div class="x-form-item {5}">',
40996 '<label for="{0}" style="{2}">{1}{4}</label>',
40997 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
40999 '</div><div class="x-form-clear-left"></div>'
41001 t.disableFormats = true;
41003 Roo.form.Layout.prototype.fieldTpl = t;
41005 for(var i = 0; i < slen; i++) {
41006 if(stack[i].isFormField){
41007 this.renderField(stack[i]);
41009 this.renderComponent(stack[i]);
41014 this.el.createChild({cls:'x-form-clear'});
41019 renderField : function(f){
41020 f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
41023 f.labelStyle||this.labelStyle||'', //2
41024 this.elementStyle||'', //3
41025 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
41026 f.itemCls||this.itemCls||'' //5
41027 ], true).getPrevSibling());
41031 renderComponent : function(c){
41032 c.render(c.isLayout ? this.el : this.el.createChild());
41035 * Adds a object form elements (using the xtype property as the factory method.)
41036 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column
41037 * @param {Object} config
41039 addxtype : function(o)
41041 // create the lement.
41042 o.form = this.form;
41043 var fe = Roo.factory(o, Roo.form);
41044 this.form.allItems.push(fe);
41045 this.stack.push(fe);
41047 if (fe.isFormField) {
41048 this.form.items.add(fe);
41056 * @class Roo.form.Column
41057 * @extends Roo.form.Layout
41058 * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
41060 * @param {Object} config Configuration options
41062 Roo.form.Column = function(config){
41063 Roo.form.Column.superclass.constructor.call(this, config);
41066 Roo.extend(Roo.form.Column, Roo.form.Layout, {
41068 * @cfg {Number/String} width
41069 * The fixed width of the column in pixels or CSS value (defaults to "auto")
41072 * @cfg {String/Object} autoCreate
41073 * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
41077 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
41080 onRender : function(ct, position){
41081 Roo.form.Column.superclass.onRender.call(this, ct, position);
41083 this.el.setWidth(this.width);
41090 * @class Roo.form.Row
41091 * @extends Roo.form.Layout
41092 * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
41094 * @param {Object} config Configuration options
41098 Roo.form.Row = function(config){
41099 Roo.form.Row.superclass.constructor.call(this, config);
41102 Roo.extend(Roo.form.Row, Roo.form.Layout, {
41104 * @cfg {Number/String} width
41105 * The fixed width of the column in pixels or CSS value (defaults to "auto")
41108 * @cfg {Number/String} height
41109 * The fixed height of the column in pixels or CSS value (defaults to "auto")
41111 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
41115 onRender : function(ct, position){
41116 //console.log('row render');
41118 var t = new Roo.Template(
41119 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
41120 '<label for="{0}" style="{2}">{1}{4}</label>',
41121 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
41125 t.disableFormats = true;
41127 Roo.form.Layout.prototype.rowTpl = t;
41129 this.fieldTpl = this.rowTpl;
41131 //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
41132 var labelWidth = 100;
41134 if ((this.labelAlign != 'top')) {
41135 if (typeof this.labelWidth == 'number') {
41136 labelWidth = this.labelWidth
41138 this.padWidth = 20 + labelWidth;
41142 Roo.form.Column.superclass.onRender.call(this, ct, position);
41144 this.el.setWidth(this.width);
41147 this.el.setHeight(this.height);
41152 renderField : function(f){
41153 f.fieldEl = this.fieldTpl.append(this.el, [
41154 f.id, f.fieldLabel,
41155 f.labelStyle||this.labelStyle||'',
41156 this.elementStyle||'',
41157 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
41158 f.itemCls||this.itemCls||'',
41159 f.width ? f.width + this.padWidth : 160 + this.padWidth
41166 * @class Roo.form.FieldSet
41167 * @extends Roo.form.Layout
41168 * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
41170 * @param {Object} config Configuration options
41172 Roo.form.FieldSet = function(config){
41173 Roo.form.FieldSet.superclass.constructor.call(this, config);
41176 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
41178 * @cfg {String} legend
41179 * The text to display as the legend for the FieldSet (defaults to '')
41182 * @cfg {String/Object} autoCreate
41183 * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
41187 defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
41190 onRender : function(ct, position){
41191 Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
41193 this.setLegend(this.legend);
41198 setLegend : function(text){
41200 this.el.child('legend').update(text);
41205 * Ext JS Library 1.1.1
41206 * Copyright(c) 2006-2007, Ext JS, LLC.
41208 * Originally Released Under LGPL - original licence link has changed is not relivant.
41211 * <script type="text/javascript">
41214 * @class Roo.form.VTypes
41215 * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
41218 Roo.form.VTypes = function(){
41219 // closure these in so they are only created once.
41220 var alpha = /^[a-zA-Z_]+$/;
41221 var alphanum = /^[a-zA-Z0-9_]+$/;
41222 var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/;
41223 var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
41225 // All these messages and functions are configurable
41228 * The function used to validate email addresses
41229 * @param {String} value The email address
41231 'email' : function(v){
41232 return email.test(v);
41235 * The error text to display when the email validation function returns false
41238 'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
41240 * The keystroke filter mask to be applied on email input
41243 'emailMask' : /[a-z0-9_\.\-@]/i,
41246 * The function used to validate URLs
41247 * @param {String} value The URL
41249 'url' : function(v){
41250 return url.test(v);
41253 * The error text to display when the url validation function returns false
41256 'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
41259 * The function used to validate alpha values
41260 * @param {String} value The value
41262 'alpha' : function(v){
41263 return alpha.test(v);
41266 * The error text to display when the alpha validation function returns false
41269 'alphaText' : 'This field should only contain letters and _',
41271 * The keystroke filter mask to be applied on alpha input
41274 'alphaMask' : /[a-z_]/i,
41277 * The function used to validate alphanumeric values
41278 * @param {String} value The value
41280 'alphanum' : function(v){
41281 return alphanum.test(v);
41284 * The error text to display when the alphanumeric validation function returns false
41287 'alphanumText' : 'This field should only contain letters, numbers and _',
41289 * The keystroke filter mask to be applied on alphanumeric input
41292 'alphanumMask' : /[a-z0-9_]/i
41294 }();//<script type="text/javascript">
41297 * @class Roo.form.FCKeditor
41298 * @extends Roo.form.TextArea
41299 * Wrapper around the FCKEditor http://www.fckeditor.net
41301 * Creates a new FCKeditor
41302 * @param {Object} config Configuration options
41304 Roo.form.FCKeditor = function(config){
41305 Roo.form.FCKeditor.superclass.constructor.call(this, config);
41308 * @event editorinit
41309 * Fired when the editor is initialized - you can add extra handlers here..
41310 * @param {FCKeditor} this
41311 * @param {Object} the FCK object.
41318 Roo.form.FCKeditor.editors = { };
41319 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
41321 //defaultAutoCreate : {
41322 // tag : "textarea",style : "width:100px;height:60px;" ,autocomplete : "off"
41326 * @cfg {Object} fck options - see fck manual for details.
41331 * @cfg {Object} fck toolbar set (Basic or Default)
41333 toolbarSet : 'Basic',
41335 * @cfg {Object} fck BasePath
41337 basePath : '/fckeditor/',
41345 onRender : function(ct, position)
41348 this.defaultAutoCreate = {
41350 style:"width:300px;height:60px;",
41351 autocomplete: "off"
41354 Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
41357 this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
41358 if(this.preventScrollbars){
41359 this.el.setStyle("overflow", "hidden");
41361 this.el.setHeight(this.growMin);
41364 //console.log('onrender' + this.getId() );
41365 Roo.form.FCKeditor.editors[this.getId()] = this;
41368 this.replaceTextarea() ;
41372 getEditor : function() {
41373 return this.fckEditor;
41376 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
41377 * @param {Mixed} value The value to set
41381 setValue : function(value)
41383 //console.log('setValue: ' + value);
41385 if(typeof(value) == 'undefined') { // not sure why this is happending...
41388 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
41390 //if(!this.el || !this.getEditor()) {
41391 // this.value = value;
41392 //this.setValue.defer(100,this,[value]);
41396 if(!this.getEditor()) {
41400 this.getEditor().SetData(value);
41407 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
41408 * @return {Mixed} value The field value
41410 getValue : function()
41413 if (this.frame && this.frame.dom.style.display == 'none') {
41414 return Roo.form.FCKeditor.superclass.getValue.call(this);
41417 if(!this.el || !this.getEditor()) {
41419 // this.getValue.defer(100,this);
41424 var value=this.getEditor().GetData();
41425 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
41426 return Roo.form.FCKeditor.superclass.getValue.call(this);
41432 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
41433 * @return {Mixed} value The field value
41435 getRawValue : function()
41437 if (this.frame && this.frame.dom.style.display == 'none') {
41438 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
41441 if(!this.el || !this.getEditor()) {
41442 //this.getRawValue.defer(100,this);
41449 var value=this.getEditor().GetData();
41450 Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
41451 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
41455 setSize : function(w,h) {
41459 //if (this.frame && this.frame.dom.style.display == 'none') {
41460 // Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
41463 //if(!this.el || !this.getEditor()) {
41464 // this.setSize.defer(100,this, [w,h]);
41470 Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
41472 this.frame.dom.setAttribute('width', w);
41473 this.frame.dom.setAttribute('height', h);
41474 this.frame.setSize(w,h);
41478 toggleSourceEdit : function(value) {
41482 this.el.dom.style.display = value ? '' : 'none';
41483 this.frame.dom.style.display = value ? 'none' : '';
41488 focus: function(tag)
41490 if (this.frame.dom.style.display == 'none') {
41491 return Roo.form.FCKeditor.superclass.focus.call(this);
41493 if(!this.el || !this.getEditor()) {
41494 this.focus.defer(100,this, [tag]);
41501 var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
41502 this.getEditor().Focus();
41504 if (!this.getEditor().Selection.GetSelection()) {
41505 this.focus.defer(100,this, [tag]);
41510 var r = this.getEditor().EditorDocument.createRange();
41511 r.setStart(tgs[0],0);
41512 r.setEnd(tgs[0],0);
41513 this.getEditor().Selection.GetSelection().removeAllRanges();
41514 this.getEditor().Selection.GetSelection().addRange(r);
41515 this.getEditor().Focus();
41522 replaceTextarea : function()
41524 if ( document.getElementById( this.getId() + '___Frame' ) )
41526 //if ( !this.checkBrowser || this._isCompatibleBrowser() )
41528 // We must check the elements firstly using the Id and then the name.
41529 var oTextarea = document.getElementById( this.getId() );
41531 var colElementsByName = document.getElementsByName( this.getId() ) ;
41533 oTextarea.style.display = 'none' ;
41535 if ( oTextarea.tabIndex ) {
41536 this.TabIndex = oTextarea.tabIndex ;
41539 this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
41540 this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
41541 this.frame = Roo.get(this.getId() + '___Frame')
41544 _getConfigHtml : function()
41548 for ( var o in this.fckconfig ) {
41549 sConfig += sConfig.length > 0 ? '&' : '';
41550 sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
41553 return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
41557 _getIFrameHtml : function()
41559 var sFile = 'fckeditor.html' ;
41560 /* no idea what this is about..
41563 if ( (/fcksource=true/i).test( window.top.location.search ) )
41564 sFile = 'fckeditor.original.html' ;
41569 var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
41570 sLink += this.toolbarSet ? ( '&Toolbar=' + this.toolbarSet) : '';
41573 var html = '<iframe id="' + this.getId() +
41574 '___Frame" src="' + sLink +
41575 '" width="' + this.width +
41576 '" height="' + this.height + '"' +
41577 (this.tabIndex ? ' tabindex="' + this.tabIndex + '"' :'' ) +
41578 ' frameborder="0" scrolling="no"></iframe>' ;
41583 _insertHtmlBefore : function( html, element )
41585 if ( element.insertAdjacentHTML ) {
41587 element.insertAdjacentHTML( 'beforeBegin', html ) ;
41589 var oRange = document.createRange() ;
41590 oRange.setStartBefore( element ) ;
41591 var oFragment = oRange.createContextualFragment( html );
41592 element.parentNode.insertBefore( oFragment, element ) ;
41605 //Roo.reg('fckeditor', Roo.form.FCKeditor);
41607 function FCKeditor_OnComplete(editorInstance){
41608 var f = Roo.form.FCKeditor.editors[editorInstance.Name];
41609 f.fckEditor = editorInstance;
41610 //console.log("loaded");
41611 f.fireEvent('editorinit', f, editorInstance);
41631 //<script type="text/javascript">
41633 * @class Roo.form.GridField
41634 * @extends Roo.form.Field
41635 * Embed a grid (or editable grid into a form)
41638 * Creates a new GridField
41639 * @param {Object} config Configuration options
41641 Roo.form.GridField = function(config){
41642 Roo.form.GridField.superclass.constructor.call(this, config);
41646 Roo.extend(Roo.form.GridField, Roo.form.Field, {
41648 * @cfg {Number} width - used to restrict width of grid..
41652 * @cfg {Number} height - used to restrict height of grid..
41656 * @cfg {Object} xgrid (xtype'd description of grid) Grid or EditorGrid
41660 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
41661 * {tag: "input", type: "checkbox", autocomplete: "off"})
41663 // defaultAutoCreate : { tag: 'div' },
41664 defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
41666 * @cfg {String} addTitle Text to include for adding a title.
41670 onResize : function(){
41671 Roo.form.Field.superclass.onResize.apply(this, arguments);
41674 initEvents : function(){
41675 // Roo.form.Checkbox.superclass.initEvents.call(this);
41676 // has no events...
41681 getResizeEl : function(){
41685 getPositionEl : function(){
41690 onRender : function(ct, position){
41692 this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
41693 var style = this.style;
41696 Roo.form.DisplayImage.superclass.onRender.call(this, ct, position);
41697 this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
41698 this.viewEl = this.wrap.createChild({ tag: 'div' });
41700 this.viewEl.applyStyles(style);
41703 this.viewEl.setWidth(this.width);
41706 this.viewEl.setHeight(this.height);
41708 //if(this.inputValue !== undefined){
41709 //this.setValue(this.value);
41712 this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
41715 this.grid.render();
41716 this.grid.getDataSource().on('remove', this.refreshValue, this);
41717 this.grid.getDataSource().on('update', this.refreshValue, this);
41718 this.grid.on('afteredit', this.refreshValue, this);
41724 * Sets the value of the item.
41725 * @param {String} either an object or a string..
41727 setValue : function(v){
41729 v = v || []; // empty set..
41730 // this does not seem smart - it really only affects memoryproxy grids..
41731 if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
41732 var ds = this.grid.getDataSource();
41733 // assumes a json reader..
41735 data[ds.reader.meta.root ] = typeof(v) == 'string' ? Roo.decode(v) : v;
41736 ds.loadData( data);
41738 Roo.form.GridField.superclass.setValue.call(this, v);
41739 this.refreshValue();
41740 // should load data in the grid really....
41744 refreshValue: function() {
41746 this.grid.getDataSource().each(function(r) {
41749 this.el.dom.value = Roo.encode(val);
41755 });//<script type="text/javasscript">
41759 * @class Roo.DDView
41760 * A DnD enabled version of Roo.View.
41761 * @param {Element/String} container The Element in which to create the View.
41762 * @param {String} tpl The template string used to create the markup for each element of the View
41763 * @param {Object} config The configuration properties. These include all the config options of
41764 * {@link Roo.View} plus some specific to this class.<br>
41766 * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
41767 * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
41769 * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
41770 .x-view-drag-insert-above {
41771 border-top:1px dotted #3366cc;
41773 .x-view-drag-insert-below {
41774 border-bottom:1px dotted #3366cc;
41780 Roo.DDView = function(container, tpl, config) {
41781 Roo.DDView.superclass.constructor.apply(this, arguments);
41782 this.getEl().setStyle("outline", "0px none");
41783 this.getEl().unselectable();
41784 if (this.dragGroup) {
41785 this.setDraggable(this.dragGroup.split(","));
41787 if (this.dropGroup) {
41788 this.setDroppable(this.dropGroup.split(","));
41790 if (this.deletable) {
41791 this.setDeletable();
41793 this.isDirtyFlag = false;
41799 Roo.extend(Roo.DDView, Roo.View, {
41800 /** @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
41801 /** @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
41802 /** @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
41803 /** @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
41807 reset: Roo.emptyFn,
41809 clearInvalid: Roo.form.Field.prototype.clearInvalid,
41811 validate: function() {
41815 destroy: function() {
41816 this.purgeListeners();
41817 this.getEl.removeAllListeners();
41818 this.getEl().remove();
41819 if (this.dragZone) {
41820 if (this.dragZone.destroy) {
41821 this.dragZone.destroy();
41824 if (this.dropZone) {
41825 if (this.dropZone.destroy) {
41826 this.dropZone.destroy();
41831 /** Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
41832 getName: function() {
41836 /** Loads the View from a JSON string representing the Records to put into the Store. */
41837 setValue: function(v) {
41839 throw "DDView.setValue(). DDView must be constructed with a valid Store";
41842 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
41843 this.store.proxy = new Roo.data.MemoryProxy(data);
41847 /** @return {String} a parenthesised list of the ids of the Records in the View. */
41848 getValue: function() {
41850 this.store.each(function(rec) {
41851 result += rec.id + ',';
41853 return result.substr(0, result.length - 1) + ')';
41856 getIds: function() {
41857 var i = 0, result = new Array(this.store.getCount());
41858 this.store.each(function(rec) {
41859 result[i++] = rec.id;
41864 isDirty: function() {
41865 return this.isDirtyFlag;
41869 * Part of the Roo.dd.DropZone interface. If no target node is found, the
41870 * whole Element becomes the target, and this causes the drop gesture to append.
41872 getTargetFromEvent : function(e) {
41873 var target = e.getTarget();
41874 while ((target !== null) && (target.parentNode != this.el.dom)) {
41875 target = target.parentNode;
41878 target = this.el.dom.lastChild || this.el.dom;
41884 * Create the drag data which consists of an object which has the property "ddel" as
41885 * the drag proxy element.
41887 getDragData : function(e) {
41888 var target = this.findItemFromChild(e.getTarget());
41890 this.handleSelection(e);
41891 var selNodes = this.getSelectedNodes();
41894 copy: this.copy || (this.allowCopy && e.ctrlKey),
41898 var selectedIndices = this.getSelectedIndexes();
41899 for (var i = 0; i < selectedIndices.length; i++) {
41900 dragData.records.push(this.store.getAt(selectedIndices[i]));
41902 if (selNodes.length == 1) {
41903 dragData.ddel = target.cloneNode(true); // the div element
41905 var div = document.createElement('div'); // create the multi element drag "ghost"
41906 div.className = 'multi-proxy';
41907 for (var i = 0, len = selNodes.length; i < len; i++) {
41908 div.appendChild(selNodes[i].cloneNode(true));
41910 dragData.ddel = div;
41912 //console.log(dragData)
41913 //console.log(dragData.ddel.innerHTML)
41916 //console.log('nodragData')
41920 /** Specify to which ddGroup items in this DDView may be dragged. */
41921 setDraggable: function(ddGroup) {
41922 if (ddGroup instanceof Array) {
41923 Roo.each(ddGroup, this.setDraggable, this);
41926 if (this.dragZone) {
41927 this.dragZone.addToGroup(ddGroup);
41929 this.dragZone = new Roo.dd.DragZone(this.getEl(), {
41930 containerScroll: true,
41934 // Draggability implies selection. DragZone's mousedown selects the element.
41935 if (!this.multiSelect) { this.singleSelect = true; }
41937 // Wire the DragZone's handlers up to methods in *this*
41938 this.dragZone.getDragData = this.getDragData.createDelegate(this);
41942 /** Specify from which ddGroup this DDView accepts drops. */
41943 setDroppable: function(ddGroup) {
41944 if (ddGroup instanceof Array) {
41945 Roo.each(ddGroup, this.setDroppable, this);
41948 if (this.dropZone) {
41949 this.dropZone.addToGroup(ddGroup);
41951 this.dropZone = new Roo.dd.DropZone(this.getEl(), {
41952 containerScroll: true,
41956 // Wire the DropZone's handlers up to methods in *this*
41957 this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
41958 this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
41959 this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
41960 this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
41961 this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
41965 /** Decide whether to drop above or below a View node. */
41966 getDropPoint : function(e, n, dd){
41967 if (n == this.el.dom) { return "above"; }
41968 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
41969 var c = t + (b - t) / 2;
41970 var y = Roo.lib.Event.getPageY(e);
41978 onNodeEnter : function(n, dd, e, data){
41982 onNodeOver : function(n, dd, e, data){
41983 var pt = this.getDropPoint(e, n, dd);
41984 // set the insert point style on the target node
41985 var dragElClass = this.dropNotAllowed;
41988 if (pt == "above"){
41989 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
41990 targetElClass = "x-view-drag-insert-above";
41992 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
41993 targetElClass = "x-view-drag-insert-below";
41995 if (this.lastInsertClass != targetElClass){
41996 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
41997 this.lastInsertClass = targetElClass;
42000 return dragElClass;
42003 onNodeOut : function(n, dd, e, data){
42004 this.removeDropIndicators(n);
42007 onNodeDrop : function(n, dd, e, data){
42008 if (this.fireEvent("drop", this, n, dd, e, data) === false) {
42011 var pt = this.getDropPoint(e, n, dd);
42012 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
42013 if (pt == "below") { insertAt++; }
42014 for (var i = 0; i < data.records.length; i++) {
42015 var r = data.records[i];
42016 var dup = this.store.getById(r.id);
42017 if (dup && (dd != this.dragZone)) {
42018 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
42021 this.store.insert(insertAt++, r.copy());
42023 data.source.isDirtyFlag = true;
42025 this.store.insert(insertAt++, r);
42027 this.isDirtyFlag = true;
42030 this.dragZone.cachedTarget = null;
42034 removeDropIndicators : function(n){
42036 Roo.fly(n).removeClass([
42037 "x-view-drag-insert-above",
42038 "x-view-drag-insert-below"]);
42039 this.lastInsertClass = "_noclass";
42044 * Utility method. Add a delete option to the DDView's context menu.
42045 * @param {String} imageUrl The URL of the "delete" icon image.
42047 setDeletable: function(imageUrl) {
42048 if (!this.singleSelect && !this.multiSelect) {
42049 this.singleSelect = true;
42051 var c = this.getContextMenu();
42052 this.contextMenu.on("itemclick", function(item) {
42055 this.remove(this.getSelectedIndexes());
42059 this.contextMenu.add({
42066 /** Return the context menu for this DDView. */
42067 getContextMenu: function() {
42068 if (!this.contextMenu) {
42069 // Create the View's context menu
42070 this.contextMenu = new Roo.menu.Menu({
42071 id: this.id + "-contextmenu"
42073 this.el.on("contextmenu", this.showContextMenu, this);
42075 return this.contextMenu;
42078 disableContextMenu: function() {
42079 if (this.contextMenu) {
42080 this.el.un("contextmenu", this.showContextMenu, this);
42084 showContextMenu: function(e, item) {
42085 item = this.findItemFromChild(e.getTarget());
42088 this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
42089 this.contextMenu.showAt(e.getXY());
42094 * Remove {@link Roo.data.Record}s at the specified indices.
42095 * @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
42097 remove: function(selectedIndices) {
42098 selectedIndices = [].concat(selectedIndices);
42099 for (var i = 0; i < selectedIndices.length; i++) {
42100 var rec = this.store.getAt(selectedIndices[i]);
42101 this.store.remove(rec);
42106 * Double click fires the event, but also, if this is draggable, and there is only one other
42107 * related DropZone, it transfers the selected node.
42109 onDblClick : function(e){
42110 var item = this.findItemFromChild(e.getTarget());
42112 if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
42115 if (this.dragGroup) {
42116 var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
42117 while (targets.indexOf(this.dropZone) > -1) {
42118 targets.remove(this.dropZone);
42120 if (targets.length == 1) {
42121 this.dragZone.cachedTarget = null;
42122 var el = Roo.get(targets[0].getEl());
42123 var box = el.getBox(true);
42124 targets[0].onNodeDrop(el.dom, {
42126 xy: [box.x, box.y + box.height - 1]
42127 }, null, this.getDragData(e));
42133 handleSelection: function(e) {
42134 this.dragZone.cachedTarget = null;
42135 var item = this.findItemFromChild(e.getTarget());
42137 this.clearSelections(true);
42140 if (item && (this.multiSelect || this.singleSelect)){
42141 if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
42142 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
42143 }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
42144 this.unselect(item);
42146 this.select(item, this.multiSelect && e.ctrlKey);
42147 this.lastSelection = item;
42152 onItemClick : function(item, index, e){
42153 if(this.fireEvent("beforeclick", this, index, item, e) === false){
42159 unselect : function(nodeInfo, suppressEvent){
42160 var node = this.getNode(nodeInfo);
42161 if(node && this.isSelected(node)){
42162 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
42163 Roo.fly(node).removeClass(this.selectedClass);
42164 this.selections.remove(node);
42165 if(!suppressEvent){
42166 this.fireEvent("selectionchange", this, this.selections);
42174 * Ext JS Library 1.1.1
42175 * Copyright(c) 2006-2007, Ext JS, LLC.
42177 * Originally Released Under LGPL - original licence link has changed is not relivant.
42180 * <script type="text/javascript">
42184 * @class Roo.LayoutManager
42185 * @extends Roo.util.Observable
42186 * Base class for layout managers.
42188 Roo.LayoutManager = function(container, config){
42189 Roo.LayoutManager.superclass.constructor.call(this);
42190 this.el = Roo.get(container);
42191 // ie scrollbar fix
42192 if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
42193 document.body.scroll = "no";
42194 }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
42195 this.el.position('relative');
42197 this.id = this.el.id;
42198 this.el.addClass("x-layout-container");
42199 /** false to disable window resize monitoring @type Boolean */
42200 this.monitorWindowResize = true;
42205 * Fires when a layout is performed.
42206 * @param {Roo.LayoutManager} this
42210 * @event regionresized
42211 * Fires when the user resizes a region.
42212 * @param {Roo.LayoutRegion} region The resized region
42213 * @param {Number} newSize The new size (width for east/west, height for north/south)
42215 "regionresized" : true,
42217 * @event regioncollapsed
42218 * Fires when a region is collapsed.
42219 * @param {Roo.LayoutRegion} region The collapsed region
42221 "regioncollapsed" : true,
42223 * @event regionexpanded
42224 * Fires when a region is expanded.
42225 * @param {Roo.LayoutRegion} region The expanded region
42227 "regionexpanded" : true
42229 this.updating = false;
42230 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
42233 Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
42235 * Returns true if this layout is currently being updated
42236 * @return {Boolean}
42238 isUpdating : function(){
42239 return this.updating;
42243 * Suspend the LayoutManager from doing auto-layouts while
42244 * making multiple add or remove calls
42246 beginUpdate : function(){
42247 this.updating = true;
42251 * Restore auto-layouts and optionally disable the manager from performing a layout
42252 * @param {Boolean} noLayout true to disable a layout update
42254 endUpdate : function(noLayout){
42255 this.updating = false;
42261 layout: function(){
42265 onRegionResized : function(region, newSize){
42266 this.fireEvent("regionresized", region, newSize);
42270 onRegionCollapsed : function(region){
42271 this.fireEvent("regioncollapsed", region);
42274 onRegionExpanded : function(region){
42275 this.fireEvent("regionexpanded", region);
42279 * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
42280 * performs box-model adjustments.
42281 * @return {Object} The size as an object {width: (the width), height: (the height)}
42283 getViewSize : function(){
42285 if(this.el.dom != document.body){
42286 size = this.el.getSize();
42288 size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
42290 size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
42291 size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
42296 * Returns the Element this layout is bound to.
42297 * @return {Roo.Element}
42299 getEl : function(){
42304 * Returns the specified region.
42305 * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
42306 * @return {Roo.LayoutRegion}
42308 getRegion : function(target){
42309 return this.regions[target.toLowerCase()];
42312 onWindowResize : function(){
42313 if(this.monitorWindowResize){
42319 * Ext JS Library 1.1.1
42320 * Copyright(c) 2006-2007, Ext JS, LLC.
42322 * Originally Released Under LGPL - original licence link has changed is not relivant.
42325 * <script type="text/javascript">
42328 * @class Roo.BorderLayout
42329 * @extends Roo.LayoutManager
42330 * This class represents a common layout manager used in desktop applications. For screenshots and more details,
42331 * please see: <br><br>
42332 * <a href="http://www.jackslocum.com/yui/2006/10/19/cross-browser-web-20-layouts-with-yahoo-ui/">Cross Browser Layouts - Part 1</a><br>
42333 * <a href="http://www.jackslocum.com/yui/2006/10/28/cross-browser-web-20-layouts-part-2-ajax-feed-viewer-20/">Cross Browser Layouts - Part 2</a><br><br>
42336 var layout = new Roo.BorderLayout(document.body, {
42370 preferredTabWidth: 150
42375 var CP = Roo.ContentPanel;
42377 layout.beginUpdate();
42378 layout.add("north", new CP("north", "North"));
42379 layout.add("south", new CP("south", {title: "South", closable: true}));
42380 layout.add("west", new CP("west", {title: "West"}));
42381 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
42382 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
42383 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
42384 layout.getRegion("center").showPanel("center1");
42385 layout.endUpdate();
42388 <b>The container the layout is rendered into can be either the body element or any other element.
42389 If it is not the body element, the container needs to either be an absolute positioned element,
42390 or you will need to add "position:relative" to the css of the container. You will also need to specify
42391 the container size if it is not the body element.</b>
42394 * Create a new BorderLayout
42395 * @param {String/HTMLElement/Element} container The container this layout is bound to
42396 * @param {Object} config Configuration options
42398 Roo.BorderLayout = function(container, config){
42399 config = config || {};
42400 Roo.BorderLayout.superclass.constructor.call(this, container, config);
42401 this.factory = config.factory || Roo.BorderLayout.RegionFactory;
42402 for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
42403 var target = this.factory.validRegions[i];
42404 if(config[target]){
42405 this.addRegion(target, config[target]);
42410 Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
42412 * Creates and adds a new region if it doesn't already exist.
42413 * @param {String} target The target region key (north, south, east, west or center).
42414 * @param {Object} config The regions config object
42415 * @return {BorderLayoutRegion} The new region
42417 addRegion : function(target, config){
42418 if(!this.regions[target]){
42419 var r = this.factory.create(target, this, config);
42420 this.bindRegion(target, r);
42422 return this.regions[target];
42426 bindRegion : function(name, r){
42427 this.regions[name] = r;
42428 r.on("visibilitychange", this.layout, this);
42429 r.on("paneladded", this.layout, this);
42430 r.on("panelremoved", this.layout, this);
42431 r.on("invalidated", this.layout, this);
42432 r.on("resized", this.onRegionResized, this);
42433 r.on("collapsed", this.onRegionCollapsed, this);
42434 r.on("expanded", this.onRegionExpanded, this);
42438 * Performs a layout update.
42440 layout : function(){
42441 if(this.updating) return;
42442 var size = this.getViewSize();
42443 var w = size.width;
42444 var h = size.height;
42449 //var x = 0, y = 0;
42451 var rs = this.regions;
42452 var north = rs["north"];
42453 var south = rs["south"];
42454 var west = rs["west"];
42455 var east = rs["east"];
42456 var center = rs["center"];
42457 //if(this.hideOnLayout){ // not supported anymore
42458 //c.el.setStyle("display", "none");
42460 if(north && north.isVisible()){
42461 var b = north.getBox();
42462 var m = north.getMargins();
42463 b.width = w - (m.left+m.right);
42466 centerY = b.height + b.y + m.bottom;
42467 centerH -= centerY;
42468 north.updateBox(this.safeBox(b));
42470 if(south && south.isVisible()){
42471 var b = south.getBox();
42472 var m = south.getMargins();
42473 b.width = w - (m.left+m.right);
42475 var totalHeight = (b.height + m.top + m.bottom);
42476 b.y = h - totalHeight + m.top;
42477 centerH -= totalHeight;
42478 south.updateBox(this.safeBox(b));
42480 if(west && west.isVisible()){
42481 var b = west.getBox();
42482 var m = west.getMargins();
42483 b.height = centerH - (m.top+m.bottom);
42485 b.y = centerY + m.top;
42486 var totalWidth = (b.width + m.left + m.right);
42487 centerX += totalWidth;
42488 centerW -= totalWidth;
42489 west.updateBox(this.safeBox(b));
42491 if(east && east.isVisible()){
42492 var b = east.getBox();
42493 var m = east.getMargins();
42494 b.height = centerH - (m.top+m.bottom);
42495 var totalWidth = (b.width + m.left + m.right);
42496 b.x = w - totalWidth + m.left;
42497 b.y = centerY + m.top;
42498 centerW -= totalWidth;
42499 east.updateBox(this.safeBox(b));
42502 var m = center.getMargins();
42504 x: centerX + m.left,
42505 y: centerY + m.top,
42506 width: centerW - (m.left+m.right),
42507 height: centerH - (m.top+m.bottom)
42509 //if(this.hideOnLayout){
42510 //center.el.setStyle("display", "block");
42512 center.updateBox(this.safeBox(centerBox));
42515 this.fireEvent("layout", this);
42519 safeBox : function(box){
42520 box.width = Math.max(0, box.width);
42521 box.height = Math.max(0, box.height);
42526 * Adds a ContentPanel (or subclass) to this layout.
42527 * @param {String} target The target region key (north, south, east, west or center).
42528 * @param {Roo.ContentPanel} panel The panel to add
42529 * @return {Roo.ContentPanel} The added panel
42531 add : function(target, panel){
42533 target = target.toLowerCase();
42534 return this.regions[target].add(panel);
42538 * Remove a ContentPanel (or subclass) to this layout.
42539 * @param {String} target The target region key (north, south, east, west or center).
42540 * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
42541 * @return {Roo.ContentPanel} The removed panel
42543 remove : function(target, panel){
42544 target = target.toLowerCase();
42545 return this.regions[target].remove(panel);
42549 * Searches all regions for a panel with the specified id
42550 * @param {String} panelId
42551 * @return {Roo.ContentPanel} The panel or null if it wasn't found
42553 findPanel : function(panelId){
42554 var rs = this.regions;
42555 for(var target in rs){
42556 if(typeof rs[target] != "function"){
42557 var p = rs[target].getPanel(panelId);
42567 * Searches all regions for a panel with the specified id and activates (shows) it.
42568 * @param {String/ContentPanel} panelId The panels id or the panel itself
42569 * @return {Roo.ContentPanel} The shown panel or null
42571 showPanel : function(panelId) {
42572 var rs = this.regions;
42573 for(var target in rs){
42574 var r = rs[target];
42575 if(typeof r != "function"){
42576 if(r.hasPanel(panelId)){
42577 return r.showPanel(panelId);
42585 * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
42586 * @param {Roo.state.Provider} provider (optional) An alternate state provider
42588 restoreState : function(provider){
42590 provider = Roo.state.Manager;
42592 var sm = new Roo.LayoutStateManager();
42593 sm.init(this, provider);
42597 * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object. This config
42598 * object should contain properties for each region to add ContentPanels to, and each property's value should be
42599 * a valid ContentPanel config object. Example:
42601 // Create the main layout
42602 var layout = new Roo.BorderLayout('main-ct', {
42613 // Create and add multiple ContentPanels at once via configs
42616 id: 'source-files',
42618 title:'Ext Source Files',
42631 * @param {Object} regions An object containing ContentPanel configs by region name
42633 batchAdd : function(regions){
42634 this.beginUpdate();
42635 for(var rname in regions){
42636 var lr = this.regions[rname];
42638 this.addTypedPanels(lr, regions[rname]);
42645 addTypedPanels : function(lr, ps){
42646 if(typeof ps == 'string'){
42647 lr.add(new Roo.ContentPanel(ps));
42649 else if(ps instanceof Array){
42650 for(var i =0, len = ps.length; i < len; i++){
42651 this.addTypedPanels(lr, ps[i]);
42654 else if(!ps.events){ // raw config?
42656 delete ps.el; // prevent conflict
42657 lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
42659 else { // panel object assumed!
42664 * Adds a xtype elements to the layout.
42668 xtype : 'ContentPanel',
42675 xtype : 'NestedLayoutPanel',
42681 items : [ ... list of content panels or nested layout panels.. ]
42685 * @param {Object} cfg Xtype definition of item to add.
42687 addxtype : function(cfg)
42689 // basically accepts a pannel...
42690 // can accept a layout region..!?!?
42691 // console.log('BorderLayout add ' + cfg.xtype)
42693 if (!cfg.xtype.match(/Panel$/)) {
42697 var region = cfg.region;
42703 xitems = cfg.items;
42710 case 'ContentPanel': // ContentPanel (el, cfg)
42711 if(cfg.autoCreate) {
42712 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
42714 var el = this.el.createChild();
42715 ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
42718 this.add(region, ret);
42722 case 'TreePanel': // our new panel!
42723 cfg.el = this.el.createChild();
42724 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
42725 this.add(region, ret);
42728 case 'NestedLayoutPanel':
42729 // create a new Layout (which is a Border Layout...
42730 var el = this.el.createChild();
42731 var clayout = cfg.layout;
42733 clayout.items = clayout.items || [];
42734 // replace this exitems with the clayout ones..
42735 xitems = clayout.items;
42738 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
42739 cfg.background = false;
42741 var layout = new Roo.BorderLayout(el, clayout);
42743 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
42744 //console.log('adding nested layout panel ' + cfg.toSource());
42745 this.add(region, ret);
42751 // needs grid and region
42753 //var el = this.getRegion(region).el.createChild();
42754 var el = this.el.createChild();
42755 // create the grid first...
42757 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
42759 if (region == 'center' && this.active ) {
42760 cfg.background = false;
42762 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
42764 this.add(region, ret);
42765 if (cfg.background) {
42766 ret.on('activate', function(gp) {
42767 if (!gp.grid.rendered) {
42780 alert("Can not add '" + cfg.xtype + "' to BorderLayout");
42782 // GridPanel (grid, cfg)
42785 this.beginUpdate();
42787 Roo.each(xitems, function(i) {
42797 * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
42798 * the beginUpdate and endUpdate calls internally. The key to this method is the <b>panels</b> property that can be
42799 * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
42800 * during creation. The following code is equivalent to the constructor-based example at the beginning of this class:
42803 var CP = Roo.ContentPanel;
42805 var layout = Roo.BorderLayout.create({
42809 panels: [new CP("north", "North")]
42818 panels: [new CP("west", {title: "West"})]
42827 panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
42836 panels: [new CP("south", {title: "South", closable: true})]
42843 preferredTabWidth: 150,
42845 new CP("center1", {title: "Close Me", closable: true}),
42846 new CP("center2", {title: "Center Panel", closable: false})
42851 layout.getRegion("center").showPanel("center1");
42856 Roo.BorderLayout.create = function(config, targetEl){
42857 var layout = new Roo.BorderLayout(targetEl || document.body, config);
42858 layout.beginUpdate();
42859 var regions = Roo.BorderLayout.RegionFactory.validRegions;
42860 for(var j = 0, jlen = regions.length; j < jlen; j++){
42861 var lr = regions[j];
42862 if(layout.regions[lr] && config[lr].panels){
42863 var r = layout.regions[lr];
42864 var ps = config[lr].panels;
42865 layout.addTypedPanels(r, ps);
42868 layout.endUpdate();
42873 Roo.BorderLayout.RegionFactory = {
42875 validRegions : ["north","south","east","west","center"],
42878 create : function(target, mgr, config){
42879 target = target.toLowerCase();
42880 if(config.lightweight || config.basic){
42881 return new Roo.BasicLayoutRegion(mgr, config, target);
42885 return new Roo.NorthLayoutRegion(mgr, config);
42887 return new Roo.SouthLayoutRegion(mgr, config);
42889 return new Roo.EastLayoutRegion(mgr, config);
42891 return new Roo.WestLayoutRegion(mgr, config);
42893 return new Roo.CenterLayoutRegion(mgr, config);
42895 throw 'Layout region "'+target+'" not supported.';
42899 * Ext JS Library 1.1.1
42900 * Copyright(c) 2006-2007, Ext JS, LLC.
42902 * Originally Released Under LGPL - original licence link has changed is not relivant.
42905 * <script type="text/javascript">
42909 * @class Roo.BasicLayoutRegion
42910 * @extends Roo.util.Observable
42911 * This class represents a lightweight region in a layout manager. This region does not move dom nodes
42912 * and does not have a titlebar, tabs or any other features. All it does is size and position
42913 * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
42915 Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
42917 this.position = pos;
42920 * @scope Roo.BasicLayoutRegion
42924 * @event beforeremove
42925 * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
42926 * @param {Roo.LayoutRegion} this
42927 * @param {Roo.ContentPanel} panel The panel
42928 * @param {Object} e The cancel event object
42930 "beforeremove" : true,
42932 * @event invalidated
42933 * Fires when the layout for this region is changed.
42934 * @param {Roo.LayoutRegion} this
42936 "invalidated" : true,
42938 * @event visibilitychange
42939 * Fires when this region is shown or hidden
42940 * @param {Roo.LayoutRegion} this
42941 * @param {Boolean} visibility true or false
42943 "visibilitychange" : true,
42945 * @event paneladded
42946 * Fires when a panel is added.
42947 * @param {Roo.LayoutRegion} this
42948 * @param {Roo.ContentPanel} panel The panel
42950 "paneladded" : true,
42952 * @event panelremoved
42953 * Fires when a panel is removed.
42954 * @param {Roo.LayoutRegion} this
42955 * @param {Roo.ContentPanel} panel The panel
42957 "panelremoved" : true,
42960 * Fires when this region is collapsed.
42961 * @param {Roo.LayoutRegion} this
42963 "collapsed" : true,
42966 * Fires when this region is expanded.
42967 * @param {Roo.LayoutRegion} this
42972 * Fires when this region is slid into view.
42973 * @param {Roo.LayoutRegion} this
42975 "slideshow" : true,
42978 * Fires when this region slides out of view.
42979 * @param {Roo.LayoutRegion} this
42981 "slidehide" : true,
42983 * @event panelactivated
42984 * Fires when a panel is activated.
42985 * @param {Roo.LayoutRegion} this
42986 * @param {Roo.ContentPanel} panel The activated panel
42988 "panelactivated" : true,
42991 * Fires when the user resizes this region.
42992 * @param {Roo.LayoutRegion} this
42993 * @param {Number} newSize The new size (width for east/west, height for north/south)
42997 /** A collection of panels in this region. @type Roo.util.MixedCollection */
42998 this.panels = new Roo.util.MixedCollection();
42999 this.panels.getKey = this.getPanelId.createDelegate(this);
43001 this.activePanel = null;
43002 // ensure listeners are added...
43004 if (config.listeners || config.events) {
43005 Roo.BasicLayoutRegion.superclass.constructor.call(this, {
43006 listeners : config.listeners || {},
43007 events : config.events || {}
43011 if(skipConfig !== true){
43012 this.applyConfig(config);
43016 Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
43017 getPanelId : function(p){
43021 applyConfig : function(config){
43022 this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
43023 this.config = config;
43028 * Resizes the region to the specified size. For vertical regions (west, east) this adjusts
43029 * the width, for horizontal (north, south) the height.
43030 * @param {Number} newSize The new width or height
43032 resizeTo : function(newSize){
43033 var el = this.el ? this.el :
43034 (this.activePanel ? this.activePanel.getEl() : null);
43036 switch(this.position){
43039 el.setWidth(newSize);
43040 this.fireEvent("resized", this, newSize);
43044 el.setHeight(newSize);
43045 this.fireEvent("resized", this, newSize);
43051 getBox : function(){
43052 return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
43055 getMargins : function(){
43056 return this.margins;
43059 updateBox : function(box){
43061 var el = this.activePanel.getEl();
43062 el.dom.style.left = box.x + "px";
43063 el.dom.style.top = box.y + "px";
43064 this.activePanel.setSize(box.width, box.height);
43068 * Returns the container element for this region.
43069 * @return {Roo.Element}
43071 getEl : function(){
43072 return this.activePanel;
43076 * Returns true if this region is currently visible.
43077 * @return {Boolean}
43079 isVisible : function(){
43080 return this.activePanel ? true : false;
43083 setActivePanel : function(panel){
43084 panel = this.getPanel(panel);
43085 if(this.activePanel && this.activePanel != panel){
43086 this.activePanel.setActiveState(false);
43087 this.activePanel.getEl().setLeftTop(-10000,-10000);
43089 this.activePanel = panel;
43090 panel.setActiveState(true);
43092 panel.setSize(this.box.width, this.box.height);
43094 this.fireEvent("panelactivated", this, panel);
43095 this.fireEvent("invalidated");
43099 * Show the specified panel.
43100 * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
43101 * @return {Roo.ContentPanel} The shown panel or null
43103 showPanel : function(panel){
43104 if(panel = this.getPanel(panel)){
43105 this.setActivePanel(panel);
43111 * Get the active panel for this region.
43112 * @return {Roo.ContentPanel} The active panel or null
43114 getActivePanel : function(){
43115 return this.activePanel;
43119 * Add the passed ContentPanel(s)
43120 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
43121 * @return {Roo.ContentPanel} The panel added (if only one was added)
43123 add : function(panel){
43124 if(arguments.length > 1){
43125 for(var i = 0, len = arguments.length; i < len; i++) {
43126 this.add(arguments[i]);
43130 if(this.hasPanel(panel)){
43131 this.showPanel(panel);
43134 var el = panel.getEl();
43135 if(el.dom.parentNode != this.mgr.el.dom){
43136 this.mgr.el.dom.appendChild(el.dom);
43138 if(panel.setRegion){
43139 panel.setRegion(this);
43141 this.panels.add(panel);
43142 el.setStyle("position", "absolute");
43143 if(!panel.background){
43144 this.setActivePanel(panel);
43145 if(this.config.initialSize && this.panels.getCount()==1){
43146 this.resizeTo(this.config.initialSize);
43149 this.fireEvent("paneladded", this, panel);
43154 * Returns true if the panel is in this region.
43155 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
43156 * @return {Boolean}
43158 hasPanel : function(panel){
43159 if(typeof panel == "object"){ // must be panel obj
43160 panel = panel.getId();
43162 return this.getPanel(panel) ? true : false;
43166 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
43167 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
43168 * @param {Boolean} preservePanel Overrides the config preservePanel option
43169 * @return {Roo.ContentPanel} The panel that was removed
43171 remove : function(panel, preservePanel){
43172 panel = this.getPanel(panel);
43177 this.fireEvent("beforeremove", this, panel, e);
43178 if(e.cancel === true){
43181 var panelId = panel.getId();
43182 this.panels.removeKey(panelId);
43187 * Returns the panel specified or null if it's not in this region.
43188 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
43189 * @return {Roo.ContentPanel}
43191 getPanel : function(id){
43192 if(typeof id == "object"){ // must be panel obj
43195 return this.panels.get(id);
43199 * Returns this regions position (north/south/east/west/center).
43202 getPosition: function(){
43203 return this.position;
43207 * Ext JS Library 1.1.1
43208 * Copyright(c) 2006-2007, Ext JS, LLC.
43210 * Originally Released Under LGPL - original licence link has changed is not relivant.
43213 * <script type="text/javascript">
43217 * @class Roo.LayoutRegion
43218 * @extends Roo.BasicLayoutRegion
43219 * This class represents a region in a layout manager.
43220 * @cfg {Boolean} collapsible False to disable collapsing (defaults to true)
43221 * @cfg {Boolean} collapsed True to set the initial display to collapsed (defaults to false)
43222 * @cfg {Boolean} floatable False to disable floating (defaults to true)
43223 * @cfg {Object} margins Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
43224 * @cfg {Object} cmargins Margins for the element when collapsed (defaults to: north/south {top: 2, left: 0, right:0, bottom: 2} or east/west {top: 0, left: 2, right:2, bottom: 0})
43225 * @cfg {String} tabPosition "top" or "bottom" (defaults to "bottom")
43226 * @cfg {String} collapsedTitle Optional string message to display in the collapsed block of a north or south region
43227 * @cfg {Boolean} alwaysShowTabs True to always display tabs even when there is only 1 panel (defaults to false)
43228 * @cfg {Boolean} autoScroll True to enable overflow scrolling (defaults to false)
43229 * @cfg {Boolean} titlebar True to display a title bar (defaults to true)
43230 * @cfg {String} title The title for the region (overrides panel titles)
43231 * @cfg {Boolean} animate True to animate expand/collapse (defaults to false)
43232 * @cfg {Boolean} autoHide False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
43233 * @cfg {Boolean} preservePanels True to preserve removed panels so they can be readded later (defaults to false)
43234 * @cfg {Boolean} closeOnTab True to place the close icon on the tabs instead of the region titlebar (defaults to false)
43235 * @cfg {Boolean} hideTabs True to hide the tab strip (defaults to false)
43236 * @cfg {Boolean} resizeTabs True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
43237 * the space available, similar to FireFox 1.5 tabs (defaults to false)
43238 * @cfg {Number} minTabWidth The minimum tab width (defaults to 40)
43239 * @cfg {Number} preferredTabWidth The preferred tab width (defaults to 150)
43240 * @cfg {Boolean} showPin True to show a pin button
43241 * @cfg {Boolean} hidden True to start the region hidden (defaults to false)
43242 * @cfg {Boolean} hideWhenEmpty True to hide the region when it has no panels
43243 * @cfg {Boolean} disableTabTips True to disable tab tooltips
43244 * @cfg {Number} width For East/West panels
43245 * @cfg {Number} height For North/South panels
43246 * @cfg {Boolean} split To show the splitter
43248 Roo.LayoutRegion = function(mgr, config, pos){
43249 Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
43250 var dh = Roo.DomHelper;
43251 /** This region's container element
43252 * @type Roo.Element */
43253 this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
43254 /** This region's title element
43255 * @type Roo.Element */
43257 this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
43258 {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: " "},
43259 {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
43261 this.titleEl.enableDisplayMode();
43262 /** This region's title text element
43263 * @type HTMLElement */
43264 this.titleTextEl = this.titleEl.dom.firstChild;
43265 this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
43266 this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
43267 this.closeBtn.enableDisplayMode();
43268 this.closeBtn.on("click", this.closeClicked, this);
43269 this.closeBtn.hide();
43271 this.createBody(config);
43272 this.visible = true;
43273 this.collapsed = false;
43275 if(config.hideWhenEmpty){
43277 this.on("paneladded", this.validateVisibility, this);
43278 this.on("panelremoved", this.validateVisibility, this);
43280 this.applyConfig(config);
43283 Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
43285 createBody : function(){
43286 /** This region's body element
43287 * @type Roo.Element */
43288 this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
43291 applyConfig : function(c){
43292 if(c.collapsible && this.position != "center" && !this.collapsedEl){
43293 var dh = Roo.DomHelper;
43294 if(c.titlebar !== false){
43295 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
43296 this.collapseBtn.on("click", this.collapse, this);
43297 this.collapseBtn.enableDisplayMode();
43299 if(c.showPin === true || this.showPin){
43300 this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
43301 this.stickBtn.enableDisplayMode();
43302 this.stickBtn.on("click", this.expand, this);
43303 this.stickBtn.hide();
43306 /** This region's collapsed element
43307 * @type Roo.Element */
43308 this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
43309 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
43311 if(c.floatable !== false){
43312 this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
43313 this.collapsedEl.on("click", this.collapseClick, this);
43316 if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
43317 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
43318 id: "message", unselectable: "on", style:{"float":"left"}});
43319 this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
43321 this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
43322 this.expandBtn.on("click", this.expand, this);
43324 if(this.collapseBtn){
43325 this.collapseBtn.setVisible(c.collapsible == true);
43327 this.cmargins = c.cmargins || this.cmargins ||
43328 (this.position == "west" || this.position == "east" ?
43329 {top: 0, left: 2, right:2, bottom: 0} :
43330 {top: 2, left: 0, right:0, bottom: 2});
43331 this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
43332 this.bottomTabs = c.tabPosition != "top";
43333 this.autoScroll = c.autoScroll || false;
43334 if(this.autoScroll){
43335 this.bodyEl.setStyle("overflow", "auto");
43337 this.bodyEl.setStyle("overflow", "hidden");
43339 //if(c.titlebar !== false){
43340 if((!c.titlebar && !c.title) || c.titlebar === false){
43341 this.titleEl.hide();
43343 this.titleEl.show();
43345 this.titleTextEl.innerHTML = c.title;
43349 this.duration = c.duration || .30;
43350 this.slideDuration = c.slideDuration || .45;
43353 this.collapse(true);
43360 * Returns true if this region is currently visible.
43361 * @return {Boolean}
43363 isVisible : function(){
43364 return this.visible;
43368 * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
43369 * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&#160;")
43371 setCollapsedTitle : function(title){
43372 title = title || " ";
43373 if(this.collapsedTitleTextEl){
43374 this.collapsedTitleTextEl.innerHTML = title;
43378 getBox : function(){
43380 if(!this.collapsed){
43381 b = this.el.getBox(false, true);
43383 b = this.collapsedEl.getBox(false, true);
43388 getMargins : function(){
43389 return this.collapsed ? this.cmargins : this.margins;
43392 highlight : function(){
43393 this.el.addClass("x-layout-panel-dragover");
43396 unhighlight : function(){
43397 this.el.removeClass("x-layout-panel-dragover");
43400 updateBox : function(box){
43402 if(!this.collapsed){
43403 this.el.dom.style.left = box.x + "px";
43404 this.el.dom.style.top = box.y + "px";
43405 this.updateBody(box.width, box.height);
43407 this.collapsedEl.dom.style.left = box.x + "px";
43408 this.collapsedEl.dom.style.top = box.y + "px";
43409 this.collapsedEl.setSize(box.width, box.height);
43412 this.tabs.autoSizeTabs();
43416 updateBody : function(w, h){
43418 this.el.setWidth(w);
43419 w -= this.el.getBorderWidth("rl");
43420 if(this.config.adjustments){
43421 w += this.config.adjustments[0];
43425 this.el.setHeight(h);
43426 h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
43427 h -= this.el.getBorderWidth("tb");
43428 if(this.config.adjustments){
43429 h += this.config.adjustments[1];
43431 this.bodyEl.setHeight(h);
43433 h = this.tabs.syncHeight(h);
43436 if(this.panelSize){
43437 w = w !== null ? w : this.panelSize.width;
43438 h = h !== null ? h : this.panelSize.height;
43440 if(this.activePanel){
43441 var el = this.activePanel.getEl();
43442 w = w !== null ? w : el.getWidth();
43443 h = h !== null ? h : el.getHeight();
43444 this.panelSize = {width: w, height: h};
43445 this.activePanel.setSize(w, h);
43447 if(Roo.isIE && this.tabs){
43448 this.tabs.el.repaint();
43453 * Returns the container element for this region.
43454 * @return {Roo.Element}
43456 getEl : function(){
43461 * Hides this region.
43464 if(!this.collapsed){
43465 this.el.dom.style.left = "-2000px";
43468 this.collapsedEl.dom.style.left = "-2000px";
43469 this.collapsedEl.hide();
43471 this.visible = false;
43472 this.fireEvent("visibilitychange", this, false);
43476 * Shows this region if it was previously hidden.
43479 if(!this.collapsed){
43482 this.collapsedEl.show();
43484 this.visible = true;
43485 this.fireEvent("visibilitychange", this, true);
43488 closeClicked : function(){
43489 if(this.activePanel){
43490 this.remove(this.activePanel);
43494 collapseClick : function(e){
43496 e.stopPropagation();
43499 e.stopPropagation();
43505 * Collapses this region.
43506 * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
43508 collapse : function(skipAnim){
43509 if(this.collapsed) return;
43510 this.collapsed = true;
43512 this.split.el.hide();
43514 if(this.config.animate && skipAnim !== true){
43515 this.fireEvent("invalidated", this);
43516 this.animateCollapse();
43518 this.el.setLocation(-20000,-20000);
43520 this.collapsedEl.show();
43521 this.fireEvent("collapsed", this);
43522 this.fireEvent("invalidated", this);
43526 animateCollapse : function(){
43531 * Expands this region if it was previously collapsed.
43532 * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
43533 * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
43535 expand : function(e, skipAnim){
43536 if(e) e.stopPropagation();
43537 if(!this.collapsed || this.el.hasActiveFx()) return;
43539 this.afterSlideIn();
43542 this.collapsed = false;
43543 if(this.config.animate && skipAnim !== true){
43544 this.animateExpand();
43548 this.split.el.show();
43550 this.collapsedEl.setLocation(-2000,-2000);
43551 this.collapsedEl.hide();
43552 this.fireEvent("invalidated", this);
43553 this.fireEvent("expanded", this);
43557 animateExpand : function(){
43561 initTabs : function(){
43562 this.bodyEl.setStyle("overflow", "hidden");
43563 var ts = new Roo.TabPanel(this.bodyEl.dom, {
43564 tabPosition: this.bottomTabs ? 'bottom' : 'top',
43565 disableTooltips: this.config.disableTabTips
43567 if(this.config.hideTabs){
43568 ts.stripWrap.setDisplayed(false);
43571 ts.resizeTabs = this.config.resizeTabs === true;
43572 ts.minTabWidth = this.config.minTabWidth || 40;
43573 ts.maxTabWidth = this.config.maxTabWidth || 250;
43574 ts.preferredTabWidth = this.config.preferredTabWidth || 150;
43575 ts.monitorResize = false;
43576 ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
43577 ts.bodyEl.addClass('x-layout-tabs-body');
43578 this.panels.each(this.initPanelAsTab, this);
43581 initPanelAsTab : function(panel){
43582 var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
43583 this.config.closeOnTab && panel.isClosable());
43584 if(panel.tabTip !== undefined){
43585 ti.setTooltip(panel.tabTip);
43587 ti.on("activate", function(){
43588 this.setActivePanel(panel);
43590 if(this.config.closeOnTab){
43591 ti.on("beforeclose", function(t, e){
43593 this.remove(panel);
43599 updatePanelTitle : function(panel, title){
43600 if(this.activePanel == panel){
43601 this.updateTitle(title);
43604 var ti = this.tabs.getTab(panel.getEl().id);
43606 if(panel.tabTip !== undefined){
43607 ti.setTooltip(panel.tabTip);
43612 updateTitle : function(title){
43613 if(this.titleTextEl && !this.config.title){
43614 this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : " ");
43618 setActivePanel : function(panel){
43619 panel = this.getPanel(panel);
43620 if(this.activePanel && this.activePanel != panel){
43621 this.activePanel.setActiveState(false);
43623 this.activePanel = panel;
43624 panel.setActiveState(true);
43625 if(this.panelSize){
43626 panel.setSize(this.panelSize.width, this.panelSize.height);
43629 this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
43631 this.updateTitle(panel.getTitle());
43633 this.fireEvent("invalidated", this);
43635 this.fireEvent("panelactivated", this, panel);
43639 * Shows the specified panel.
43640 * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
43641 * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
43643 showPanel : function(panel){
43644 if(panel = this.getPanel(panel)){
43646 var tab = this.tabs.getTab(panel.getEl().id);
43647 if(tab.isHidden()){
43648 this.tabs.unhideTab(tab.id);
43652 this.setActivePanel(panel);
43659 * Get the active panel for this region.
43660 * @return {Roo.ContentPanel} The active panel or null
43662 getActivePanel : function(){
43663 return this.activePanel;
43666 validateVisibility : function(){
43667 if(this.panels.getCount() < 1){
43668 this.updateTitle(" ");
43669 this.closeBtn.hide();
43672 if(!this.isVisible()){
43679 * Adds the passed ContentPanel(s) to this region.
43680 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
43681 * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
43683 add : function(panel){
43684 if(arguments.length > 1){
43685 for(var i = 0, len = arguments.length; i < len; i++) {
43686 this.add(arguments[i]);
43690 if(this.hasPanel(panel)){
43691 this.showPanel(panel);
43694 panel.setRegion(this);
43695 this.panels.add(panel);
43696 if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
43697 this.bodyEl.dom.appendChild(panel.getEl().dom);
43698 if(panel.background !== true){
43699 this.setActivePanel(panel);
43701 this.fireEvent("paneladded", this, panel);
43707 this.initPanelAsTab(panel);
43709 if(panel.background !== true){
43710 this.tabs.activate(panel.getEl().id);
43712 this.fireEvent("paneladded", this, panel);
43717 * Hides the tab for the specified panel.
43718 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
43720 hidePanel : function(panel){
43721 if(this.tabs && (panel = this.getPanel(panel))){
43722 this.tabs.hideTab(panel.getEl().id);
43727 * Unhides the tab for a previously hidden panel.
43728 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
43730 unhidePanel : function(panel){
43731 if(this.tabs && (panel = this.getPanel(panel))){
43732 this.tabs.unhideTab(panel.getEl().id);
43736 clearPanels : function(){
43737 while(this.panels.getCount() > 0){
43738 this.remove(this.panels.first());
43743 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
43744 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
43745 * @param {Boolean} preservePanel Overrides the config preservePanel option
43746 * @return {Roo.ContentPanel} The panel that was removed
43748 remove : function(panel, preservePanel){
43749 panel = this.getPanel(panel);
43754 this.fireEvent("beforeremove", this, panel, e);
43755 if(e.cancel === true){
43758 preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
43759 var panelId = panel.getId();
43760 this.panels.removeKey(panelId);
43762 document.body.appendChild(panel.getEl().dom);
43765 this.tabs.removeTab(panel.getEl().id);
43766 }else if (!preservePanel){
43767 this.bodyEl.dom.removeChild(panel.getEl().dom);
43769 if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
43770 var p = this.panels.first();
43771 var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
43772 tempEl.appendChild(p.getEl().dom);
43773 this.bodyEl.update("");
43774 this.bodyEl.dom.appendChild(p.getEl().dom);
43776 this.updateTitle(p.getTitle());
43778 this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
43779 this.setActivePanel(p);
43781 panel.setRegion(null);
43782 if(this.activePanel == panel){
43783 this.activePanel = null;
43785 if(this.config.autoDestroy !== false && preservePanel !== true){
43786 try{panel.destroy();}catch(e){}
43788 this.fireEvent("panelremoved", this, panel);
43793 * Returns the TabPanel component used by this region
43794 * @return {Roo.TabPanel}
43796 getTabs : function(){
43800 createTool : function(parentEl, className){
43801 var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
43802 children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: " "}]}, true);
43803 btn.addClassOnOver("x-layout-tools-button-over");
43808 * Ext JS Library 1.1.1
43809 * Copyright(c) 2006-2007, Ext JS, LLC.
43811 * Originally Released Under LGPL - original licence link has changed is not relivant.
43814 * <script type="text/javascript">
43820 * @class Roo.SplitLayoutRegion
43821 * @extends Roo.LayoutRegion
43822 * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
43824 Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
43825 this.cursor = cursor;
43826 Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
43829 Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
43830 splitTip : "Drag to resize.",
43831 collapsibleSplitTip : "Drag to resize. Double click to hide.",
43832 useSplitTips : false,
43834 applyConfig : function(config){
43835 Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
43838 var splitEl = Roo.DomHelper.append(this.mgr.el.dom,
43839 {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: " "});
43840 /** The SplitBar for this region
43841 * @type Roo.SplitBar */
43842 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
43843 this.split.on("moved", this.onSplitMove, this);
43844 this.split.useShim = config.useShim === true;
43845 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
43846 if(this.useSplitTips){
43847 this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
43849 if(config.collapsible){
43850 this.split.el.on("dblclick", this.collapse, this);
43853 if(typeof config.minSize != "undefined"){
43854 this.split.minSize = config.minSize;
43856 if(typeof config.maxSize != "undefined"){
43857 this.split.maxSize = config.maxSize;
43859 if(config.hideWhenEmpty || config.hidden || config.collapsed){
43860 this.hideSplitter();
43865 getHMaxSize : function(){
43866 var cmax = this.config.maxSize || 10000;
43867 var center = this.mgr.getRegion("center");
43868 return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
43871 getVMaxSize : function(){
43872 var cmax = this.config.maxSize || 10000;
43873 var center = this.mgr.getRegion("center");
43874 return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
43877 onSplitMove : function(split, newSize){
43878 this.fireEvent("resized", this, newSize);
43882 * Returns the {@link Roo.SplitBar} for this region.
43883 * @return {Roo.SplitBar}
43885 getSplitBar : function(){
43890 this.hideSplitter();
43891 Roo.SplitLayoutRegion.superclass.hide.call(this);
43894 hideSplitter : function(){
43896 this.split.el.setLocation(-2000,-2000);
43897 this.split.el.hide();
43903 this.split.el.show();
43905 Roo.SplitLayoutRegion.superclass.show.call(this);
43908 beforeSlide: function(){
43909 if(Roo.isGecko){// firefox overflow auto bug workaround
43910 this.bodyEl.clip();
43911 if(this.tabs) this.tabs.bodyEl.clip();
43912 if(this.activePanel){
43913 this.activePanel.getEl().clip();
43915 if(this.activePanel.beforeSlide){
43916 this.activePanel.beforeSlide();
43922 afterSlide : function(){
43923 if(Roo.isGecko){// firefox overflow auto bug workaround
43924 this.bodyEl.unclip();
43925 if(this.tabs) this.tabs.bodyEl.unclip();
43926 if(this.activePanel){
43927 this.activePanel.getEl().unclip();
43928 if(this.activePanel.afterSlide){
43929 this.activePanel.afterSlide();
43935 initAutoHide : function(){
43936 if(this.autoHide !== false){
43937 if(!this.autoHideHd){
43938 var st = new Roo.util.DelayedTask(this.slideIn, this);
43939 this.autoHideHd = {
43940 "mouseout": function(e){
43941 if(!e.within(this.el, true)){
43945 "mouseover" : function(e){
43951 this.el.on(this.autoHideHd);
43955 clearAutoHide : function(){
43956 if(this.autoHide !== false){
43957 this.el.un("mouseout", this.autoHideHd.mouseout);
43958 this.el.un("mouseover", this.autoHideHd.mouseover);
43962 clearMonitor : function(){
43963 Roo.get(document).un("click", this.slideInIf, this);
43966 // these names are backwards but not changed for compat
43967 slideOut : function(){
43968 if(this.isSlid || this.el.hasActiveFx()){
43971 this.isSlid = true;
43972 if(this.collapseBtn){
43973 this.collapseBtn.hide();
43975 this.closeBtnState = this.closeBtn.getStyle('display');
43976 this.closeBtn.hide();
43978 this.stickBtn.show();
43981 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
43982 this.beforeSlide();
43983 this.el.setStyle("z-index", 10001);
43984 this.el.slideIn(this.getSlideAnchor(), {
43985 callback: function(){
43987 this.initAutoHide();
43988 Roo.get(document).on("click", this.slideInIf, this);
43989 this.fireEvent("slideshow", this);
43996 afterSlideIn : function(){
43997 this.clearAutoHide();
43998 this.isSlid = false;
43999 this.clearMonitor();
44000 this.el.setStyle("z-index", "");
44001 if(this.collapseBtn){
44002 this.collapseBtn.show();
44004 this.closeBtn.setStyle('display', this.closeBtnState);
44006 this.stickBtn.hide();
44008 this.fireEvent("slidehide", this);
44011 slideIn : function(cb){
44012 if(!this.isSlid || this.el.hasActiveFx()){
44016 this.isSlid = false;
44017 this.beforeSlide();
44018 this.el.slideOut(this.getSlideAnchor(), {
44019 callback: function(){
44020 this.el.setLeftTop(-10000, -10000);
44022 this.afterSlideIn();
44030 slideInIf : function(e){
44031 if(!e.within(this.el)){
44036 animateCollapse : function(){
44037 this.beforeSlide();
44038 this.el.setStyle("z-index", 20000);
44039 var anchor = this.getSlideAnchor();
44040 this.el.slideOut(anchor, {
44041 callback : function(){
44042 this.el.setStyle("z-index", "");
44043 this.collapsedEl.slideIn(anchor, {duration:.3});
44045 this.el.setLocation(-10000,-10000);
44047 this.fireEvent("collapsed", this);
44054 animateExpand : function(){
44055 this.beforeSlide();
44056 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
44057 this.el.setStyle("z-index", 20000);
44058 this.collapsedEl.hide({
44061 this.el.slideIn(this.getSlideAnchor(), {
44062 callback : function(){
44063 this.el.setStyle("z-index", "");
44066 this.split.el.show();
44068 this.fireEvent("invalidated", this);
44069 this.fireEvent("expanded", this);
44097 getAnchor : function(){
44098 return this.anchors[this.position];
44101 getCollapseAnchor : function(){
44102 return this.canchors[this.position];
44105 getSlideAnchor : function(){
44106 return this.sanchors[this.position];
44109 getAlignAdj : function(){
44110 var cm = this.cmargins;
44111 switch(this.position){
44127 getExpandAdj : function(){
44128 var c = this.collapsedEl, cm = this.cmargins;
44129 switch(this.position){
44131 return [-(cm.right+c.getWidth()+cm.left), 0];
44134 return [cm.right+c.getWidth()+cm.left, 0];
44137 return [0, -(cm.top+cm.bottom+c.getHeight())];
44140 return [0, cm.top+cm.bottom+c.getHeight()];
44146 * Ext JS Library 1.1.1
44147 * Copyright(c) 2006-2007, Ext JS, LLC.
44149 * Originally Released Under LGPL - original licence link has changed is not relivant.
44152 * <script type="text/javascript">
44155 * These classes are private internal classes
44157 Roo.CenterLayoutRegion = function(mgr, config){
44158 Roo.LayoutRegion.call(this, mgr, config, "center");
44159 this.visible = true;
44160 this.minWidth = config.minWidth || 20;
44161 this.minHeight = config.minHeight || 20;
44164 Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
44166 // center panel can't be hidden
44170 // center panel can't be hidden
44173 getMinWidth: function(){
44174 return this.minWidth;
44177 getMinHeight: function(){
44178 return this.minHeight;
44183 Roo.NorthLayoutRegion = function(mgr, config){
44184 Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
44186 this.split.placement = Roo.SplitBar.TOP;
44187 this.split.orientation = Roo.SplitBar.VERTICAL;
44188 this.split.el.addClass("x-layout-split-v");
44190 var size = config.initialSize || config.height;
44191 if(typeof size != "undefined"){
44192 this.el.setHeight(size);
44195 Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
44196 orientation: Roo.SplitBar.VERTICAL,
44197 getBox : function(){
44198 if(this.collapsed){
44199 return this.collapsedEl.getBox();
44201 var box = this.el.getBox();
44203 box.height += this.split.el.getHeight();
44208 updateBox : function(box){
44209 if(this.split && !this.collapsed){
44210 box.height -= this.split.el.getHeight();
44211 this.split.el.setLeft(box.x);
44212 this.split.el.setTop(box.y+box.height);
44213 this.split.el.setWidth(box.width);
44215 if(this.collapsed){
44216 this.updateBody(box.width, null);
44218 Roo.LayoutRegion.prototype.updateBox.call(this, box);
44222 Roo.SouthLayoutRegion = function(mgr, config){
44223 Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
44225 this.split.placement = Roo.SplitBar.BOTTOM;
44226 this.split.orientation = Roo.SplitBar.VERTICAL;
44227 this.split.el.addClass("x-layout-split-v");
44229 var size = config.initialSize || config.height;
44230 if(typeof size != "undefined"){
44231 this.el.setHeight(size);
44234 Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
44235 orientation: Roo.SplitBar.VERTICAL,
44236 getBox : function(){
44237 if(this.collapsed){
44238 return this.collapsedEl.getBox();
44240 var box = this.el.getBox();
44242 var sh = this.split.el.getHeight();
44249 updateBox : function(box){
44250 if(this.split && !this.collapsed){
44251 var sh = this.split.el.getHeight();
44254 this.split.el.setLeft(box.x);
44255 this.split.el.setTop(box.y-sh);
44256 this.split.el.setWidth(box.width);
44258 if(this.collapsed){
44259 this.updateBody(box.width, null);
44261 Roo.LayoutRegion.prototype.updateBox.call(this, box);
44265 Roo.EastLayoutRegion = function(mgr, config){
44266 Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
44268 this.split.placement = Roo.SplitBar.RIGHT;
44269 this.split.orientation = Roo.SplitBar.HORIZONTAL;
44270 this.split.el.addClass("x-layout-split-h");
44272 var size = config.initialSize || config.width;
44273 if(typeof size != "undefined"){
44274 this.el.setWidth(size);
44277 Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
44278 orientation: Roo.SplitBar.HORIZONTAL,
44279 getBox : function(){
44280 if(this.collapsed){
44281 return this.collapsedEl.getBox();
44283 var box = this.el.getBox();
44285 var sw = this.split.el.getWidth();
44292 updateBox : function(box){
44293 if(this.split && !this.collapsed){
44294 var sw = this.split.el.getWidth();
44296 this.split.el.setLeft(box.x);
44297 this.split.el.setTop(box.y);
44298 this.split.el.setHeight(box.height);
44301 if(this.collapsed){
44302 this.updateBody(null, box.height);
44304 Roo.LayoutRegion.prototype.updateBox.call(this, box);
44308 Roo.WestLayoutRegion = function(mgr, config){
44309 Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
44311 this.split.placement = Roo.SplitBar.LEFT;
44312 this.split.orientation = Roo.SplitBar.HORIZONTAL;
44313 this.split.el.addClass("x-layout-split-h");
44315 var size = config.initialSize || config.width;
44316 if(typeof size != "undefined"){
44317 this.el.setWidth(size);
44320 Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
44321 orientation: Roo.SplitBar.HORIZONTAL,
44322 getBox : function(){
44323 if(this.collapsed){
44324 return this.collapsedEl.getBox();
44326 var box = this.el.getBox();
44328 box.width += this.split.el.getWidth();
44333 updateBox : function(box){
44334 if(this.split && !this.collapsed){
44335 var sw = this.split.el.getWidth();
44337 this.split.el.setLeft(box.x+box.width);
44338 this.split.el.setTop(box.y);
44339 this.split.el.setHeight(box.height);
44341 if(this.collapsed){
44342 this.updateBody(null, box.height);
44344 Roo.LayoutRegion.prototype.updateBox.call(this, box);
44349 * Ext JS Library 1.1.1
44350 * Copyright(c) 2006-2007, Ext JS, LLC.
44352 * Originally Released Under LGPL - original licence link has changed is not relivant.
44355 * <script type="text/javascript">
44360 * Private internal class for reading and applying state
44362 Roo.LayoutStateManager = function(layout){
44363 // default empty state
44372 Roo.LayoutStateManager.prototype = {
44373 init : function(layout, provider){
44374 this.provider = provider;
44375 var state = provider.get(layout.id+"-layout-state");
44377 var wasUpdating = layout.isUpdating();
44379 layout.beginUpdate();
44381 for(var key in state){
44382 if(typeof state[key] != "function"){
44383 var rstate = state[key];
44384 var r = layout.getRegion(key);
44387 r.resizeTo(rstate.size);
44389 if(rstate.collapsed == true){
44392 r.expand(null, true);
44398 layout.endUpdate();
44400 this.state = state;
44402 this.layout = layout;
44403 layout.on("regionresized", this.onRegionResized, this);
44404 layout.on("regioncollapsed", this.onRegionCollapsed, this);
44405 layout.on("regionexpanded", this.onRegionExpanded, this);
44408 storeState : function(){
44409 this.provider.set(this.layout.id+"-layout-state", this.state);
44412 onRegionResized : function(region, newSize){
44413 this.state[region.getPosition()].size = newSize;
44417 onRegionCollapsed : function(region){
44418 this.state[region.getPosition()].collapsed = true;
44422 onRegionExpanded : function(region){
44423 this.state[region.getPosition()].collapsed = false;
44428 * Ext JS Library 1.1.1
44429 * Copyright(c) 2006-2007, Ext JS, LLC.
44431 * Originally Released Under LGPL - original licence link has changed is not relivant.
44434 * <script type="text/javascript">
44437 * @class Roo.ContentPanel
44438 * @extends Roo.util.Observable
44439 * A basic ContentPanel element.
44440 * @cfg {Boolean} fitToFrame True for this panel to adjust its size to fit when the region resizes (defaults to false)
44441 * @cfg {Boolean} fitContainer When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container (defaults to false)
44442 * @cfg {Boolean/Object} autoCreate True to auto generate the DOM element for this panel, or a {@link Roo.DomHelper} config of the element to create
44443 * @cfg {Boolean} closable True if the panel can be closed/removed
44444 * @cfg {Boolean} background True if the panel should not be activated when it is added (defaults to false)
44445 * @cfg {String/HTMLElement/Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
44446 * @cfg {Toolbar} toolbar A toolbar for this panel
44447 * @cfg {Boolean} autoScroll True to scroll overflow in this panel (use with {@link #fitToFrame})
44448 * @cfg {String} title The title for this panel
44449 * @cfg {Array} adjustments Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
44450 * @cfg {String} url Calls {@link #setUrl} with this value
44451 * @cfg {String} region (center|north|south|east|west) which region to put this panel on (when used with xtype constructors)
44452 * @cfg {String/Object} params When used with {@link #url}, calls {@link #setUrl} with this value
44453 * @cfg {Boolean} loadOnce When used with {@link #url}, calls {@link #setUrl} with this value
44455 * Create a new ContentPanel.
44456 * @param {String/HTMLElement/Roo.Element} el The container element for this panel
44457 * @param {String/Object} config A string to set only the title or a config object
44458 * @param {String} content (optional) Set the HTML content for this panel
44459 * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
44461 Roo.ContentPanel = function(el, config, content){
44465 if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
44469 if (config && config.parentLayout) {
44470 el = config.parentLayout.el.createChild();
44473 if(el.autoCreate){ // xtype is available if this is called from factory
44477 this.el = Roo.get(el);
44478 if(!this.el && config && config.autoCreate){
44479 if(typeof config.autoCreate == "object"){
44480 if(!config.autoCreate.id){
44481 config.autoCreate.id = config.id||el;
44483 this.el = Roo.DomHelper.append(document.body,
44484 config.autoCreate, true);
44486 this.el = Roo.DomHelper.append(document.body,
44487 {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
44490 this.closable = false;
44491 this.loaded = false;
44492 this.active = false;
44493 if(typeof config == "string"){
44494 this.title = config;
44496 Roo.apply(this, config);
44499 if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
44500 this.wrapEl = this.el.wrap();
44501 this.toolbar = new Roo.Toolbar(this.el.insertSibling(false, 'before'), [] , this.toolbar);
44508 this.resizeEl = Roo.get(this.resizeEl, true);
44510 this.resizeEl = this.el;
44515 * Fires when this panel is activated.
44516 * @param {Roo.ContentPanel} this
44520 * @event deactivate
44521 * Fires when this panel is activated.
44522 * @param {Roo.ContentPanel} this
44524 "deactivate" : true,
44528 * Fires when this panel is resized if fitToFrame is true.
44529 * @param {Roo.ContentPanel} this
44530 * @param {Number} width The width after any component adjustments
44531 * @param {Number} height The height after any component adjustments
44535 if(this.autoScroll){
44536 this.resizeEl.setStyle("overflow", "auto");
44538 content = content || this.content;
44540 this.setContent(content);
44542 if(config && config.url){
44543 this.setUrl(this.url, this.params, this.loadOnce);
44548 Roo.ContentPanel.superclass.constructor.call(this);
44551 Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
44553 setRegion : function(region){
44554 this.region = region;
44556 this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
44558 this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
44563 * Returns the toolbar for this Panel if one was configured.
44564 * @return {Roo.Toolbar}
44566 getToolbar : function(){
44567 return this.toolbar;
44570 setActiveState : function(active){
44571 this.active = active;
44573 this.fireEvent("deactivate", this);
44575 this.fireEvent("activate", this);
44579 * Updates this panel's element
44580 * @param {String} content The new content
44581 * @param {Boolean} loadScripts (optional) true to look for and process scripts
44583 setContent : function(content, loadScripts){
44584 this.el.update(content, loadScripts);
44587 ignoreResize : function(w, h){
44588 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
44591 this.lastSize = {width: w, height: h};
44596 * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
44597 * @return {Roo.UpdateManager} The UpdateManager
44599 getUpdateManager : function(){
44600 return this.el.getUpdateManager();
44603 * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
44604 * @param {Object/String/Function} url The url for this request or a function to call to get the url or a config object containing any of the following options:
44607 url: "your-url.php",
44608 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
44609 callback: yourFunction,
44610 scope: yourObject, //(optional scope)
44613 text: "Loading...",
44618 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
44619 * are shorthand for <i>disableCaching</i>, <i>indicatorText</i> and <i>loadScripts</i> and are used to set their associated property on this panel UpdateManager instance.
44620 * @param {String/Object} params (optional) The parameters to pass as either a URL encoded string "param1=1&param2=2" or an object {param1: 1, param2: 2}
44621 * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
44622 * @param {Boolean} discardUrl (optional) By default when you execute an update the defaultUrl is changed to the last used URL. If true, it will not store the URL.
44623 * @return {Roo.ContentPanel} this
44626 var um = this.el.getUpdateManager();
44627 um.update.apply(um, arguments);
44633 * Set a URL to be used to load the content for this panel. When this panel is activated, the content will be loaded from that URL.
44634 * @param {String/Function} url The URL to load the content from or a function to call to get the URL
44635 * @param {String/Object} params (optional) The string params for the update call or an object of the params. See {@link Roo.UpdateManager#update} for more details. (Defaults to null)
44636 * @param {Boolean} loadOnce (optional) Whether to only load the content once. If this is false it makes the Ajax call every time this panel is activated. (Defaults to false)
44637 * @return {Roo.UpdateManager} The UpdateManager
44639 setUrl : function(url, params, loadOnce){
44640 if(this.refreshDelegate){
44641 this.removeListener("activate", this.refreshDelegate);
44643 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
44644 this.on("activate", this.refreshDelegate);
44645 return this.el.getUpdateManager();
44648 _handleRefresh : function(url, params, loadOnce){
44649 if(!loadOnce || !this.loaded){
44650 var updater = this.el.getUpdateManager();
44651 updater.update(url, params, this._setLoaded.createDelegate(this));
44655 _setLoaded : function(){
44656 this.loaded = true;
44660 * Returns this panel's id
44663 getId : function(){
44668 * Returns this panel's element - used by regiosn to add.
44669 * @return {Roo.Element}
44671 getEl : function(){
44672 return this.wrapEl || this.el;
44675 adjustForComponents : function(width, height){
44676 if(this.resizeEl != this.el){
44677 width -= this.el.getFrameWidth('lr');
44678 height -= this.el.getFrameWidth('tb');
44681 var te = this.toolbar.getEl();
44682 height -= te.getHeight();
44683 te.setWidth(width);
44685 if(this.adjustments){
44686 width += this.adjustments[0];
44687 height += this.adjustments[1];
44689 return {"width": width, "height": height};
44692 setSize : function(width, height){
44693 if(this.fitToFrame && !this.ignoreResize(width, height)){
44694 if(this.fitContainer && this.resizeEl != this.el){
44695 this.el.setSize(width, height);
44697 var size = this.adjustForComponents(width, height);
44698 this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
44699 this.fireEvent('resize', this, size.width, size.height);
44704 * Returns this panel's title
44707 getTitle : function(){
44712 * Set this panel's title
44713 * @param {String} title
44715 setTitle : function(title){
44716 this.title = title;
44718 this.region.updatePanelTitle(this, title);
44723 * Returns true is this panel was configured to be closable
44724 * @return {Boolean}
44726 isClosable : function(){
44727 return this.closable;
44730 beforeSlide : function(){
44732 this.resizeEl.clip();
44735 afterSlide : function(){
44737 this.resizeEl.unclip();
44741 * Force a content refresh from the URL specified in the {@link #setUrl} method.
44742 * Will fail silently if the {@link #setUrl} method has not been called.
44743 * This does not activate the panel, just updates its content.
44745 refresh : function(){
44746 if(this.refreshDelegate){
44747 this.loaded = false;
44748 this.refreshDelegate();
44753 * Destroys this panel
44755 destroy : function(){
44756 this.el.removeAllListeners();
44757 var tempEl = document.createElement("span");
44758 tempEl.appendChild(this.el.dom);
44759 tempEl.innerHTML = "";
44765 * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
44775 * @param {Object} cfg Xtype definition of item to add.
44778 addxtype : function(cfg) {
44780 if (cfg.xtype.match(/^Form$/)) {
44781 var el = this.el.createChild();
44783 this.form = new Roo.form.Form(cfg);
44786 if ( this.form.allItems.length) this.form.render(el.dom);
44789 if (['View', 'JsonView'].indexOf(cfg.xtype) > -1) {
44791 cfg.el = this.el.appendChild(document.createElement("div"));
44793 var ret = new Roo[cfg.xtype](cfg);
44794 ret.render(false, ''); // render blank..
44804 * @class Roo.GridPanel
44805 * @extends Roo.ContentPanel
44807 * Create a new GridPanel.
44808 * @param {Roo.grid.Grid} grid The grid for this panel
44809 * @param {String/Object} config A string to set only the panel's title, or a config object
44811 Roo.GridPanel = function(grid, config){
44814 this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
44815 {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
44817 this.wrapper.dom.appendChild(grid.getGridEl().dom);
44819 Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
44822 this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
44824 // xtype created footer. - not sure if will work as we normally have to render first..
44825 if (this.footer && !this.footer.el && this.footer.xtype) {
44827 this.footer.container = this.grid.getView().getFooterPanel(true);
44828 this.footer.dataSource = this.grid.dataSource;
44829 this.footer = Roo.factory(this.footer, Roo);
44833 grid.monitorWindowResize = false; // turn off autosizing
44834 grid.autoHeight = false;
44835 grid.autoWidth = false;
44837 this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
44840 Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
44841 getId : function(){
44842 return this.grid.id;
44846 * Returns the grid for this panel
44847 * @return {Roo.grid.Grid}
44849 getGrid : function(){
44853 setSize : function(width, height){
44854 if(!this.ignoreResize(width, height)){
44855 var grid = this.grid;
44856 var size = this.adjustForComponents(width, height);
44857 grid.getGridEl().setSize(size.width, size.height);
44862 beforeSlide : function(){
44863 this.grid.getView().scroller.clip();
44866 afterSlide : function(){
44867 this.grid.getView().scroller.unclip();
44870 destroy : function(){
44871 this.grid.destroy();
44873 Roo.GridPanel.superclass.destroy.call(this);
44879 * @class Roo.NestedLayoutPanel
44880 * @extends Roo.ContentPanel
44882 * Create a new NestedLayoutPanel.
44885 * @param {Roo.BorderLayout} layout The layout for this panel
44886 * @param {String/Object} config A string to set only the title or a config object
44888 Roo.NestedLayoutPanel = function(layout, config)
44890 // construct with only one argument..
44891 /* FIXME - implement nicer consturctors
44892 if (layout.layout) {
44894 layout = config.layout;
44895 delete config.layout;
44897 if (layout.xtype && !layout.getEl) {
44898 // then layout needs constructing..
44899 layout = Roo.factory(layout, Roo);
44903 Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
44905 layout.monitorWindowResize = false; // turn off autosizing
44906 this.layout = layout;
44907 this.layout.getEl().addClass("x-layout-nested-layout");
44913 Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
44915 setSize : function(width, height){
44916 if(!this.ignoreResize(width, height)){
44917 var size = this.adjustForComponents(width, height);
44918 var el = this.layout.getEl();
44919 el.setSize(size.width, size.height);
44920 var touch = el.dom.offsetWidth;
44921 this.layout.layout();
44922 // ie requires a double layout on the first pass
44923 if(Roo.isIE && !this.initialized){
44924 this.initialized = true;
44925 this.layout.layout();
44930 // activate all subpanels if not currently active..
44932 setActiveState : function(active){
44933 this.active = active;
44935 this.fireEvent("deactivate", this);
44939 this.fireEvent("activate", this);
44940 // not sure if this should happen before or after..
44941 if (!this.layout) {
44942 return; // should not happen..
44945 for (var r in this.layout.regions) {
44946 reg = this.layout.getRegion(r);
44947 if (reg.getActivePanel()) {
44948 //reg.showPanel(reg.getActivePanel()); // force it to activate..
44949 reg.setActivePanel(reg.getActivePanel());
44952 if (!reg.panels.length) {
44955 reg.showPanel(reg.getPanel(0));
44964 * Returns the nested BorderLayout for this panel
44965 * @return {Roo.BorderLayout}
44967 getLayout : function(){
44968 return this.layout;
44972 * Adds a xtype elements to the layout of the nested panel
44976 xtype : 'ContentPanel',
44983 xtype : 'NestedLayoutPanel',
44989 items : [ ... list of content panels or nested layout panels.. ]
44993 * @param {Object} cfg Xtype definition of item to add.
44995 addxtype : function(cfg) {
44996 return this.layout.addxtype(cfg);
45001 Roo.ScrollPanel = function(el, config, content){
45002 config = config || {};
45003 config.fitToFrame = true;
45004 Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
45006 this.el.dom.style.overflow = "hidden";
45007 var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
45008 this.el.removeClass("x-layout-inactive-content");
45009 this.el.on("mousewheel", this.onWheel, this);
45011 var up = wrap.createChild({cls: "x-scroller-up", html: " "}, this.el.dom);
45012 var down = wrap.createChild({cls: "x-scroller-down", html: " "});
45013 up.unselectable(); down.unselectable();
45014 up.on("click", this.scrollUp, this);
45015 down.on("click", this.scrollDown, this);
45016 up.addClassOnOver("x-scroller-btn-over");
45017 down.addClassOnOver("x-scroller-btn-over");
45018 up.addClassOnClick("x-scroller-btn-click");
45019 down.addClassOnClick("x-scroller-btn-click");
45020 this.adjustments = [0, -(up.getHeight() + down.getHeight())];
45022 this.resizeEl = this.el;
45023 this.el = wrap; this.up = up; this.down = down;
45026 Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
45028 wheelIncrement : 5,
45029 scrollUp : function(){
45030 this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
45033 scrollDown : function(){
45034 this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
45037 afterScroll : function(){
45038 var el = this.resizeEl;
45039 var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
45040 this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
45041 this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
45044 setSize : function(){
45045 Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
45046 this.afterScroll();
45049 onWheel : function(e){
45050 var d = e.getWheelDelta();
45051 this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
45052 this.afterScroll();
45056 setContent : function(content, loadScripts){
45057 this.resizeEl.update(content, loadScripts);
45071 * @class Roo.TreePanel
45072 * @extends Roo.ContentPanel
45074 * Create a new TreePanel.
45075 * @param {String/Object} config A string to set only the panel's title, or a config object
45076 * @cfg {Roo.tree.TreePanel} tree The tree TreePanel, with config etc.
45078 Roo.TreePanel = function(config){
45079 var el = config.el;
45080 var tree = config.tree;
45081 delete config.tree;
45082 delete config.el; // hopefull!
45083 Roo.TreePanel.superclass.constructor.call(this, el, config);
45084 var treeEl = el.createChild();
45085 this.tree = new Roo.tree.TreePanel(treeEl , tree);
45086 //console.log(tree);
45087 this.on('activate', function()
45089 if (this.tree.rendered) {
45092 //console.log('render tree');
45093 this.tree.render();
45096 this.on('resize', function (cp, w, h) {
45097 this.tree.innerCt.setWidth(w);
45098 this.tree.innerCt.setHeight(h);
45099 this.tree.innerCt.setStyle('overflow-y', 'auto');
45106 Roo.extend(Roo.TreePanel, Roo.ContentPanel);
45120 * Ext JS Library 1.1.1
45121 * Copyright(c) 2006-2007, Ext JS, LLC.
45123 * Originally Released Under LGPL - original licence link has changed is not relivant.
45126 * <script type="text/javascript">
45131 * @class Roo.ReaderLayout
45132 * @extends Roo.BorderLayout
45133 * This is a pre-built layout that represents a classic, 5-pane application. It consists of a header, a primary
45134 * center region containing two nested regions (a top one for a list view and one for item preview below),
45135 * and regions on either side that can be used for navigation, application commands, informational displays, etc.
45136 * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
45137 * expedites the setup of the overall layout and regions for this common application style.
45140 var reader = new Roo.ReaderLayout();
45141 var CP = Roo.ContentPanel; // shortcut for adding
45143 reader.beginUpdate();
45144 reader.add("north", new CP("north", "North"));
45145 reader.add("west", new CP("west", {title: "West"}));
45146 reader.add("east", new CP("east", {title: "East"}));
45148 reader.regions.listView.add(new CP("listView", "List"));
45149 reader.regions.preview.add(new CP("preview", "Preview"));
45150 reader.endUpdate();
45153 * Create a new ReaderLayout
45154 * @param {Object} config Configuration options
45155 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
45156 * document.body if omitted)
45158 Roo.ReaderLayout = function(config, renderTo){
45159 var c = config || {size:{}};
45160 Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
45161 north: c.north !== false ? Roo.apply({
45165 }, c.north) : false,
45166 west: c.west !== false ? Roo.apply({
45174 margins:{left:5,right:0,bottom:5,top:5},
45175 cmargins:{left:5,right:5,bottom:5,top:5}
45176 }, c.west) : false,
45177 east: c.east !== false ? Roo.apply({
45185 margins:{left:0,right:5,bottom:5,top:5},
45186 cmargins:{left:5,right:5,bottom:5,top:5}
45187 }, c.east) : false,
45188 center: Roo.apply({
45189 tabPosition: 'top',
45193 margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
45197 this.el.addClass('x-reader');
45199 this.beginUpdate();
45201 var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
45202 south: c.preview !== false ? Roo.apply({
45209 cmargins:{top:5,left:0, right:0, bottom:0}
45210 }, c.preview) : false,
45211 center: Roo.apply({
45217 this.add('center', new Roo.NestedLayoutPanel(inner,
45218 Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
45222 this.regions.preview = inner.getRegion('south');
45223 this.regions.listView = inner.getRegion('center');
45226 Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
45228 * Ext JS Library 1.1.1
45229 * Copyright(c) 2006-2007, Ext JS, LLC.
45231 * Originally Released Under LGPL - original licence link has changed is not relivant.
45234 * <script type="text/javascript">
45238 * @class Roo.grid.Grid
45239 * @extends Roo.util.Observable
45240 * This class represents the primary interface of a component based grid control.
45241 * <br><br>Usage:<pre><code>
45242 var grid = new Roo.grid.Grid("my-container-id", {
45245 selModel: mySelectionModel,
45246 autoSizeColumns: true,
45247 monitorWindowResize: false,
45248 trackMouseOver: true
45253 * <b>Common Problems:</b><br/>
45254 * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
45255 * element will correct this<br/>
45256 * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
45257 * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
45258 * are unpredictable.<br/>
45259 * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
45260 * grid to calculate dimensions/offsets.<br/>
45262 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
45263 * The container MUST have some type of size defined for the grid to fill. The container will be
45264 * automatically set to position relative if it isn't already.
45265 * @param {Object} config A config object that sets properties on this grid.
45267 Roo.grid.Grid = function(container, config){
45268 // initialize the container
45269 this.container = Roo.get(container);
45270 this.container.update("");
45271 this.container.setStyle("overflow", "hidden");
45272 this.container.addClass('x-grid-container');
45274 this.id = this.container.id;
45276 Roo.apply(this, config);
45277 // check and correct shorthanded configs
45279 this.dataSource = this.ds;
45283 this.colModel = this.cm;
45287 this.selModel = this.sm;
45291 if (this.selModel) {
45292 this.selModel = Roo.factory(this.selModel, Roo.grid);
45293 this.sm = this.selModel;
45294 this.sm.xmodule = this.xmodule || false;
45296 if (typeof(this.colModel.config) == 'undefined') {
45297 this.colModel = new Roo.grid.ColumnModel(this.colModel);
45298 this.cm = this.colModel;
45299 this.cm.xmodule = this.xmodule || false;
45301 if (this.dataSource) {
45302 this.dataSource= Roo.factory(this.dataSource, Roo.data);
45303 this.ds = this.dataSource;
45304 this.ds.xmodule = this.xmodule || false;
45311 this.container.setWidth(this.width);
45315 this.container.setHeight(this.height);
45322 * The raw click event for the entire grid.
45323 * @param {Roo.EventObject} e
45328 * The raw dblclick event for the entire grid.
45329 * @param {Roo.EventObject} e
45333 * @event contextmenu
45334 * The raw contextmenu event for the entire grid.
45335 * @param {Roo.EventObject} e
45337 "contextmenu" : true,
45340 * The raw mousedown event for the entire grid.
45341 * @param {Roo.EventObject} e
45343 "mousedown" : true,
45346 * The raw mouseup event for the entire grid.
45347 * @param {Roo.EventObject} e
45352 * The raw mouseover event for the entire grid.
45353 * @param {Roo.EventObject} e
45355 "mouseover" : true,
45358 * The raw mouseout event for the entire grid.
45359 * @param {Roo.EventObject} e
45364 * The raw keypress event for the entire grid.
45365 * @param {Roo.EventObject} e
45370 * The raw keydown event for the entire grid.
45371 * @param {Roo.EventObject} e
45379 * Fires when a cell is clicked
45380 * @param {Grid} this
45381 * @param {Number} rowIndex
45382 * @param {Number} columnIndex
45383 * @param {Roo.EventObject} e
45385 "cellclick" : true,
45387 * @event celldblclick
45388 * Fires when a cell is double clicked
45389 * @param {Grid} this
45390 * @param {Number} rowIndex
45391 * @param {Number} columnIndex
45392 * @param {Roo.EventObject} e
45394 "celldblclick" : true,
45397 * Fires when a row is clicked
45398 * @param {Grid} this
45399 * @param {Number} rowIndex
45400 * @param {Roo.EventObject} e
45404 * @event rowdblclick
45405 * Fires when a row is double clicked
45406 * @param {Grid} this
45407 * @param {Number} rowIndex
45408 * @param {Roo.EventObject} e
45410 "rowdblclick" : true,
45412 * @event headerclick
45413 * Fires when a header is clicked
45414 * @param {Grid} this
45415 * @param {Number} columnIndex
45416 * @param {Roo.EventObject} e
45418 "headerclick" : true,
45420 * @event headerdblclick
45421 * Fires when a header cell is double clicked
45422 * @param {Grid} this
45423 * @param {Number} columnIndex
45424 * @param {Roo.EventObject} e
45426 "headerdblclick" : true,
45428 * @event rowcontextmenu
45429 * Fires when a row is right clicked
45430 * @param {Grid} this
45431 * @param {Number} rowIndex
45432 * @param {Roo.EventObject} e
45434 "rowcontextmenu" : true,
45436 * @event cellcontextmenu
45437 * Fires when a cell is right clicked
45438 * @param {Grid} this
45439 * @param {Number} rowIndex
45440 * @param {Number} cellIndex
45441 * @param {Roo.EventObject} e
45443 "cellcontextmenu" : true,
45445 * @event headercontextmenu
45446 * Fires when a header is right clicked
45447 * @param {Grid} this
45448 * @param {Number} columnIndex
45449 * @param {Roo.EventObject} e
45451 "headercontextmenu" : true,
45453 * @event bodyscroll
45454 * Fires when the body element is scrolled
45455 * @param {Number} scrollLeft
45456 * @param {Number} scrollTop
45458 "bodyscroll" : true,
45460 * @event columnresize
45461 * Fires when the user resizes a column
45462 * @param {Number} columnIndex
45463 * @param {Number} newSize
45465 "columnresize" : true,
45467 * @event columnmove
45468 * Fires when the user moves a column
45469 * @param {Number} oldIndex
45470 * @param {Number} newIndex
45472 "columnmove" : true,
45475 * Fires when row(s) start being dragged
45476 * @param {Grid} this
45477 * @param {Roo.GridDD} dd The drag drop object
45478 * @param {event} e The raw browser event
45480 "startdrag" : true,
45483 * Fires when a drag operation is complete
45484 * @param {Grid} this
45485 * @param {Roo.GridDD} dd The drag drop object
45486 * @param {event} e The raw browser event
45491 * Fires when dragged row(s) are dropped on a valid DD target
45492 * @param {Grid} this
45493 * @param {Roo.GridDD} dd The drag drop object
45494 * @param {String} targetId The target drag drop object
45495 * @param {event} e The raw browser event
45500 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
45501 * @param {Grid} this
45502 * @param {Roo.GridDD} dd The drag drop object
45503 * @param {String} targetId The target drag drop object
45504 * @param {event} e The raw browser event
45509 * Fires when the dragged row(s) first cross another DD target while being dragged
45510 * @param {Grid} this
45511 * @param {Roo.GridDD} dd The drag drop object
45512 * @param {String} targetId The target drag drop object
45513 * @param {event} e The raw browser event
45515 "dragenter" : true,
45518 * Fires when the dragged row(s) leave another DD target while being dragged
45519 * @param {Grid} this
45520 * @param {Roo.GridDD} dd The drag drop object
45521 * @param {String} targetId The target drag drop object
45522 * @param {event} e The raw browser event
45527 * Fires when the grid is rendered
45528 * @param {Grid} grid
45533 Roo.grid.Grid.superclass.constructor.call(this);
45535 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
45537 * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
45539 minColumnWidth : 25,
45542 * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
45543 * <b>on initial render.</b> It is more efficient to explicitly size the columns
45544 * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option. Default is false.
45546 autoSizeColumns : false,
45549 * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
45551 autoSizeHeaders : true,
45554 * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
45556 monitorWindowResize : true,
45559 * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
45560 * rows measured to get a columns size. Default is 0 (all rows).
45562 maxRowsToMeasure : 0,
45565 * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
45567 trackMouseOver : true,
45570 * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
45572 enableDragDrop : false,
45575 * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
45577 enableColumnMove : true,
45580 * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
45582 enableColumnHide : true,
45585 * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
45587 enableRowHeightSync : false,
45590 * @cfg {Boolean} stripeRows True to stripe the rows. Default is true.
45595 * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
45597 autoHeight : false,
45600 * @cfg {String} autoExpandColumn The id (or dataIndex) of a column in this grid that should expand to fill unused space. This id can not be 0. Default is false.
45602 autoExpandColumn : false,
45605 * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
45608 autoExpandMin : 50,
45611 * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
45613 autoExpandMax : 1000,
45616 * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
45621 * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
45629 * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
45630 * of a fixed width. Default is false.
45633 * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
45636 * Called once after all setup has been completed and the grid is ready to be rendered.
45637 * @return {Roo.grid.Grid} this
45639 render : function(){
45640 var c = this.container;
45641 // try to detect autoHeight/width mode
45642 if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
45643 this.autoHeight = true;
45645 var view = this.getView();
45648 c.on("click", this.onClick, this);
45649 c.on("dblclick", this.onDblClick, this);
45650 c.on("contextmenu", this.onContextMenu, this);
45651 c.on("keydown", this.onKeyDown, this);
45653 this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
45655 this.getSelectionModel().init(this);
45660 this.loadMask = new Roo.LoadMask(this.container,
45661 Roo.apply({store:this.dataSource}, this.loadMask));
45665 if (this.toolbar && this.toolbar.xtype) {
45666 this.toolbar.container = this.getView().getHeaderPanel(true);
45667 this.toolbar = new Ext.Toolbar(this.toolbar);
45669 if (this.footer && this.footer.xtype) {
45670 this.footer.dataSource = this.getDataSource();
45671 this.footer.container = this.getView().getFooterPanel(true);
45672 this.footer = Roo.factory(this.footer, Roo);
45674 this.rendered = true;
45675 this.fireEvent('render', this);
45680 * Reconfigures the grid to use a different Store and Column Model.
45681 * The View will be bound to the new objects and refreshed.
45682 * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
45683 * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
45685 reconfigure : function(dataSource, colModel){
45687 this.loadMask.destroy();
45688 this.loadMask = new Roo.LoadMask(this.container,
45689 Roo.apply({store:dataSource}, this.loadMask));
45691 this.view.bind(dataSource, colModel);
45692 this.dataSource = dataSource;
45693 this.colModel = colModel;
45694 this.view.refresh(true);
45698 onKeyDown : function(e){
45699 this.fireEvent("keydown", e);
45703 * Destroy this grid.
45704 * @param {Boolean} removeEl True to remove the element
45706 destroy : function(removeEl, keepListeners){
45708 this.loadMask.destroy();
45710 var c = this.container;
45711 c.removeAllListeners();
45712 this.view.destroy();
45713 this.colModel.purgeListeners();
45714 if(!keepListeners){
45715 this.purgeListeners();
45718 if(removeEl === true){
45724 processEvent : function(name, e){
45725 this.fireEvent(name, e);
45726 var t = e.getTarget();
45728 var header = v.findHeaderIndex(t);
45729 if(header !== false){
45730 this.fireEvent("header" + name, this, header, e);
45732 var row = v.findRowIndex(t);
45733 var cell = v.findCellIndex(t);
45735 this.fireEvent("row" + name, this, row, e);
45736 if(cell !== false){
45737 this.fireEvent("cell" + name, this, row, cell, e);
45744 onClick : function(e){
45745 this.processEvent("click", e);
45749 onContextMenu : function(e, t){
45750 this.processEvent("contextmenu", e);
45754 onDblClick : function(e){
45755 this.processEvent("dblclick", e);
45759 walkCells : function(row, col, step, fn, scope){
45760 var cm = this.colModel, clen = cm.getColumnCount();
45761 var ds = this.dataSource, rlen = ds.getCount(), first = true;
45773 if(fn.call(scope || this, row, col, cm) === true){
45791 if(fn.call(scope || this, row, col, cm) === true){
45803 getSelections : function(){
45804 return this.selModel.getSelections();
45808 * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
45809 * but if manual update is required this method will initiate it.
45811 autoSize : function(){
45813 this.view.layout();
45814 if(this.view.adjustForScroll){
45815 this.view.adjustForScroll();
45821 * Returns the grid's underlying element.
45822 * @return {Element} The element
45824 getGridEl : function(){
45825 return this.container;
45828 // private for compatibility, overridden by editor grid
45829 stopEditing : function(){},
45832 * Returns the grid's SelectionModel.
45833 * @return {SelectionModel}
45835 getSelectionModel : function(){
45836 if(!this.selModel){
45837 this.selModel = new Roo.grid.RowSelectionModel();
45839 return this.selModel;
45843 * Returns the grid's DataSource.
45844 * @return {DataSource}
45846 getDataSource : function(){
45847 return this.dataSource;
45851 * Returns the grid's ColumnModel.
45852 * @return {ColumnModel}
45854 getColumnModel : function(){
45855 return this.colModel;
45859 * Returns the grid's GridView object.
45860 * @return {GridView}
45862 getView : function(){
45864 this.view = new Roo.grid.GridView(this.viewConfig);
45869 * Called to get grid's drag proxy text, by default returns this.ddText.
45872 getDragDropText : function(){
45873 var count = this.selModel.getCount();
45874 return String.format(this.ddText, count, count == 1 ? '' : 's');
45878 * Configures the text is the drag proxy (defaults to "%0 selected row(s)").
45879 * %0 is replaced with the number of selected rows.
45882 Roo.grid.Grid.prototype.ddText = "{0} selected row{1}";/*
45884 * Ext JS Library 1.1.1
45885 * Copyright(c) 2006-2007, Ext JS, LLC.
45887 * Originally Released Under LGPL - original licence link has changed is not relivant.
45890 * <script type="text/javascript">
45893 Roo.grid.AbstractGridView = function(){
45897 "beforerowremoved" : true,
45898 "beforerowsinserted" : true,
45899 "beforerefresh" : true,
45900 "rowremoved" : true,
45901 "rowsinserted" : true,
45902 "rowupdated" : true,
45905 Roo.grid.AbstractGridView.superclass.constructor.call(this);
45908 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
45909 rowClass : "x-grid-row",
45910 cellClass : "x-grid-cell",
45911 tdClass : "x-grid-td",
45912 hdClass : "x-grid-hd",
45913 splitClass : "x-grid-hd-split",
45915 init: function(grid){
45917 var cid = this.grid.getGridEl().id;
45918 this.colSelector = "#" + cid + " ." + this.cellClass + "-";
45919 this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
45920 this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
45921 this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
45924 getColumnRenderers : function(){
45925 var renderers = [];
45926 var cm = this.grid.colModel;
45927 var colCount = cm.getColumnCount();
45928 for(var i = 0; i < colCount; i++){
45929 renderers[i] = cm.getRenderer(i);
45934 getColumnIds : function(){
45936 var cm = this.grid.colModel;
45937 var colCount = cm.getColumnCount();
45938 for(var i = 0; i < colCount; i++){
45939 ids[i] = cm.getColumnId(i);
45944 getDataIndexes : function(){
45945 if(!this.indexMap){
45946 this.indexMap = this.buildIndexMap();
45948 return this.indexMap.colToData;
45951 getColumnIndexByDataIndex : function(dataIndex){
45952 if(!this.indexMap){
45953 this.indexMap = this.buildIndexMap();
45955 return this.indexMap.dataToCol[dataIndex];
45959 * Set a css style for a column dynamically.
45960 * @param {Number} colIndex The index of the column
45961 * @param {String} name The css property name
45962 * @param {String} value The css value
45964 setCSSStyle : function(colIndex, name, value){
45965 var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
45966 Roo.util.CSS.updateRule(selector, name, value);
45969 generateRules : function(cm){
45970 var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
45971 Roo.util.CSS.removeStyleSheet(rulesId);
45972 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
45973 var cid = cm.getColumnId(i);
45974 ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
45975 this.tdSelector, cid, " {\n}\n",
45976 this.hdSelector, cid, " {\n}\n",
45977 this.splitSelector, cid, " {\n}\n");
45979 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
45983 * Ext JS Library 1.1.1
45984 * Copyright(c) 2006-2007, Ext JS, LLC.
45986 * Originally Released Under LGPL - original licence link has changed is not relivant.
45989 * <script type="text/javascript">
45993 // This is a support class used internally by the Grid components
45994 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
45996 this.view = grid.getView();
45997 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
45998 Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
46000 this.setHandleElId(Roo.id(hd));
46001 this.setOuterHandleElId(Roo.id(hd2));
46003 this.scroll = false;
46005 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
46007 getDragData : function(e){
46008 var t = Roo.lib.Event.getTarget(e);
46009 var h = this.view.findHeaderCell(t);
46011 return {ddel: h.firstChild, header:h};
46016 onInitDrag : function(e){
46017 this.view.headersDisabled = true;
46018 var clone = this.dragData.ddel.cloneNode(true);
46019 clone.id = Roo.id();
46020 clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
46021 this.proxy.update(clone);
46025 afterValidDrop : function(){
46027 setTimeout(function(){
46028 v.headersDisabled = false;
46032 afterInvalidDrop : function(){
46034 setTimeout(function(){
46035 v.headersDisabled = false;
46041 * Ext JS Library 1.1.1
46042 * Copyright(c) 2006-2007, Ext JS, LLC.
46044 * Originally Released Under LGPL - original licence link has changed is not relivant.
46047 * <script type="text/javascript">
46050 // This is a support class used internally by the Grid components
46051 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
46053 this.view = grid.getView();
46054 // split the proxies so they don't interfere with mouse events
46055 this.proxyTop = Roo.DomHelper.append(document.body, {
46056 cls:"col-move-top", html:" "
46058 this.proxyBottom = Roo.DomHelper.append(document.body, {
46059 cls:"col-move-bottom", html:" "
46061 this.proxyTop.hide = this.proxyBottom.hide = function(){
46062 this.setLeftTop(-100,-100);
46063 this.setStyle("visibility", "hidden");
46065 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
46066 // temporarily disabled
46067 //Roo.dd.ScrollManager.register(this.view.scroller.dom);
46068 Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
46070 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
46071 proxyOffsets : [-4, -9],
46072 fly: Roo.Element.fly,
46074 getTargetFromEvent : function(e){
46075 var t = Roo.lib.Event.getTarget(e);
46076 var cindex = this.view.findCellIndex(t);
46077 if(cindex !== false){
46078 return this.view.getHeaderCell(cindex);
46082 nextVisible : function(h){
46083 var v = this.view, cm = this.grid.colModel;
46086 if(!cm.isHidden(v.getCellIndex(h))){
46094 prevVisible : function(h){
46095 var v = this.view, cm = this.grid.colModel;
46098 if(!cm.isHidden(v.getCellIndex(h))){
46106 positionIndicator : function(h, n, e){
46107 var x = Roo.lib.Event.getPageX(e);
46108 var r = Roo.lib.Dom.getRegion(n.firstChild);
46109 var px, pt, py = r.top + this.proxyOffsets[1];
46110 if((r.right - x) <= (r.right-r.left)/2){
46111 px = r.right+this.view.borderWidth;
46117 var oldIndex = this.view.getCellIndex(h);
46118 var newIndex = this.view.getCellIndex(n);
46120 if(this.grid.colModel.isFixed(newIndex)){
46124 var locked = this.grid.colModel.isLocked(newIndex);
46129 if(oldIndex < newIndex){
46132 if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
46135 px += this.proxyOffsets[0];
46136 this.proxyTop.setLeftTop(px, py);
46137 this.proxyTop.show();
46138 if(!this.bottomOffset){
46139 this.bottomOffset = this.view.mainHd.getHeight();
46141 this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
46142 this.proxyBottom.show();
46146 onNodeEnter : function(n, dd, e, data){
46147 if(data.header != n){
46148 this.positionIndicator(data.header, n, e);
46152 onNodeOver : function(n, dd, e, data){
46153 var result = false;
46154 if(data.header != n){
46155 result = this.positionIndicator(data.header, n, e);
46158 this.proxyTop.hide();
46159 this.proxyBottom.hide();
46161 return result ? this.dropAllowed : this.dropNotAllowed;
46164 onNodeOut : function(n, dd, e, data){
46165 this.proxyTop.hide();
46166 this.proxyBottom.hide();
46169 onNodeDrop : function(n, dd, e, data){
46170 var h = data.header;
46172 var cm = this.grid.colModel;
46173 var x = Roo.lib.Event.getPageX(e);
46174 var r = Roo.lib.Dom.getRegion(n.firstChild);
46175 var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
46176 var oldIndex = this.view.getCellIndex(h);
46177 var newIndex = this.view.getCellIndex(n);
46178 var locked = cm.isLocked(newIndex);
46182 if(oldIndex < newIndex){
46185 if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
46188 cm.setLocked(oldIndex, locked, true);
46189 cm.moveColumn(oldIndex, newIndex);
46190 this.grid.fireEvent("columnmove", oldIndex, newIndex);
46198 * Ext JS Library 1.1.1
46199 * Copyright(c) 2006-2007, Ext JS, LLC.
46201 * Originally Released Under LGPL - original licence link has changed is not relivant.
46204 * <script type="text/javascript">
46208 * @class Roo.grid.GridView
46209 * @extends Roo.util.Observable
46212 * @param {Object} config
46214 Roo.grid.GridView = function(config){
46215 Roo.grid.GridView.superclass.constructor.call(this);
46218 Roo.apply(this, config);
46221 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
46224 * Override this function to apply custom css classes to rows during rendering
46225 * @param {Record} record The record
46226 * @param {Number} index
46227 * @method getRowClass
46229 rowClass : "x-grid-row",
46231 cellClass : "x-grid-col",
46233 tdClass : "x-grid-td",
46235 hdClass : "x-grid-hd",
46237 splitClass : "x-grid-split",
46239 sortClasses : ["sort-asc", "sort-desc"],
46241 enableMoveAnim : false,
46245 dh : Roo.DomHelper,
46247 fly : Roo.Element.fly,
46249 css : Roo.util.CSS,
46255 scrollIncrement : 22,
46257 cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
46259 findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
46261 bind : function(ds, cm){
46263 this.ds.un("load", this.onLoad, this);
46264 this.ds.un("datachanged", this.onDataChange, this);
46265 this.ds.un("add", this.onAdd, this);
46266 this.ds.un("remove", this.onRemove, this);
46267 this.ds.un("update", this.onUpdate, this);
46268 this.ds.un("clear", this.onClear, this);
46271 ds.on("load", this.onLoad, this);
46272 ds.on("datachanged", this.onDataChange, this);
46273 ds.on("add", this.onAdd, this);
46274 ds.on("remove", this.onRemove, this);
46275 ds.on("update", this.onUpdate, this);
46276 ds.on("clear", this.onClear, this);
46281 this.cm.un("widthchange", this.onColWidthChange, this);
46282 this.cm.un("headerchange", this.onHeaderChange, this);
46283 this.cm.un("hiddenchange", this.onHiddenChange, this);
46284 this.cm.un("columnmoved", this.onColumnMove, this);
46285 this.cm.un("columnlockchange", this.onColumnLock, this);
46288 this.generateRules(cm);
46289 cm.on("widthchange", this.onColWidthChange, this);
46290 cm.on("headerchange", this.onHeaderChange, this);
46291 cm.on("hiddenchange", this.onHiddenChange, this);
46292 cm.on("columnmoved", this.onColumnMove, this);
46293 cm.on("columnlockchange", this.onColumnLock, this);
46298 init: function(grid){
46299 Roo.grid.GridView.superclass.init.call(this, grid);
46301 this.bind(grid.dataSource, grid.colModel);
46303 grid.on("headerclick", this.handleHeaderClick, this);
46305 if(grid.trackMouseOver){
46306 grid.on("mouseover", this.onRowOver, this);
46307 grid.on("mouseout", this.onRowOut, this);
46309 grid.cancelTextSelection = function(){};
46310 this.gridId = grid.id;
46312 var tpls = this.templates || {};
46315 tpls.master = new Roo.Template(
46316 '<div class="x-grid" hidefocus="true">',
46317 '<div class="x-grid-topbar"></div>',
46318 '<div class="x-grid-scroller"><div></div></div>',
46319 '<div class="x-grid-locked">',
46320 '<div class="x-grid-header">{lockedHeader}</div>',
46321 '<div class="x-grid-body">{lockedBody}</div>',
46323 '<div class="x-grid-viewport">',
46324 '<div class="x-grid-header">{header}</div>',
46325 '<div class="x-grid-body">{body}</div>',
46327 '<div class="x-grid-bottombar"></div>',
46328 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
46329 '<div class="x-grid-resize-proxy"> </div>',
46332 tpls.master.disableformats = true;
46336 tpls.header = new Roo.Template(
46337 '<table border="0" cellspacing="0" cellpadding="0">',
46338 '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
46341 tpls.header.disableformats = true;
46343 tpls.header.compile();
46346 tpls.hcell = new Roo.Template(
46347 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
46348 '<div class="x-grid-hd-text" unselectable="on">{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
46351 tpls.hcell.disableFormats = true;
46353 tpls.hcell.compile();
46356 tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style}" unselectable="on"> </div>');
46357 tpls.hsplit.disableFormats = true;
46359 tpls.hsplit.compile();
46362 tpls.body = new Roo.Template(
46363 '<table border="0" cellspacing="0" cellpadding="0">',
46364 "<tbody>{rows}</tbody>",
46367 tpls.body.disableFormats = true;
46369 tpls.body.compile();
46372 tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
46373 tpls.row.disableFormats = true;
46375 tpls.row.compile();
46378 tpls.cell = new Roo.Template(
46379 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
46380 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text" unselectable="on" {attr}>{value}</div></div>',
46383 tpls.cell.disableFormats = true;
46385 tpls.cell.compile();
46387 this.templates = tpls;
46390 // remap these for backwards compat
46391 onColWidthChange : function(){
46392 this.updateColumns.apply(this, arguments);
46394 onHeaderChange : function(){
46395 this.updateHeaders.apply(this, arguments);
46397 onHiddenChange : function(){
46398 this.handleHiddenChange.apply(this, arguments);
46400 onColumnMove : function(){
46401 this.handleColumnMove.apply(this, arguments);
46403 onColumnLock : function(){
46404 this.handleLockChange.apply(this, arguments);
46407 onDataChange : function(){
46409 this.updateHeaderSortState();
46412 onClear : function(){
46416 onUpdate : function(ds, record){
46417 this.refreshRow(record);
46420 refreshRow : function(record){
46421 var ds = this.ds, index;
46422 if(typeof record == 'number'){
46424 record = ds.getAt(index);
46426 index = ds.indexOf(record);
46428 this.insertRows(ds, index, index, true);
46429 this.onRemove(ds, record, index+1, true);
46430 this.syncRowHeights(index, index);
46432 this.fireEvent("rowupdated", this, index, record);
46435 onAdd : function(ds, records, index){
46436 this.insertRows(ds, index, index + (records.length-1));
46439 onRemove : function(ds, record, index, isUpdate){
46440 if(isUpdate !== true){
46441 this.fireEvent("beforerowremoved", this, index, record);
46443 var bt = this.getBodyTable(), lt = this.getLockedTable();
46444 if(bt.rows[index]){
46445 bt.firstChild.removeChild(bt.rows[index]);
46447 if(lt.rows[index]){
46448 lt.firstChild.removeChild(lt.rows[index]);
46450 if(isUpdate !== true){
46451 this.stripeRows(index);
46452 this.syncRowHeights(index, index);
46454 this.fireEvent("rowremoved", this, index, record);
46458 onLoad : function(){
46459 this.scrollToTop();
46463 * Scrolls the grid to the top
46465 scrollToTop : function(){
46467 this.scroller.dom.scrollTop = 0;
46473 * Gets a panel in the header of the grid that can be used for toolbars etc.
46474 * After modifying the contents of this panel a call to grid.autoSize() may be
46475 * required to register any changes in size.
46476 * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
46477 * @return Roo.Element
46479 getHeaderPanel : function(doShow){
46481 this.headerPanel.show();
46483 return this.headerPanel;
46487 * Gets a panel in the footer of the grid that can be used for toolbars etc.
46488 * After modifying the contents of this panel a call to grid.autoSize() may be
46489 * required to register any changes in size.
46490 * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
46491 * @return Roo.Element
46493 getFooterPanel : function(doShow){
46495 this.footerPanel.show();
46497 return this.footerPanel;
46500 initElements : function(){
46501 var E = Roo.Element;
46502 var el = this.grid.getGridEl().dom.firstChild;
46503 var cs = el.childNodes;
46505 this.el = new E(el);
46506 this.headerPanel = new E(el.firstChild);
46507 this.headerPanel.enableDisplayMode("block");
46509 this.scroller = new E(cs[1]);
46510 this.scrollSizer = new E(this.scroller.dom.firstChild);
46512 this.lockedWrap = new E(cs[2]);
46513 this.lockedHd = new E(this.lockedWrap.dom.firstChild);
46514 this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
46516 this.mainWrap = new E(cs[3]);
46517 this.mainHd = new E(this.mainWrap.dom.firstChild);
46518 this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
46520 this.footerPanel = new E(cs[4]);
46521 this.footerPanel.enableDisplayMode("block");
46523 this.focusEl = new E(cs[5]);
46524 this.focusEl.swallowEvent("click", true);
46525 this.resizeProxy = new E(cs[6]);
46527 this.headerSelector = String.format(
46528 '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
46529 this.lockedHd.id, this.mainHd.id
46532 this.splitterSelector = String.format(
46533 '#{0} div.x-grid-split, #{1} div.x-grid-split',
46534 this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
46537 idToCssName : function(s)
46539 return s.replace(/[^a-z0-9]+/ig, '-');
46542 getHeaderCell : function(index){
46543 return Roo.DomQuery.select(this.headerSelector)[index];
46546 getHeaderCellMeasure : function(index){
46547 return this.getHeaderCell(index).firstChild;
46550 getHeaderCellText : function(index){
46551 return this.getHeaderCell(index).firstChild.firstChild;
46554 getLockedTable : function(){
46555 return this.lockedBody.dom.firstChild;
46558 getBodyTable : function(){
46559 return this.mainBody.dom.firstChild;
46562 getLockedRow : function(index){
46563 return this.getLockedTable().rows[index];
46566 getRow : function(index){
46567 return this.getBodyTable().rows[index];
46570 getRowComposite : function(index){
46572 this.rowEl = new Roo.CompositeElementLite();
46574 var els = [], lrow, mrow;
46575 if(lrow = this.getLockedRow(index)){
46578 if(mrow = this.getRow(index)){
46581 this.rowEl.elements = els;
46585 getCell : function(rowIndex, colIndex){
46586 var locked = this.cm.getLockedCount();
46588 if(colIndex < locked){
46589 source = this.lockedBody.dom.firstChild;
46591 source = this.mainBody.dom.firstChild;
46592 colIndex -= locked;
46594 return source.rows[rowIndex].childNodes[colIndex];
46597 getCellText : function(rowIndex, colIndex){
46598 return this.getCell(rowIndex, colIndex).firstChild.firstChild;
46601 getCellBox : function(cell){
46602 var b = this.fly(cell).getBox();
46603 if(Roo.isOpera){ // opera fails to report the Y
46604 b.y = cell.offsetTop + this.mainBody.getY();
46609 getCellIndex : function(cell){
46610 var id = String(cell.className).match(this.cellRE);
46612 return parseInt(id[1], 10);
46617 findHeaderIndex : function(n){
46618 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
46619 return r ? this.getCellIndex(r) : false;
46622 findHeaderCell : function(n){
46623 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
46624 return r ? r : false;
46627 findRowIndex : function(n){
46631 var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
46632 return r ? r.rowIndex : false;
46635 findCellIndex : function(node){
46636 var stop = this.el.dom;
46637 while(node && node != stop){
46638 if(this.findRE.test(node.className)){
46639 return this.getCellIndex(node);
46641 node = node.parentNode;
46646 getColumnId : function(index){
46647 return this.cm.getColumnId(index);
46650 getSplitters : function(){
46651 if(this.splitterSelector){
46652 return Roo.DomQuery.select(this.splitterSelector);
46658 getSplitter : function(index){
46659 return this.getSplitters()[index];
46662 onRowOver : function(e, t){
46664 if((row = this.findRowIndex(t)) !== false){
46665 this.getRowComposite(row).addClass("x-grid-row-over");
46669 onRowOut : function(e, t){
46671 if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
46672 this.getRowComposite(row).removeClass("x-grid-row-over");
46676 renderHeaders : function(){
46678 var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
46679 var cb = [], lb = [], sb = [], lsb = [], p = {};
46680 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
46681 p.cellId = "x-grid-hd-0-" + i;
46682 p.splitId = "x-grid-csplit-0-" + i;
46683 p.id = cm.getColumnId(i);
46684 p.title = cm.getColumnTooltip(i) || "";
46685 p.value = cm.getColumnHeader(i) || "";
46686 p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
46687 if(!cm.isLocked(i)){
46688 cb[cb.length] = ct.apply(p);
46689 sb[sb.length] = st.apply(p);
46691 lb[lb.length] = ct.apply(p);
46692 lsb[lsb.length] = st.apply(p);
46695 return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
46696 ht.apply({cells: cb.join(""), splits:sb.join("")})];
46699 updateHeaders : function(){
46700 var html = this.renderHeaders();
46701 this.lockedHd.update(html[0]);
46702 this.mainHd.update(html[1]);
46706 * Focuses the specified row.
46707 * @param {Number} row The row index
46709 focusRow : function(row){
46710 var x = this.scroller.dom.scrollLeft;
46711 this.focusCell(row, 0, false);
46712 this.scroller.dom.scrollLeft = x;
46716 * Focuses the specified cell.
46717 * @param {Number} row The row index
46718 * @param {Number} col The column index
46719 * @param {Boolean} hscroll false to disable horizontal scrolling
46721 focusCell : function(row, col, hscroll){
46722 var el = this.ensureVisible(row, col, hscroll);
46723 this.focusEl.alignTo(el, "tl-tl");
46725 this.focusEl.focus();
46727 this.focusEl.focus.defer(1, this.focusEl);
46732 * Scrolls the specified cell into view
46733 * @param {Number} row The row index
46734 * @param {Number} col The column index
46735 * @param {Boolean} hscroll false to disable horizontal scrolling
46737 ensureVisible : function(row, col, hscroll){
46738 if(typeof row != "number"){
46739 row = row.rowIndex;
46741 if(row < 0 && row >= this.ds.getCount()){
46744 col = (col !== undefined ? col : 0);
46745 var cm = this.grid.colModel;
46746 while(cm.isHidden(col)){
46750 var el = this.getCell(row, col);
46754 var c = this.scroller.dom;
46756 var ctop = parseInt(el.offsetTop, 10);
46757 var cleft = parseInt(el.offsetLeft, 10);
46758 var cbot = ctop + el.offsetHeight;
46759 var cright = cleft + el.offsetWidth;
46761 var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
46762 var stop = parseInt(c.scrollTop, 10);
46763 var sleft = parseInt(c.scrollLeft, 10);
46764 var sbot = stop + ch;
46765 var sright = sleft + c.clientWidth;
46768 c.scrollTop = ctop;
46769 }else if(cbot > sbot){
46770 c.scrollTop = cbot-ch;
46773 if(hscroll !== false){
46775 c.scrollLeft = cleft;
46776 }else if(cright > sright){
46777 c.scrollLeft = cright-c.clientWidth;
46783 updateColumns : function(){
46784 this.grid.stopEditing();
46785 var cm = this.grid.colModel, colIds = this.getColumnIds();
46786 //var totalWidth = cm.getTotalWidth();
46788 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
46789 //if(cm.isHidden(i)) continue;
46790 var w = cm.getColumnWidth(i);
46791 this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
46792 this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
46794 this.updateSplitters();
46797 generateRules : function(cm){
46798 var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
46799 Roo.util.CSS.removeStyleSheet(rulesId);
46800 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
46801 var cid = cm.getColumnId(i);
46803 if(cm.config[i].align){
46804 align = 'text-align:'+cm.config[i].align+';';
46807 if(cm.isHidden(i)){
46808 hidden = 'display:none;';
46810 var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
46812 this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
46813 this.hdSelector, cid, " {\n", align, width, "}\n",
46814 this.tdSelector, cid, " {\n",hidden,"\n}\n",
46815 this.splitSelector, cid, " {\n", hidden , "\n}\n");
46817 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
46820 updateSplitters : function(){
46821 var cm = this.cm, s = this.getSplitters();
46822 if(s){ // splitters not created yet
46823 var pos = 0, locked = true;
46824 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
46825 if(cm.isHidden(i)) continue;
46826 var w = cm.getColumnWidth(i);
46827 if(!cm.isLocked(i) && locked){
46832 s[i].style.left = (pos-this.splitOffset) + "px";
46837 handleHiddenChange : function(colModel, colIndex, hidden){
46839 this.hideColumn(colIndex);
46841 this.unhideColumn(colIndex);
46845 hideColumn : function(colIndex){
46846 var cid = this.getColumnId(colIndex);
46847 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
46848 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
46850 this.updateHeaders();
46852 this.updateSplitters();
46856 unhideColumn : function(colIndex){
46857 var cid = this.getColumnId(colIndex);
46858 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
46859 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
46862 this.updateHeaders();
46864 this.updateSplitters();
46868 insertRows : function(dm, firstRow, lastRow, isUpdate){
46869 if(firstRow == 0 && lastRow == dm.getCount()-1){
46873 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
46875 var s = this.getScrollState();
46876 var markup = this.renderRows(firstRow, lastRow);
46877 this.bufferRows(markup[0], this.getLockedTable(), firstRow);
46878 this.bufferRows(markup[1], this.getBodyTable(), firstRow);
46879 this.restoreScroll(s);
46881 this.fireEvent("rowsinserted", this, firstRow, lastRow);
46882 this.syncRowHeights(firstRow, lastRow);
46883 this.stripeRows(firstRow);
46889 bufferRows : function(markup, target, index){
46890 var before = null, trows = target.rows, tbody = target.tBodies[0];
46891 if(index < trows.length){
46892 before = trows[index];
46894 var b = document.createElement("div");
46895 b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
46896 var rows = b.firstChild.rows;
46897 for(var i = 0, len = rows.length; i < len; i++){
46899 tbody.insertBefore(rows[0], before);
46901 tbody.appendChild(rows[0]);
46908 deleteRows : function(dm, firstRow, lastRow){
46909 if(dm.getRowCount()<1){
46910 this.fireEvent("beforerefresh", this);
46911 this.mainBody.update("");
46912 this.lockedBody.update("");
46913 this.fireEvent("refresh", this);
46915 this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
46916 var bt = this.getBodyTable();
46917 var tbody = bt.firstChild;
46918 var rows = bt.rows;
46919 for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
46920 tbody.removeChild(rows[firstRow]);
46922 this.stripeRows(firstRow);
46923 this.fireEvent("rowsdeleted", this, firstRow, lastRow);
46927 updateRows : function(dataSource, firstRow, lastRow){
46928 var s = this.getScrollState();
46930 this.restoreScroll(s);
46933 handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
46937 this.updateHeaderSortState();
46940 getScrollState : function(){
46941 var sb = this.scroller.dom;
46942 return {left: sb.scrollLeft, top: sb.scrollTop};
46945 stripeRows : function(startRow){
46946 if(!this.grid.stripeRows || this.ds.getCount() < 1){
46949 startRow = startRow || 0;
46950 var rows = this.getBodyTable().rows;
46951 var lrows = this.getLockedTable().rows;
46952 var cls = ' x-grid-row-alt ';
46953 for(var i = startRow, len = rows.length; i < len; i++){
46954 var row = rows[i], lrow = lrows[i];
46955 var isAlt = ((i+1) % 2 == 0);
46956 var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
46957 if(isAlt == hasAlt){
46961 row.className += " x-grid-row-alt";
46963 row.className = row.className.replace("x-grid-row-alt", "");
46966 lrow.className = row.className;
46971 restoreScroll : function(state){
46972 var sb = this.scroller.dom;
46973 sb.scrollLeft = state.left;
46974 sb.scrollTop = state.top;
46978 syncScroll : function(){
46979 var sb = this.scroller.dom;
46980 var sh = this.mainHd.dom;
46981 var bs = this.mainBody.dom;
46982 var lv = this.lockedBody.dom;
46983 sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
46984 lv.scrollTop = bs.scrollTop = sb.scrollTop;
46987 handleScroll : function(e){
46989 var sb = this.scroller.dom;
46990 this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
46994 handleWheel : function(e){
46995 var d = e.getWheelDelta();
46996 this.scroller.dom.scrollTop -= d*22;
46997 // set this here to prevent jumpy scrolling on large tables
46998 this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
47002 renderRows : function(startRow, endRow){
47003 // pull in all the crap needed to render rows
47004 var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
47005 var colCount = cm.getColumnCount();
47007 if(ds.getCount() < 1){
47011 // build a map for all the columns
47013 for(var i = 0; i < colCount; i++){
47014 var name = cm.getDataIndex(i);
47016 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
47017 renderer : cm.getRenderer(i),
47018 id : cm.getColumnId(i),
47019 locked : cm.isLocked(i)
47023 startRow = startRow || 0;
47024 endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
47026 // records to render
47027 var rs = ds.getRange(startRow, endRow);
47029 return this.doRender(cs, rs, ds, startRow, colCount, stripe);
47032 // As much as I hate to duplicate code, this was branched because FireFox really hates
47033 // [].join("") on strings. The performance difference was substantial enough to
47034 // branch this function
47035 doRender : Roo.isGecko ?
47036 function(cs, rs, ds, startRow, colCount, stripe){
47037 var ts = this.templates, ct = ts.cell, rt = ts.row;
47039 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
47040 for(var j = 0, len = rs.length; j < len; j++){
47041 r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
47042 for(var i = 0; i < colCount; i++){
47044 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
47046 p.css = p.attr = "";
47047 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
47048 if(p.value == undefined || p.value === "") p.value = " ";
47049 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
47050 p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
47052 var markup = ct.apply(p);
47060 if(stripe && ((rowIndex+1) % 2 == 0)){
47061 alt[0] = "x-grid-row-alt";
47064 alt[1] = " x-grid-dirty-row";
47067 if(this.getRowClass){
47068 alt[2] = this.getRowClass(r, rowIndex);
47070 rp.alt = alt.join(" ");
47071 lbuf+= rt.apply(rp);
47073 buf+= rt.apply(rp);
47075 return [lbuf, buf];
47077 function(cs, rs, ds, startRow, colCount, stripe){
47078 var ts = this.templates, ct = ts.cell, rt = ts.row;
47080 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
47081 for(var j = 0, len = rs.length; j < len; j++){
47082 r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
47083 for(var i = 0; i < colCount; i++){
47085 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
47087 p.css = p.attr = "";
47088 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
47089 if(p.value == undefined || p.value === "") p.value = " ";
47090 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
47091 p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
47093 var markup = ct.apply(p);
47095 cb[cb.length] = markup;
47097 lcb[lcb.length] = markup;
47101 if(stripe && ((rowIndex+1) % 2 == 0)){
47102 alt[0] = "x-grid-row-alt";
47105 alt[1] = " x-grid-dirty-row";
47108 if(this.getRowClass){
47109 alt[2] = this.getRowClass(r, rowIndex);
47111 rp.alt = alt.join(" ");
47112 rp.cells = lcb.join("");
47113 lbuf[lbuf.length] = rt.apply(rp);
47114 rp.cells = cb.join("");
47115 buf[buf.length] = rt.apply(rp);
47117 return [lbuf.join(""), buf.join("")];
47120 renderBody : function(){
47121 var markup = this.renderRows();
47122 var bt = this.templates.body;
47123 return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
47127 * Refreshes the grid
47128 * @param {Boolean} headersToo
47130 refresh : function(headersToo){
47131 this.fireEvent("beforerefresh", this);
47132 this.grid.stopEditing();
47133 var result = this.renderBody();
47134 this.lockedBody.update(result[0]);
47135 this.mainBody.update(result[1]);
47136 if(headersToo === true){
47137 this.updateHeaders();
47138 this.updateColumns();
47139 this.updateSplitters();
47140 this.updateHeaderSortState();
47142 this.syncRowHeights();
47144 this.fireEvent("refresh", this);
47147 handleColumnMove : function(cm, oldIndex, newIndex){
47148 this.indexMap = null;
47149 var s = this.getScrollState();
47150 this.refresh(true);
47151 this.restoreScroll(s);
47152 this.afterMove(newIndex);
47155 afterMove : function(colIndex){
47156 if(this.enableMoveAnim && Roo.enableFx){
47157 this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
47161 updateCell : function(dm, rowIndex, dataIndex){
47162 var colIndex = this.getColumnIndexByDataIndex(dataIndex);
47163 if(typeof colIndex == "undefined"){ // not present in grid
47166 var cm = this.grid.colModel;
47167 var cell = this.getCell(rowIndex, colIndex);
47168 var cellText = this.getCellText(rowIndex, colIndex);
47171 cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
47172 id : cm.getColumnId(colIndex),
47173 css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
47175 var renderer = cm.getRenderer(colIndex);
47176 var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
47177 if(typeof val == "undefined" || val === "") val = " ";
47178 cellText.innerHTML = val;
47179 cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
47180 this.syncRowHeights(rowIndex, rowIndex);
47183 calcColumnWidth : function(colIndex, maxRowsToMeasure){
47185 if(this.grid.autoSizeHeaders){
47186 var h = this.getHeaderCellMeasure(colIndex);
47187 maxWidth = Math.max(maxWidth, h.scrollWidth);
47190 if(this.cm.isLocked(colIndex)){
47191 tb = this.getLockedTable();
47194 tb = this.getBodyTable();
47195 index = colIndex - this.cm.getLockedCount();
47198 var rows = tb.rows;
47199 var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
47200 for(var i = 0; i < stopIndex; i++){
47201 var cell = rows[i].childNodes[index].firstChild;
47202 maxWidth = Math.max(maxWidth, cell.scrollWidth);
47205 return maxWidth + /*margin for error in IE*/ 5;
47208 * Autofit a column to its content.
47209 * @param {Number} colIndex
47210 * @param {Boolean} forceMinSize true to force the column to go smaller if possible
47212 autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
47213 if(this.cm.isHidden(colIndex)){
47214 return; // can't calc a hidden column
47217 var cid = this.cm.getColumnId(colIndex);
47218 this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
47219 if(this.grid.autoSizeHeaders){
47220 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
47223 var newWidth = this.calcColumnWidth(colIndex);
47224 this.cm.setColumnWidth(colIndex,
47225 Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
47226 if(!suppressEvent){
47227 this.grid.fireEvent("columnresize", colIndex, newWidth);
47232 * Autofits all columns to their content and then expands to fit any extra space in the grid
47234 autoSizeColumns : function(){
47235 var cm = this.grid.colModel;
47236 var colCount = cm.getColumnCount();
47237 for(var i = 0; i < colCount; i++){
47238 this.autoSizeColumn(i, true, true);
47240 if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
47243 this.updateColumns();
47249 * Autofits all columns to the grid's width proportionate with their current size
47250 * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
47252 fitColumns : function(reserveScrollSpace){
47253 var cm = this.grid.colModel;
47254 var colCount = cm.getColumnCount();
47258 for (i = 0; i < colCount; i++){
47259 if(!cm.isHidden(i) && !cm.isFixed(i)){
47260 w = cm.getColumnWidth(i);
47266 var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
47267 if(reserveScrollSpace){
47270 var frac = (avail - cm.getTotalWidth())/width;
47271 while (cols.length){
47274 cm.setColumnWidth(i, Math.floor(w + w*frac), true);
47276 this.updateColumns();
47280 onRowSelect : function(rowIndex){
47281 var row = this.getRowComposite(rowIndex);
47282 row.addClass("x-grid-row-selected");
47285 onRowDeselect : function(rowIndex){
47286 var row = this.getRowComposite(rowIndex);
47287 row.removeClass("x-grid-row-selected");
47290 onCellSelect : function(row, col){
47291 var cell = this.getCell(row, col);
47293 Roo.fly(cell).addClass("x-grid-cell-selected");
47297 onCellDeselect : function(row, col){
47298 var cell = this.getCell(row, col);
47300 Roo.fly(cell).removeClass("x-grid-cell-selected");
47304 updateHeaderSortState : function(){
47305 var state = this.ds.getSortState();
47309 this.sortState = state;
47310 var sortColumn = this.cm.findColumnIndex(state.field);
47311 if(sortColumn != -1){
47312 var sortDir = state.direction;
47313 var sc = this.sortClasses;
47314 var hds = this.el.select(this.headerSelector).removeClass(sc);
47315 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
47319 handleHeaderClick : function(g, index){
47320 if(this.headersDisabled){
47323 var dm = g.dataSource, cm = g.colModel;
47324 if(!cm.isSortable(index)){
47328 dm.sort(cm.getDataIndex(index));
47332 destroy : function(){
47334 this.colMenu.removeAll();
47335 Roo.menu.MenuMgr.unregister(this.colMenu);
47336 this.colMenu.getEl().remove();
47337 delete this.colMenu;
47340 this.hmenu.removeAll();
47341 Roo.menu.MenuMgr.unregister(this.hmenu);
47342 this.hmenu.getEl().remove();
47345 if(this.grid.enableColumnMove){
47346 var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
47348 for(var dd in dds){
47349 if(!dds[dd].config.isTarget && dds[dd].dragElId){
47350 var elid = dds[dd].dragElId;
47352 Roo.get(elid).remove();
47353 } else if(dds[dd].config.isTarget){
47354 dds[dd].proxyTop.remove();
47355 dds[dd].proxyBottom.remove();
47358 if(Roo.dd.DDM.locationCache[dd]){
47359 delete Roo.dd.DDM.locationCache[dd];
47362 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
47365 Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
47366 this.bind(null, null);
47367 Roo.EventManager.removeResizeListener(this.onWindowResize, this);
47370 handleLockChange : function(){
47371 this.refresh(true);
47374 onDenyColumnLock : function(){
47378 onDenyColumnHide : function(){
47382 handleHdMenuClick : function(item){
47383 var index = this.hdCtxIndex;
47384 var cm = this.cm, ds = this.ds;
47387 ds.sort(cm.getDataIndex(index), "ASC");
47390 ds.sort(cm.getDataIndex(index), "DESC");
47393 var lc = cm.getLockedCount();
47394 if(cm.getColumnCount(true) <= lc+1){
47395 this.onDenyColumnLock();
47399 cm.setLocked(index, true, true);
47400 cm.moveColumn(index, lc);
47401 this.grid.fireEvent("columnmove", index, lc);
47403 cm.setLocked(index, true);
47407 var lc = cm.getLockedCount();
47408 if((lc-1) != index){
47409 cm.setLocked(index, false, true);
47410 cm.moveColumn(index, lc-1);
47411 this.grid.fireEvent("columnmove", index, lc-1);
47413 cm.setLocked(index, false);
47417 index = cm.getIndexById(item.id.substr(4));
47419 if(item.checked && cm.getColumnCount(true) <= 1){
47420 this.onDenyColumnHide();
47423 cm.setHidden(index, item.checked);
47429 beforeColMenuShow : function(){
47430 var cm = this.cm, colCount = cm.getColumnCount();
47431 this.colMenu.removeAll();
47432 for(var i = 0; i < colCount; i++){
47433 this.colMenu.add(new Roo.menu.CheckItem({
47434 id: "col-"+cm.getColumnId(i),
47435 text: cm.getColumnHeader(i),
47436 checked: !cm.isHidden(i),
47442 handleHdCtx : function(g, index, e){
47444 var hd = this.getHeaderCell(index);
47445 this.hdCtxIndex = index;
47446 var ms = this.hmenu.items, cm = this.cm;
47447 ms.get("asc").setDisabled(!cm.isSortable(index));
47448 ms.get("desc").setDisabled(!cm.isSortable(index));
47449 if(this.grid.enableColLock !== false){
47450 ms.get("lock").setDisabled(cm.isLocked(index));
47451 ms.get("unlock").setDisabled(!cm.isLocked(index));
47453 this.hmenu.show(hd, "tl-bl");
47456 handleHdOver : function(e){
47457 var hd = this.findHeaderCell(e.getTarget());
47458 if(hd && !this.headersDisabled){
47459 if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
47460 this.fly(hd).addClass("x-grid-hd-over");
47465 handleHdOut : function(e){
47466 var hd = this.findHeaderCell(e.getTarget());
47468 this.fly(hd).removeClass("x-grid-hd-over");
47472 handleSplitDblClick : function(e, t){
47473 var i = this.getCellIndex(t);
47474 if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
47475 this.autoSizeColumn(i, true);
47480 render : function(){
47483 var colCount = cm.getColumnCount();
47485 if(this.grid.monitorWindowResize === true){
47486 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
47488 var header = this.renderHeaders();
47489 var body = this.templates.body.apply({rows:""});
47490 var html = this.templates.master.apply({
47493 lockedHeader: header[0],
47497 //this.updateColumns();
47499 this.grid.getGridEl().dom.innerHTML = html;
47501 this.initElements();
47503 this.scroller.on("scroll", this.handleScroll, this);
47504 this.lockedBody.on("mousewheel", this.handleWheel, this);
47505 this.mainBody.on("mousewheel", this.handleWheel, this);
47507 this.mainHd.on("mouseover", this.handleHdOver, this);
47508 this.mainHd.on("mouseout", this.handleHdOut, this);
47509 this.mainHd.on("dblclick", this.handleSplitDblClick, this,
47510 {delegate: "."+this.splitClass});
47512 this.lockedHd.on("mouseover", this.handleHdOver, this);
47513 this.lockedHd.on("mouseout", this.handleHdOut, this);
47514 this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
47515 {delegate: "."+this.splitClass});
47517 if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
47518 new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
47521 this.updateSplitters();
47523 if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
47524 new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
47525 new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
47528 if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
47529 this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
47531 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
47532 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
47534 if(this.grid.enableColLock !== false){
47535 this.hmenu.add('-',
47536 {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
47537 {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
47540 if(this.grid.enableColumnHide !== false){
47542 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
47543 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
47544 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
47546 this.hmenu.add('-',
47547 {id:"columns", text: this.columnsText, menu: this.colMenu}
47550 this.hmenu.on("itemclick", this.handleHdMenuClick, this);
47552 this.grid.on("headercontextmenu", this.handleHdCtx, this);
47555 if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
47556 this.dd = new Roo.grid.GridDragZone(this.grid, {
47557 ddGroup : this.grid.ddGroup || 'GridDD'
47562 for(var i = 0; i < colCount; i++){
47563 if(cm.isHidden(i)){
47564 this.hideColumn(i);
47566 if(cm.config[i].align){
47567 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
47568 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
47572 this.updateHeaderSortState();
47574 this.beforeInitialResize();
47577 // two part rendering gives faster view to the user
47578 this.renderPhase2.defer(1, this);
47581 renderPhase2 : function(){
47582 // render the rows now
47584 if(this.grid.autoSizeColumns){
47585 this.autoSizeColumns();
47589 beforeInitialResize : function(){
47593 onColumnSplitterMoved : function(i, w){
47594 this.userResized = true;
47595 var cm = this.grid.colModel;
47596 cm.setColumnWidth(i, w, true);
47597 var cid = cm.getColumnId(i);
47598 this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
47599 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
47600 this.updateSplitters();
47602 this.grid.fireEvent("columnresize", i, w);
47605 syncRowHeights : function(startIndex, endIndex){
47606 if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
47607 startIndex = startIndex || 0;
47608 var mrows = this.getBodyTable().rows;
47609 var lrows = this.getLockedTable().rows;
47610 var len = mrows.length-1;
47611 endIndex = Math.min(endIndex || len, len);
47612 for(var i = startIndex; i <= endIndex; i++){
47613 var m = mrows[i], l = lrows[i];
47614 var h = Math.max(m.offsetHeight, l.offsetHeight);
47615 m.style.height = l.style.height = h + "px";
47620 layout : function(initialRender, is2ndPass){
47622 var auto = g.autoHeight;
47623 var scrollOffset = 16;
47624 var c = g.getGridEl(), cm = this.cm,
47625 expandCol = g.autoExpandColumn,
47627 //c.beginMeasure();
47629 if(!c.dom.offsetWidth){ // display:none?
47631 this.lockedWrap.show();
47632 this.mainWrap.show();
47637 var hasLock = this.cm.isLocked(0);
47639 var tbh = this.headerPanel.getHeight();
47640 var bbh = this.footerPanel.getHeight();
47643 var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
47644 var newHeight = ch + c.getBorderWidth("tb");
47646 newHeight = Math.min(g.maxHeight, newHeight);
47648 c.setHeight(newHeight);
47652 c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
47655 var s = this.scroller;
47657 var csize = c.getSize(true);
47659 this.el.setSize(csize.width, csize.height);
47661 this.headerPanel.setWidth(csize.width);
47662 this.footerPanel.setWidth(csize.width);
47664 var hdHeight = this.mainHd.getHeight();
47665 var vw = csize.width;
47666 var vh = csize.height - (tbh + bbh);
47670 var bt = this.getBodyTable();
47671 var ltWidth = hasLock ?
47672 Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
47674 var scrollHeight = bt.offsetHeight;
47675 var scrollWidth = ltWidth + bt.offsetWidth;
47676 var vscroll = false, hscroll = false;
47678 this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
47680 var lw = this.lockedWrap, mw = this.mainWrap;
47681 var lb = this.lockedBody, mb = this.mainBody;
47683 setTimeout(function(){
47684 var t = s.dom.offsetTop;
47685 var w = s.dom.clientWidth,
47686 h = s.dom.clientHeight;
47689 lw.setSize(ltWidth, h);
47691 mw.setLeftTop(ltWidth, t);
47692 mw.setSize(w-ltWidth, h);
47694 lb.setHeight(h-hdHeight);
47695 mb.setHeight(h-hdHeight);
47697 if(is2ndPass !== true && !gv.userResized && expandCol){
47698 // high speed resize without full column calculation
47700 var ci = cm.getIndexById(expandCol);
47702 ci = cm.findColumnIndex(expandCol);
47704 ci = Math.max(0, ci); // make sure it's got at least the first col.
47705 var expandId = cm.getColumnId(ci);
47706 var tw = cm.getTotalWidth(false);
47707 var currentWidth = cm.getColumnWidth(ci);
47708 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
47709 if(currentWidth != cw){
47710 cm.setColumnWidth(ci, cw, true);
47711 gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
47712 gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
47713 gv.updateSplitters();
47714 gv.layout(false, true);
47726 onWindowResize : function(){
47727 if(!this.grid.monitorWindowResize || this.grid.autoHeight){
47733 appendFooter : function(parentEl){
47737 sortAscText : "Sort Ascending",
47738 sortDescText : "Sort Descending",
47739 lockText : "Lock Column",
47740 unlockText : "Unlock Column",
47741 columnsText : "Columns"
47745 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
47746 Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
47747 this.proxy.el.addClass('x-grid3-col-dd');
47750 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
47751 handleMouseDown : function(e){
47755 callHandleMouseDown : function(e){
47756 Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
47761 * Ext JS Library 1.1.1
47762 * Copyright(c) 2006-2007, Ext JS, LLC.
47764 * Originally Released Under LGPL - original licence link has changed is not relivant.
47767 * <script type="text/javascript">
47771 // This is a support class used internally by the Grid components
47772 Roo.grid.SplitDragZone = function(grid, hd, hd2){
47774 this.view = grid.getView();
47775 this.proxy = this.view.resizeProxy;
47776 Roo.grid.SplitDragZone.superclass.constructor.call(this, hd,
47777 "gridSplitters" + this.grid.getGridEl().id, {
47778 dragElId : Roo.id(this.proxy.dom), resizeFrame:false
47780 this.setHandleElId(Roo.id(hd));
47781 this.setOuterHandleElId(Roo.id(hd2));
47782 this.scroll = false;
47784 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
47785 fly: Roo.Element.fly,
47787 b4StartDrag : function(x, y){
47788 this.view.headersDisabled = true;
47789 this.proxy.setHeight(this.view.mainWrap.getHeight());
47790 var w = this.cm.getColumnWidth(this.cellIndex);
47791 var minw = Math.max(w-this.grid.minColumnWidth, 0);
47792 this.resetConstraints();
47793 this.setXConstraint(minw, 1000);
47794 this.setYConstraint(0, 0);
47795 this.minX = x - minw;
47796 this.maxX = x + 1000;
47798 Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
47802 handleMouseDown : function(e){
47803 ev = Roo.EventObject.setEvent(e);
47804 var t = this.fly(ev.getTarget());
47805 if(t.hasClass("x-grid-split")){
47806 this.cellIndex = this.view.getCellIndex(t.dom);
47807 this.split = t.dom;
47808 this.cm = this.grid.colModel;
47809 if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
47810 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
47815 endDrag : function(e){
47816 this.view.headersDisabled = false;
47817 var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
47818 var diff = endX - this.startPos;
47819 this.view.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff);
47822 autoOffset : function(){
47823 this.setDelta(0,0);
47827 * Ext JS Library 1.1.1
47828 * Copyright(c) 2006-2007, Ext JS, LLC.
47830 * Originally Released Under LGPL - original licence link has changed is not relivant.
47833 * <script type="text/javascript">
47837 // This is a support class used internally by the Grid components
47838 Roo.grid.GridDragZone = function(grid, config){
47839 this.view = grid.getView();
47840 Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
47841 if(this.view.lockedBody){
47842 this.setHandleElId(Roo.id(this.view.mainBody.dom));
47843 this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
47845 this.scroll = false;
47847 this.ddel = document.createElement('div');
47848 this.ddel.className = 'x-grid-dd-wrap';
47851 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
47852 ddGroup : "GridDD",
47854 getDragData : function(e){
47855 var t = Roo.lib.Event.getTarget(e);
47856 var rowIndex = this.view.findRowIndex(t);
47857 if(rowIndex !== false){
47858 var sm = this.grid.selModel;
47859 //if(!sm.isSelected(rowIndex) || e.hasModifier()){
47860 // sm.mouseDown(e, t);
47862 if (e.hasModifier()){
47863 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
47865 return {grid: this.grid, ddel: this.ddel, rowIndex: rowIndex, selections:sm.getSelections()};
47870 onInitDrag : function(e){
47871 var data = this.dragData;
47872 this.ddel.innerHTML = this.grid.getDragDropText();
47873 this.proxy.update(this.ddel);
47874 // fire start drag?
47877 afterRepair : function(){
47878 this.dragging = false;
47881 getRepairXY : function(e, data){
47885 onEndDrag : function(data, e){
47889 onValidDrop : function(dd, e, id){
47894 beforeInvalidDrop : function(e, id){
47899 * Ext JS Library 1.1.1
47900 * Copyright(c) 2006-2007, Ext JS, LLC.
47902 * Originally Released Under LGPL - original licence link has changed is not relivant.
47905 * <script type="text/javascript">
47910 * @class Roo.grid.ColumnModel
47911 * @extends Roo.util.Observable
47912 * This is the default implementation of a ColumnModel used by the Grid. It defines
47913 * the columns in the grid.
47916 var colModel = new Roo.grid.ColumnModel([
47917 {header: "Ticker", width: 60, sortable: true, locked: true},
47918 {header: "Company Name", width: 150, sortable: true},
47919 {header: "Market Cap.", width: 100, sortable: true},
47920 {header: "$ Sales", width: 100, sortable: true, renderer: money},
47921 {header: "Employees", width: 100, sortable: true, resizable: false}
47926 * The config options listed for this class are options which may appear in each
47927 * individual column definition.
47928 * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
47930 * @param {Object} config An Array of column config objects. See this class's
47931 * config objects for details.
47933 Roo.grid.ColumnModel = function(config){
47935 * The config passed into the constructor
47937 this.config = config;
47940 // if no id, create one
47941 // if the column does not have a dataIndex mapping,
47942 // map it to the order it is in the config
47943 for(var i = 0, len = config.length; i < len; i++){
47945 if(typeof c.dataIndex == "undefined"){
47948 if(typeof c.renderer == "string"){
47949 c.renderer = Roo.util.Format[c.renderer];
47951 if(typeof c.id == "undefined"){
47954 if(c.editor && c.editor.xtype){
47955 c.editor = Roo.factory(c.editor, Roo.grid);
47957 if(c.editor && c.editor.isFormField){
47958 c.editor = new Roo.grid.GridEditor(c.editor);
47960 this.lookup[c.id] = c;
47964 * The width of columns which have no width specified (defaults to 100)
47967 this.defaultWidth = 100;
47970 * Default sortable of columns which have no sortable specified (defaults to false)
47973 this.defaultSortable = false;
47977 * @event widthchange
47978 * Fires when the width of a column changes.
47979 * @param {ColumnModel} this
47980 * @param {Number} columnIndex The column index
47981 * @param {Number} newWidth The new width
47983 "widthchange": true,
47985 * @event headerchange
47986 * Fires when the text of a header changes.
47987 * @param {ColumnModel} this
47988 * @param {Number} columnIndex The column index
47989 * @param {Number} newText The new header text
47991 "headerchange": true,
47993 * @event hiddenchange
47994 * Fires when a column is hidden or "unhidden".
47995 * @param {ColumnModel} this
47996 * @param {Number} columnIndex The column index
47997 * @param {Boolean} hidden true if hidden, false otherwise
47999 "hiddenchange": true,
48001 * @event columnmoved
48002 * Fires when a column is moved.
48003 * @param {ColumnModel} this
48004 * @param {Number} oldIndex
48005 * @param {Number} newIndex
48007 "columnmoved" : true,
48009 * @event columlockchange
48010 * Fires when a column's locked state is changed
48011 * @param {ColumnModel} this
48012 * @param {Number} colIndex
48013 * @param {Boolean} locked true if locked
48015 "columnlockchange" : true
48017 Roo.grid.ColumnModel.superclass.constructor.call(this);
48019 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
48021 * @cfg {String} header The header text to display in the Grid view.
48024 * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
48025 * {@link Roo.data.Record} definition from which to draw the column's value. If not
48026 * specified, the column's index is used as an index into the Record's data Array.
48029 * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
48030 * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
48033 * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
48034 * Defaults to the value of the {@link #defaultSortable} property.
48035 * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
48038 * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid. Defaults to false.
48041 * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed. Defaults to false.
48044 * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
48047 * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
48050 * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
48051 * given the cell's data value. See {@link #setRenderer}. If not specified, the
48052 * default renderer uses the raw data value.
48055 * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor
48058 * @cfg {String} align (Optional) Set the CSS text-align property of the column. Defaults to undefined.
48062 * Returns the id of the column at the specified index.
48063 * @param {Number} index The column index
48064 * @return {String} the id
48066 getColumnId : function(index){
48067 return this.config[index].id;
48071 * Returns the column for a specified id.
48072 * @param {String} id The column id
48073 * @return {Object} the column
48075 getColumnById : function(id){
48076 return this.lookup[id];
48080 * Returns the index for a specified column id.
48081 * @param {String} id The column id
48082 * @return {Number} the index, or -1 if not found
48084 getIndexById : function(id){
48085 for(var i = 0, len = this.config.length; i < len; i++){
48086 if(this.config[i].id == id){
48093 * Returns the index for a specified column dataIndex.
48094 * @param {String} dataIndex The column dataIndex
48095 * @return {Number} the index, or -1 if not found
48098 findColumnIndex : function(dataIndex){
48099 for(var i = 0, len = this.config.length; i < len; i++){
48100 if(this.config[i].dataIndex == dataIndex){
48108 moveColumn : function(oldIndex, newIndex){
48109 var c = this.config[oldIndex];
48110 this.config.splice(oldIndex, 1);
48111 this.config.splice(newIndex, 0, c);
48112 this.dataMap = null;
48113 this.fireEvent("columnmoved", this, oldIndex, newIndex);
48116 isLocked : function(colIndex){
48117 return this.config[colIndex].locked === true;
48120 setLocked : function(colIndex, value, suppressEvent){
48121 if(this.isLocked(colIndex) == value){
48124 this.config[colIndex].locked = value;
48125 if(!suppressEvent){
48126 this.fireEvent("columnlockchange", this, colIndex, value);
48130 getTotalLockedWidth : function(){
48131 var totalWidth = 0;
48132 for(var i = 0; i < this.config.length; i++){
48133 if(this.isLocked(i) && !this.isHidden(i)){
48134 this.totalWidth += this.getColumnWidth(i);
48140 getLockedCount : function(){
48141 for(var i = 0, len = this.config.length; i < len; i++){
48142 if(!this.isLocked(i)){
48149 * Returns the number of columns.
48152 getColumnCount : function(visibleOnly){
48153 if(visibleOnly === true){
48155 for(var i = 0, len = this.config.length; i < len; i++){
48156 if(!this.isHidden(i)){
48162 return this.config.length;
48166 * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
48167 * @param {Function} fn
48168 * @param {Object} scope (optional)
48169 * @return {Array} result
48171 getColumnsBy : function(fn, scope){
48173 for(var i = 0, len = this.config.length; i < len; i++){
48174 var c = this.config[i];
48175 if(fn.call(scope||this, c, i) === true){
48183 * Returns true if the specified column is sortable.
48184 * @param {Number} col The column index
48185 * @return {Boolean}
48187 isSortable : function(col){
48188 if(typeof this.config[col].sortable == "undefined"){
48189 return this.defaultSortable;
48191 return this.config[col].sortable;
48195 * Returns the rendering (formatting) function defined for the column.
48196 * @param {Number} col The column index.
48197 * @return {Function} The function used to render the cell. See {@link #setRenderer}.
48199 getRenderer : function(col){
48200 if(!this.config[col].renderer){
48201 return Roo.grid.ColumnModel.defaultRenderer;
48203 return this.config[col].renderer;
48207 * Sets the rendering (formatting) function for a column.
48208 * @param {Number} col The column index
48209 * @param {Function} fn The function to use to process the cell's raw data
48210 * to return HTML markup for the grid view. The render function is called with
48211 * the following parameters:<ul>
48212 * <li>Data value.</li>
48213 * <li>Cell metadata. An object in which you may set the following attributes:<ul>
48214 * <li>css A CSS style string to apply to the table cell.</li>
48215 * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
48216 * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
48217 * <li>Row index</li>
48218 * <li>Column index</li>
48219 * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
48221 setRenderer : function(col, fn){
48222 this.config[col].renderer = fn;
48226 * Returns the width for the specified column.
48227 * @param {Number} col The column index
48230 getColumnWidth : function(col){
48231 return this.config[col].width || this.defaultWidth;
48235 * Sets the width for a column.
48236 * @param {Number} col The column index
48237 * @param {Number} width The new width
48239 setColumnWidth : function(col, width, suppressEvent){
48240 this.config[col].width = width;
48241 this.totalWidth = null;
48242 if(!suppressEvent){
48243 this.fireEvent("widthchange", this, col, width);
48248 * Returns the total width of all columns.
48249 * @param {Boolean} includeHidden True to include hidden column widths
48252 getTotalWidth : function(includeHidden){
48253 if(!this.totalWidth){
48254 this.totalWidth = 0;
48255 for(var i = 0, len = this.config.length; i < len; i++){
48256 if(includeHidden || !this.isHidden(i)){
48257 this.totalWidth += this.getColumnWidth(i);
48261 return this.totalWidth;
48265 * Returns the header for the specified column.
48266 * @param {Number} col The column index
48269 getColumnHeader : function(col){
48270 return this.config[col].header;
48274 * Sets the header for a column.
48275 * @param {Number} col The column index
48276 * @param {String} header The new header
48278 setColumnHeader : function(col, header){
48279 this.config[col].header = header;
48280 this.fireEvent("headerchange", this, col, header);
48284 * Returns the tooltip for the specified column.
48285 * @param {Number} col The column index
48288 getColumnTooltip : function(col){
48289 return this.config[col].tooltip;
48292 * Sets the tooltip for a column.
48293 * @param {Number} col The column index
48294 * @param {String} tooltip The new tooltip
48296 setColumnTooltip : function(col, tooltip){
48297 this.config[col].tooltip = tooltip;
48301 * Returns the dataIndex for the specified column.
48302 * @param {Number} col The column index
48305 getDataIndex : function(col){
48306 return this.config[col].dataIndex;
48310 * Sets the dataIndex for a column.
48311 * @param {Number} col The column index
48312 * @param {Number} dataIndex The new dataIndex
48314 setDataIndex : function(col, dataIndex){
48315 this.config[col].dataIndex = dataIndex;
48321 * Returns true if the cell is editable.
48322 * @param {Number} colIndex The column index
48323 * @param {Number} rowIndex The row index
48324 * @return {Boolean}
48326 isCellEditable : function(colIndex, rowIndex){
48327 return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
48331 * Returns the editor defined for the cell/column.
48332 * return false or null to disable editing.
48333 * @param {Number} colIndex The column index
48334 * @param {Number} rowIndex The row index
48337 getCellEditor : function(colIndex, rowIndex){
48338 return this.config[colIndex].editor;
48342 * Sets if a column is editable.
48343 * @param {Number} col The column index
48344 * @param {Boolean} editable True if the column is editable
48346 setEditable : function(col, editable){
48347 this.config[col].editable = editable;
48352 * Returns true if the column is hidden.
48353 * @param {Number} colIndex The column index
48354 * @return {Boolean}
48356 isHidden : function(colIndex){
48357 return this.config[colIndex].hidden;
48362 * Returns true if the column width cannot be changed
48364 isFixed : function(colIndex){
48365 return this.config[colIndex].fixed;
48369 * Returns true if the column can be resized
48370 * @return {Boolean}
48372 isResizable : function(colIndex){
48373 return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
48376 * Sets if a column is hidden.
48377 * @param {Number} colIndex The column index
48378 * @param {Boolean} hidden True if the column is hidden
48380 setHidden : function(colIndex, hidden){
48381 this.config[colIndex].hidden = hidden;
48382 this.totalWidth = null;
48383 this.fireEvent("hiddenchange", this, colIndex, hidden);
48387 * Sets the editor for a column.
48388 * @param {Number} col The column index
48389 * @param {Object} editor The editor object
48391 setEditor : function(col, editor){
48392 this.config[col].editor = editor;
48396 Roo.grid.ColumnModel.defaultRenderer = function(value){
48397 if(typeof value == "string" && value.length < 1){
48403 // Alias for backwards compatibility
48404 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
48407 * Ext JS Library 1.1.1
48408 * Copyright(c) 2006-2007, Ext JS, LLC.
48410 * Originally Released Under LGPL - original licence link has changed is not relivant.
48413 * <script type="text/javascript">
48417 * @class Roo.grid.AbstractSelectionModel
48418 * @extends Roo.util.Observable
48419 * Abstract base class for grid SelectionModels. It provides the interface that should be
48420 * implemented by descendant classes. This class should not be directly instantiated.
48423 Roo.grid.AbstractSelectionModel = function(){
48424 this.locked = false;
48425 Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
48428 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable, {
48429 /** @ignore Called by the grid automatically. Do not call directly. */
48430 init : function(grid){
48436 * Locks the selections.
48439 this.locked = true;
48443 * Unlocks the selections.
48445 unlock : function(){
48446 this.locked = false;
48450 * Returns true if the selections are locked.
48451 * @return {Boolean}
48453 isLocked : function(){
48454 return this.locked;
48458 * Ext JS Library 1.1.1
48459 * Copyright(c) 2006-2007, Ext JS, LLC.
48461 * Originally Released Under LGPL - original licence link has changed is not relivant.
48464 * <script type="text/javascript">
48467 * @extends Roo.grid.AbstractSelectionModel
48468 * @class Roo.grid.RowSelectionModel
48469 * The default SelectionModel used by {@link Roo.grid.Grid}.
48470 * It supports multiple selections and keyboard selection/navigation.
48472 * @param {Object} config
48474 Roo.grid.RowSelectionModel = function(config){
48475 Roo.apply(this, config);
48476 this.selections = new Roo.util.MixedCollection(false, function(o){
48481 this.lastActive = false;
48485 * @event selectionchange
48486 * Fires when the selection changes
48487 * @param {SelectionModel} this
48489 "selectionchange" : true,
48491 * @event afterselectionchange
48492 * Fires after the selection changes (eg. by key press or clicking)
48493 * @param {SelectionModel} this
48495 "afterselectionchange" : true,
48497 * @event beforerowselect
48498 * Fires when a row is selected being selected, return false to cancel.
48499 * @param {SelectionModel} this
48500 * @param {Number} rowIndex The selected index
48501 * @param {Boolean} keepExisting False if other selections will be cleared
48503 "beforerowselect" : true,
48506 * Fires when a row is selected.
48507 * @param {SelectionModel} this
48508 * @param {Number} rowIndex The selected index
48509 * @param {Roo.data.Record} r The record
48511 "rowselect" : true,
48513 * @event rowdeselect
48514 * Fires when a row is deselected.
48515 * @param {SelectionModel} this
48516 * @param {Number} rowIndex The selected index
48518 "rowdeselect" : true
48520 Roo.grid.RowSelectionModel.superclass.constructor.call(this);
48521 this.locked = false;
48524 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel, {
48526 * @cfg {Boolean} singleSelect
48527 * True to allow selection of only one row at a time (defaults to false)
48529 singleSelect : false,
48532 initEvents : function(){
48534 if(!this.grid.enableDragDrop && !this.grid.enableDrag){
48535 this.grid.on("mousedown", this.handleMouseDown, this);
48536 }else{ // allow click to work like normal
48537 this.grid.on("rowclick", this.handleDragableRowClick, this);
48540 this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
48541 "up" : function(e){
48543 this.selectPrevious(e.shiftKey);
48544 }else if(this.last !== false && this.lastActive !== false){
48545 var last = this.last;
48546 this.selectRange(this.last, this.lastActive-1);
48547 this.grid.getView().focusRow(this.lastActive);
48548 if(last !== false){
48552 this.selectFirstRow();
48554 this.fireEvent("afterselectionchange", this);
48556 "down" : function(e){
48558 this.selectNext(e.shiftKey);
48559 }else if(this.last !== false && this.lastActive !== false){
48560 var last = this.last;
48561 this.selectRange(this.last, this.lastActive+1);
48562 this.grid.getView().focusRow(this.lastActive);
48563 if(last !== false){
48567 this.selectFirstRow();
48569 this.fireEvent("afterselectionchange", this);
48574 var view = this.grid.view;
48575 view.on("refresh", this.onRefresh, this);
48576 view.on("rowupdated", this.onRowUpdated, this);
48577 view.on("rowremoved", this.onRemove, this);
48581 onRefresh : function(){
48582 var ds = this.grid.dataSource, i, v = this.grid.view;
48583 var s = this.selections;
48584 s.each(function(r){
48585 if((i = ds.indexOfId(r.id)) != -1){
48594 onRemove : function(v, index, r){
48595 this.selections.remove(r);
48599 onRowUpdated : function(v, index, r){
48600 if(this.isSelected(r)){
48601 v.onRowSelect(index);
48607 * @param {Array} records The records to select
48608 * @param {Boolean} keepExisting (optional) True to keep existing selections
48610 selectRecords : function(records, keepExisting){
48612 this.clearSelections();
48614 var ds = this.grid.dataSource;
48615 for(var i = 0, len = records.length; i < len; i++){
48616 this.selectRow(ds.indexOf(records[i]), true);
48621 * Gets the number of selected rows.
48624 getCount : function(){
48625 return this.selections.length;
48629 * Selects the first row in the grid.
48631 selectFirstRow : function(){
48636 * Select the last row.
48637 * @param {Boolean} keepExisting (optional) True to keep existing selections
48639 selectLastRow : function(keepExisting){
48640 this.selectRow(this.grid.dataSource.getCount() - 1, keepExisting);
48644 * Selects the row immediately following the last selected row.
48645 * @param {Boolean} keepExisting (optional) True to keep existing selections
48647 selectNext : function(keepExisting){
48648 if(this.last !== false && (this.last+1) < this.grid.dataSource.getCount()){
48649 this.selectRow(this.last+1, keepExisting);
48650 this.grid.getView().focusRow(this.last);
48655 * Selects the row that precedes the last selected row.
48656 * @param {Boolean} keepExisting (optional) True to keep existing selections
48658 selectPrevious : function(keepExisting){
48660 this.selectRow(this.last-1, keepExisting);
48661 this.grid.getView().focusRow(this.last);
48666 * Returns the selected records
48667 * @return {Array} Array of selected records
48669 getSelections : function(){
48670 return [].concat(this.selections.items);
48674 * Returns the first selected record.
48677 getSelected : function(){
48678 return this.selections.itemAt(0);
48683 * Clears all selections.
48685 clearSelections : function(fast){
48686 if(this.locked) return;
48688 var ds = this.grid.dataSource;
48689 var s = this.selections;
48690 s.each(function(r){
48691 this.deselectRow(ds.indexOfId(r.id));
48695 this.selections.clear();
48702 * Selects all rows.
48704 selectAll : function(){
48705 if(this.locked) return;
48706 this.selections.clear();
48707 for(var i = 0, len = this.grid.dataSource.getCount(); i < len; i++){
48708 this.selectRow(i, true);
48713 * Returns True if there is a selection.
48714 * @return {Boolean}
48716 hasSelection : function(){
48717 return this.selections.length > 0;
48721 * Returns True if the specified row is selected.
48722 * @param {Number/Record} record The record or index of the record to check
48723 * @return {Boolean}
48725 isSelected : function(index){
48726 var r = typeof index == "number" ? this.grid.dataSource.getAt(index) : index;
48727 return (r && this.selections.key(r.id) ? true : false);
48731 * Returns True if the specified record id is selected.
48732 * @param {String} id The id of record to check
48733 * @return {Boolean}
48735 isIdSelected : function(id){
48736 return (this.selections.key(id) ? true : false);
48740 handleMouseDown : function(e, t){
48741 var view = this.grid.getView(), rowIndex;
48742 if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
48745 if(e.shiftKey && this.last !== false){
48746 var last = this.last;
48747 this.selectRange(last, rowIndex, e.ctrlKey);
48748 this.last = last; // reset the last
48749 view.focusRow(rowIndex);
48751 var isSelected = this.isSelected(rowIndex);
48752 if(e.button !== 0 && isSelected){
48753 view.focusRow(rowIndex);
48754 }else if(e.ctrlKey && isSelected){
48755 this.deselectRow(rowIndex);
48756 }else if(!isSelected){
48757 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
48758 view.focusRow(rowIndex);
48761 this.fireEvent("afterselectionchange", this);
48764 handleDragableRowClick : function(grid, rowIndex, e)
48766 if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
48767 this.selectRow(rowIndex, false);
48768 grid.view.focusRow(rowIndex);
48769 this.fireEvent("afterselectionchange", this);
48774 * Selects multiple rows.
48775 * @param {Array} rows Array of the indexes of the row to select
48776 * @param {Boolean} keepExisting (optional) True to keep existing selections
48778 selectRows : function(rows, keepExisting){
48780 this.clearSelections();
48782 for(var i = 0, len = rows.length; i < len; i++){
48783 this.selectRow(rows[i], true);
48788 * Selects a range of rows. All rows in between startRow and endRow are also selected.
48789 * @param {Number} startRow The index of the first row in the range
48790 * @param {Number} endRow The index of the last row in the range
48791 * @param {Boolean} keepExisting (optional) True to retain existing selections
48793 selectRange : function(startRow, endRow, keepExisting){
48794 if(this.locked) return;
48796 this.clearSelections();
48798 if(startRow <= endRow){
48799 for(var i = startRow; i <= endRow; i++){
48800 this.selectRow(i, true);
48803 for(var i = startRow; i >= endRow; i--){
48804 this.selectRow(i, true);
48810 * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
48811 * @param {Number} startRow The index of the first row in the range
48812 * @param {Number} endRow The index of the last row in the range
48814 deselectRange : function(startRow, endRow, preventViewNotify){
48815 if(this.locked) return;
48816 for(var i = startRow; i <= endRow; i++){
48817 this.deselectRow(i, preventViewNotify);
48823 * @param {Number} row The index of the row to select
48824 * @param {Boolean} keepExisting (optional) True to keep existing selections
48826 selectRow : function(index, keepExisting, preventViewNotify){
48827 if(this.locked || (index < 0 || index >= this.grid.dataSource.getCount())) return;
48828 if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
48829 if(!keepExisting || this.singleSelect){
48830 this.clearSelections();
48832 var r = this.grid.dataSource.getAt(index);
48833 this.selections.add(r);
48834 this.last = this.lastActive = index;
48835 if(!preventViewNotify){
48836 this.grid.getView().onRowSelect(index);
48838 this.fireEvent("rowselect", this, index, r);
48839 this.fireEvent("selectionchange", this);
48845 * @param {Number} row The index of the row to deselect
48847 deselectRow : function(index, preventViewNotify){
48848 if(this.locked) return;
48849 if(this.last == index){
48852 if(this.lastActive == index){
48853 this.lastActive = false;
48855 var r = this.grid.dataSource.getAt(index);
48856 this.selections.remove(r);
48857 if(!preventViewNotify){
48858 this.grid.getView().onRowDeselect(index);
48860 this.fireEvent("rowdeselect", this, index);
48861 this.fireEvent("selectionchange", this);
48865 restoreLast : function(){
48867 this.last = this._last;
48872 acceptsNav : function(row, col, cm){
48873 return !cm.isHidden(col) && cm.isCellEditable(col, row);
48877 onEditorKey : function(field, e){
48878 var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
48883 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
48885 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
48887 }else if(k == e.ENTER && !e.ctrlKey){
48891 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
48893 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
48895 }else if(k == e.ESC){
48899 g.startEditing(newCell[0], newCell[1]);
48904 * Ext JS Library 1.1.1
48905 * Copyright(c) 2006-2007, Ext JS, LLC.
48907 * Originally Released Under LGPL - original licence link has changed is not relivant.
48910 * <script type="text/javascript">
48913 * @class Roo.grid.CellSelectionModel
48914 * @extends Roo.grid.AbstractSelectionModel
48915 * This class provides the basic implementation for cell selection in a grid.
48917 * @param {Object} config The object containing the configuration of this model.
48919 Roo.grid.CellSelectionModel = function(config){
48920 Roo.apply(this, config);
48922 this.selection = null;
48926 * @event beforerowselect
48927 * Fires before a cell is selected.
48928 * @param {SelectionModel} this
48929 * @param {Number} rowIndex The selected row index
48930 * @param {Number} colIndex The selected cell index
48932 "beforecellselect" : true,
48934 * @event cellselect
48935 * Fires when a cell is selected.
48936 * @param {SelectionModel} this
48937 * @param {Number} rowIndex The selected row index
48938 * @param {Number} colIndex The selected cell index
48940 "cellselect" : true,
48942 * @event selectionchange
48943 * Fires when the active selection changes.
48944 * @param {SelectionModel} this
48945 * @param {Object} selection null for no selection or an object (o) with two properties
48947 <li>o.record: the record object for the row the selection is in</li>
48948 <li>o.cell: An array of [rowIndex, columnIndex]</li>
48951 "selectionchange" : true
48953 Roo.grid.CellSelectionModel.superclass.constructor.call(this);
48956 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel, {
48959 initEvents : function(){
48960 this.grid.on("mousedown", this.handleMouseDown, this);
48961 this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
48962 var view = this.grid.view;
48963 view.on("refresh", this.onViewChange, this);
48964 view.on("rowupdated", this.onRowUpdated, this);
48965 view.on("beforerowremoved", this.clearSelections, this);
48966 view.on("beforerowsinserted", this.clearSelections, this);
48967 if(this.grid.isEditor){
48968 this.grid.on("beforeedit", this.beforeEdit, this);
48973 beforeEdit : function(e){
48974 this.select(e.row, e.column, false, true, e.record);
48978 onRowUpdated : function(v, index, r){
48979 if(this.selection && this.selection.record == r){
48980 v.onCellSelect(index, this.selection.cell[1]);
48985 onViewChange : function(){
48986 this.clearSelections(true);
48990 * Returns the currently selected cell,.
48991 * @return {Array} The selected cell (row, column) or null if none selected.
48993 getSelectedCell : function(){
48994 return this.selection ? this.selection.cell : null;
48998 * Clears all selections.
48999 * @param {Boolean} true to prevent the gridview from being notified about the change.
49001 clearSelections : function(preventNotify){
49002 var s = this.selection;
49004 if(preventNotify !== true){
49005 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
49007 this.selection = null;
49008 this.fireEvent("selectionchange", this, null);
49013 * Returns true if there is a selection.
49014 * @return {Boolean}
49016 hasSelection : function(){
49017 return this.selection ? true : false;
49021 handleMouseDown : function(e, t){
49022 var v = this.grid.getView();
49023 if(this.isLocked()){
49026 var row = v.findRowIndex(t);
49027 var cell = v.findCellIndex(t);
49028 if(row !== false && cell !== false){
49029 this.select(row, cell);
49035 * @param {Number} rowIndex
49036 * @param {Number} collIndex
49038 select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
49039 if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
49040 this.clearSelections();
49041 r = r || this.grid.dataSource.getAt(rowIndex);
49044 cell : [rowIndex, colIndex]
49046 if(!preventViewNotify){
49047 var v = this.grid.getView();
49048 v.onCellSelect(rowIndex, colIndex);
49049 if(preventFocus !== true){
49050 v.focusCell(rowIndex, colIndex);
49053 this.fireEvent("cellselect", this, rowIndex, colIndex);
49054 this.fireEvent("selectionchange", this, this.selection);
49059 isSelectable : function(rowIndex, colIndex, cm){
49060 return !cm.isHidden(colIndex);
49064 handleKeyDown : function(e){
49065 if(!e.isNavKeyPress()){
49068 var g = this.grid, s = this.selection;
49071 var cell = g.walkCells(0, 0, 1, this.isSelectable, this);
49073 this.select(cell[0], cell[1]);
49078 var walk = function(row, col, step){
49079 return g.walkCells(row, col, step, sm.isSelectable, sm);
49081 var k = e.getKey(), r = s.cell[0], c = s.cell[1];
49087 newCell = walk(r, c-1, -1);
49089 newCell = walk(r, c+1, 1);
49093 newCell = walk(r+1, c, 1);
49096 newCell = walk(r-1, c, -1);
49099 newCell = walk(r, c+1, 1);
49102 newCell = walk(r, c-1, -1);
49105 if(g.isEditor && !g.editing){
49106 g.startEditing(r, c);
49113 this.select(newCell[0], newCell[1]);
49118 acceptsNav : function(row, col, cm){
49119 return !cm.isHidden(col) && cm.isCellEditable(col, row);
49122 onEditorKey : function(field, e){
49123 var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
49126 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
49128 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
49131 }else if(k == e.ENTER && !e.ctrlKey){
49134 }else if(k == e.ESC){
49138 g.startEditing(newCell[0], newCell[1]);
49143 * Ext JS Library 1.1.1
49144 * Copyright(c) 2006-2007, Ext JS, LLC.
49146 * Originally Released Under LGPL - original licence link has changed is not relivant.
49149 * <script type="text/javascript">
49153 * @class Roo.grid.EditorGrid
49154 * @extends Roo.grid.Grid
49155 * Class for creating and editable grid.
49156 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
49157 * The container MUST have some type of size defined for the grid to fill. The container will be
49158 * automatically set to position relative if it isn't already.
49159 * @param {Object} dataSource The data model to bind to
49160 * @param {Object} colModel The column model with info about this grid's columns
49162 Roo.grid.EditorGrid = function(container, config){
49163 Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
49164 this.getGridEl().addClass("xedit-grid");
49166 if(!this.selModel){
49167 this.selModel = new Roo.grid.CellSelectionModel();
49170 this.activeEditor = null;
49174 * @event beforeedit
49175 * Fires before cell editing is triggered. The edit event object has the following properties <br />
49176 * <ul style="padding:5px;padding-left:16px;">
49177 * <li>grid - This grid</li>
49178 * <li>record - The record being edited</li>
49179 * <li>field - The field name being edited</li>
49180 * <li>value - The value for the field being edited.</li>
49181 * <li>row - The grid row index</li>
49182 * <li>column - The grid column index</li>
49183 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
49185 * @param {Object} e An edit event (see above for description)
49187 "beforeedit" : true,
49190 * Fires after a cell is edited. <br />
49191 * <ul style="padding:5px;padding-left:16px;">
49192 * <li>grid - This grid</li>
49193 * <li>record - The record being edited</li>
49194 * <li>field - The field name being edited</li>
49195 * <li>value - The value being set</li>
49196 * <li>originalValue - The original value for the field, before the edit.</li>
49197 * <li>row - The grid row index</li>
49198 * <li>column - The grid column index</li>
49200 * @param {Object} e An edit event (see above for description)
49202 "afteredit" : true,
49204 * @event validateedit
49205 * Fires after a cell is edited, but before the value is set in the record.
49206 * You can use this to modify the value being set in the field, Return false
49207 * to cancel the change. The edit event object has the following properties <br />
49208 * <ul style="padding:5px;padding-left:16px;">
49209 * <li>editor - This editor</li>
49210 * <li>grid - This grid</li>
49211 * <li>record - The record being edited</li>
49212 * <li>field - The field name being edited</li>
49213 * <li>value - The value being set</li>
49214 * <li>originalValue - The original value for the field, before the edit.</li>
49215 * <li>row - The grid row index</li>
49216 * <li>column - The grid column index</li>
49217 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
49219 * @param {Object} e An edit event (see above for description)
49221 "validateedit" : true
49223 this.on("bodyscroll", this.stopEditing, this);
49224 this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick, this);
49227 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
49229 * @cfg {Number} clicksToEdit
49230 * The number of clicks on a cell required to display the cell's editor (defaults to 2)
49237 trackMouseOver: false, // causes very odd FF errors
49239 onCellDblClick : function(g, row, col){
49240 this.startEditing(row, col);
49243 onEditComplete : function(ed, value, startValue){
49244 this.editing = false;
49245 this.activeEditor = null;
49246 ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
49248 var field = this.colModel.getDataIndex(ed.col);
49253 originalValue: startValue,
49260 if(String(value) !== String(startValue)){
49262 if(this.fireEvent("validateedit", e) !== false && !e.cancel){
49263 r.set(field, e.value);
49264 delete e.cancel; //?? why!!!
49265 this.fireEvent("afteredit", e);
49268 this.fireEvent("afteredit", e); // always fir it!
49270 this.view.focusCell(ed.row, ed.col);
49274 * Starts editing the specified for the specified row/column
49275 * @param {Number} rowIndex
49276 * @param {Number} colIndex
49278 startEditing : function(row, col){
49279 this.stopEditing();
49280 if(this.colModel.isCellEditable(col, row)){
49281 this.view.ensureVisible(row, col, true);
49282 var r = this.dataSource.getAt(row);
49283 var field = this.colModel.getDataIndex(col);
49288 value: r.data[field],
49293 if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
49294 this.editing = true;
49295 var ed = this.colModel.getCellEditor(col, row);
49301 ed.render(ed.parentEl || document.body);
49304 (function(){ // complex but required for focus issues in safari, ie and opera
49308 ed.on("complete", this.onEditComplete, this, {single: true});
49309 ed.on("specialkey", this.selModel.onEditorKey, this.selModel);
49310 this.activeEditor = ed;
49311 var v = r.data[field];
49312 ed.startEdit(this.view.getCell(row, col), v);
49313 }).defer(50, this);
49319 * Stops any active editing
49321 stopEditing : function(){
49322 if(this.activeEditor){
49323 this.activeEditor.completeEdit();
49325 this.activeEditor = null;
49329 * Ext JS Library 1.1.1
49330 * Copyright(c) 2006-2007, Ext JS, LLC.
49332 * Originally Released Under LGPL - original licence link has changed is not relivant.
49335 * <script type="text/javascript">
49338 // private - not really -- you end up using it !
49339 // This is a support class used internally by the Grid components
49342 * @class Roo.grid.GridEditor
49343 * @extends Roo.Editor
49344 * Class for creating and editable grid elements.
49345 * @param {Object} config any settings (must include field)
49347 Roo.grid.GridEditor = function(field, config){
49348 if (!config && field.field) {
49350 field = Roo.factory(config.field, Roo.form);
49352 Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
49353 field.monitorTab = false;
49356 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
49359 * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
49362 alignment: "tl-tl",
49365 cls: "x-small-editor x-grid-editor",
49370 * Ext JS Library 1.1.1
49371 * Copyright(c) 2006-2007, Ext JS, LLC.
49373 * Originally Released Under LGPL - original licence link has changed is not relivant.
49376 * <script type="text/javascript">
49381 Roo.grid.PropertyRecord = Roo.data.Record.create([
49382 {name:'name',type:'string'}, 'value'
49386 Roo.grid.PropertyStore = function(grid, source){
49388 this.store = new Roo.data.Store({
49389 recordType : Roo.grid.PropertyRecord
49391 this.store.on('update', this.onUpdate, this);
49393 this.setSource(source);
49395 Roo.grid.PropertyStore.superclass.constructor.call(this);
49400 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
49401 setSource : function(o){
49403 this.store.removeAll();
49406 if(this.isEditableValue(o[k])){
49407 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
49410 this.store.loadRecords({records: data}, {}, true);
49413 onUpdate : function(ds, record, type){
49414 if(type == Roo.data.Record.EDIT){
49415 var v = record.data['value'];
49416 var oldValue = record.modified['value'];
49417 if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
49418 this.source[record.id] = v;
49420 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
49427 getProperty : function(row){
49428 return this.store.getAt(row);
49431 isEditableValue: function(val){
49432 if(val && val instanceof Date){
49434 }else if(typeof val == 'object' || typeof val == 'function'){
49440 setValue : function(prop, value){
49441 this.source[prop] = value;
49442 this.store.getById(prop).set('value', value);
49445 getSource : function(){
49446 return this.source;
49450 Roo.grid.PropertyColumnModel = function(grid, store){
49453 g.PropertyColumnModel.superclass.constructor.call(this, [
49454 {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
49455 {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
49457 this.store = store;
49458 this.bselect = Roo.DomHelper.append(document.body, {
49459 tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
49460 {tag: 'option', value: 'true', html: 'true'},
49461 {tag: 'option', value: 'false', html: 'false'}
49464 Roo.id(this.bselect);
49467 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
49468 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
49469 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
49470 'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
49471 'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
49473 this.renderCellDelegate = this.renderCell.createDelegate(this);
49474 this.renderPropDelegate = this.renderProp.createDelegate(this);
49477 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
49481 valueText : 'Value',
49483 dateFormat : 'm/j/Y',
49486 renderDate : function(dateVal){
49487 return dateVal.dateFormat(this.dateFormat);
49490 renderBool : function(bVal){
49491 return bVal ? 'true' : 'false';
49494 isCellEditable : function(colIndex, rowIndex){
49495 return colIndex == 1;
49498 getRenderer : function(col){
49500 this.renderCellDelegate : this.renderPropDelegate;
49503 renderProp : function(v){
49504 return this.getPropertyName(v);
49507 renderCell : function(val){
49509 if(val instanceof Date){
49510 rv = this.renderDate(val);
49511 }else if(typeof val == 'boolean'){
49512 rv = this.renderBool(val);
49514 return Roo.util.Format.htmlEncode(rv);
49517 getPropertyName : function(name){
49518 var pn = this.grid.propertyNames;
49519 return pn && pn[name] ? pn[name] : name;
49522 getCellEditor : function(colIndex, rowIndex){
49523 var p = this.store.getProperty(rowIndex);
49524 var n = p.data['name'], val = p.data['value'];
49526 if(typeof(this.grid.customEditors[n]) == 'string'){
49527 return this.editors[this.grid.customEditors[n]];
49529 if(typeof(this.grid.customEditors[n]) != 'undefined'){
49530 return this.grid.customEditors[n];
49532 if(val instanceof Date){
49533 return this.editors['date'];
49534 }else if(typeof val == 'number'){
49535 return this.editors['number'];
49536 }else if(typeof val == 'boolean'){
49537 return this.editors['boolean'];
49539 return this.editors['string'];
49545 * @class Roo.grid.PropertyGrid
49546 * @extends Roo.grid.EditorGrid
49547 * This class represents the interface of a component based property grid control.
49548 * <br><br>Usage:<pre><code>
49549 var grid = new Roo.grid.PropertyGrid("my-container-id", {
49557 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
49558 * The container MUST have some type of size defined for the grid to fill. The container will be
49559 * automatically set to position relative if it isn't already.
49560 * @param {Object} config A config object that sets properties on this grid.
49562 Roo.grid.PropertyGrid = function(container, config){
49563 config = config || {};
49564 var store = new Roo.grid.PropertyStore(this);
49565 this.store = store;
49566 var cm = new Roo.grid.PropertyColumnModel(this, store);
49567 store.store.sort('name', 'ASC');
49568 Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
49571 enableColLock:false,
49572 enableColumnMove:false,
49574 trackMouseOver: false,
49577 this.getGridEl().addClass('x-props-grid');
49578 this.lastEditRow = null;
49579 this.on('columnresize', this.onColumnResize, this);
49582 * @event beforepropertychange
49583 * Fires before a property changes (return false to stop?)
49584 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
49585 * @param {String} id Record Id
49586 * @param {String} newval New Value
49587 * @param {String} oldval Old Value
49589 "beforepropertychange": true,
49591 * @event propertychange
49592 * Fires after a property changes
49593 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
49594 * @param {String} id Record Id
49595 * @param {String} newval New Value
49596 * @param {String} oldval Old Value
49598 "propertychange": true
49600 this.customEditors = this.customEditors || {};
49602 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
49605 * @cfg {Object} customEditors map of colnames=> custom editors.
49606 * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
49607 * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
49608 * false disables editing of the field.
49612 * @cfg {Object} propertyNames map of property Names to their displayed value
49615 render : function(){
49616 Roo.grid.PropertyGrid.superclass.render.call(this);
49617 this.autoSize.defer(100, this);
49620 autoSize : function(){
49621 Roo.grid.PropertyGrid.superclass.autoSize.call(this);
49623 this.view.fitColumns();
49627 onColumnResize : function(){
49628 this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
49632 * Sets the data for the Grid
49633 * accepts a Key => Value object of all the elements avaiable.
49634 * @param {Object} data to appear in grid.
49636 setSource : function(source){
49637 this.store.setSource(source);
49641 * Gets all the data from the grid.
49642 * @return {Object} data data stored in grid
49644 getSource : function(){
49645 return this.store.getSource();
49649 * Ext JS Library 1.1.1
49650 * Copyright(c) 2006-2007, Ext JS, LLC.
49652 * Originally Released Under LGPL - original licence link has changed is not relivant.
49655 * <script type="text/javascript">
49659 * @class Roo.LoadMask
49660 * A simple utility class for generically masking elements while loading data. If the element being masked has
49661 * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
49662 * process and the mask element will be cached for reuse. For all other elements, this mask will replace the
49663 * element's UpdateManager load indicator and will be destroyed after the initial load.
49665 * Create a new LoadMask
49666 * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
49667 * @param {Object} config The config object
49669 Roo.LoadMask = function(el, config){
49670 this.el = Roo.get(el);
49671 Roo.apply(this, config);
49673 this.store.on('beforeload', this.onBeforeLoad, this);
49674 this.store.on('load', this.onLoad, this);
49675 this.store.on('loadexception', this.onLoad, this);
49676 this.removeMask = false;
49678 var um = this.el.getUpdateManager();
49679 um.showLoadIndicator = false; // disable the default indicator
49680 um.on('beforeupdate', this.onBeforeLoad, this);
49681 um.on('update', this.onLoad, this);
49682 um.on('failure', this.onLoad, this);
49683 this.removeMask = true;
49687 Roo.LoadMask.prototype = {
49689 * @cfg {Boolean} removeMask
49690 * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
49691 * False to persist the mask element reference for multiple uses (e.g., for paged data widgets). Defaults to false.
49694 * @cfg {String} msg
49695 * The text to display in a centered loading message box (defaults to 'Loading...')
49697 msg : 'Loading...',
49699 * @cfg {String} msgCls
49700 * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
49702 msgCls : 'x-mask-loading',
49705 * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
49711 * Disables the mask to prevent it from being displayed
49713 disable : function(){
49714 this.disabled = true;
49718 * Enables the mask so that it can be displayed
49720 enable : function(){
49721 this.disabled = false;
49725 onLoad : function(){
49726 this.el.unmask(this.removeMask);
49730 onBeforeLoad : function(){
49731 if(!this.disabled){
49732 this.el.mask(this.msg, this.msgCls);
49737 destroy : function(){
49739 this.store.un('beforeload', this.onBeforeLoad, this);
49740 this.store.un('load', this.onLoad, this);
49741 this.store.un('loadexception', this.onLoad, this);
49743 var um = this.el.getUpdateManager();
49744 um.un('beforeupdate', this.onBeforeLoad, this);
49745 um.un('update', this.onLoad, this);
49746 um.un('failure', this.onLoad, this);
49751 * Ext JS Library 1.1.1
49752 * Copyright(c) 2006-2007, Ext JS, LLC.
49754 * Originally Released Under LGPL - original licence link has changed is not relivant.
49757 * <script type="text/javascript">
49759 Roo.XTemplate = function(){
49760 Roo.XTemplate.superclass.constructor.apply(this, arguments);
49763 s = ['<tpl>', s, '</tpl>'].join('');
49765 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/;
49767 var nameRe = /^<tpl\b[^>]*?for="(.*?)"/;
49768 var ifRe = /^<tpl\b[^>]*?if="(.*?)"/;
49769 var execRe = /^<tpl\b[^>]*?exec="(.*?)"/;
49773 while(m = s.match(re)){
49774 var m2 = m[0].match(nameRe);
49775 var m3 = m[0].match(ifRe);
49776 var m4 = m[0].match(execRe);
49777 var exp = null, fn = null, exec = null;
49778 var name = m2 && m2[1] ? m2[1] : '';
49780 exp = m3 && m3[1] ? m3[1] : null;
49782 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
49786 exp = m4 && m4[1] ? m4[1] : null;
49788 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
49793 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
49794 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
49795 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
49805 s = s.replace(m[0], '{xtpl'+ id + '}');
49808 for(var i = tpls.length-1; i >= 0; --i){
49809 this.compileTpl(tpls[i]);
49811 this.master = tpls[tpls.length-1];
49814 Roo.extend(Roo.XTemplate, Roo.Template, {
49816 re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
49818 applySubTemplate : function(id, values, parent){
49819 var t = this.tpls[id];
49820 if(t.test && !t.test.call(this, values, parent)){
49823 if(t.exec && t.exec.call(this, values, parent)){
49826 var vs = t.target ? t.target.call(this, values, parent) : values;
49827 parent = t.target ? values : parent;
49828 if(t.target && vs instanceof Array){
49830 for(var i = 0, len = vs.length; i < len; i++){
49831 buf[buf.length] = t.compiled.call(this, vs[i], parent);
49833 return buf.join('');
49835 return t.compiled.call(this, vs, parent);
49838 compileTpl : function(tpl){
49839 var fm = Roo.util.Format;
49840 var useF = this.disableFormats !== true;
49841 var sep = Roo.isGecko ? "+" : ",";
49842 var fn = function(m, name, format, args){
49843 if(name.substr(0, 4) == 'xtpl'){
49844 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
49847 if(name.indexOf('.') != -1){
49850 v = "values['" + name + "']";
49852 if(format && useF){
49853 args = args ? ',' + args : "";
49854 if(format.substr(0, 5) != "this."){
49855 format = "fm." + format + '(';
49857 format = 'this.call("'+ format.substr(5) + '", ';
49861 args= ''; format = "("+v+" === undefined ? '' : ";
49863 return "'"+ sep + format + v + args + ")"+sep+"'";
49866 // branched to use + in gecko and [].join() in others
49868 body = "tpl.compiled = function(values, parent){ return '" +
49869 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
49872 body = ["tpl.compiled = function(values, parent){ return ['"];
49873 body.push(tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
49874 body.push("'].join('');};");
49875 body = body.join('');
49877 /** eval:var:zzzzzzz */
49882 applyTemplate : function(values){
49883 return this.master.compiled.call(this, values, {});
49887 apply : function(){
49888 return this.applyTemplate.apply(this, arguments);
49891 compile : function(){return this;}
49894 Roo.XTemplate.from = function(el){
49895 el = Roo.getDom(el);
49896 return new Roo.XTemplate(el.value || el.innerHTML);
49898 * Original code for Roojs - LGPL
49899 * <script type="text/javascript">
49903 * @class Roo.XComponent
49904 * A delayed Element creator...
49906 * Mypart.xyx = new Roo.XComponent({
49908 parent : 'Mypart.xyz', // empty == document.element.!!
49912 disabled : function() {}
49914 tree : function() { // return an tree of xtype declared components
49918 xtype : 'NestedLayoutPanel',
49923 * @extends Roo.util.Observable
49925 * @param cfg {Object} configuration of component
49928 Roo.XComponent = function(cfg) {
49929 Roo.apply(this, cfg);
49933 * Fires when this the componnt is built
49934 * @param {Roo.XComponent} c the component
49938 * @event buildcomplete
49939 * Fires on the top level element when all elements have been built
49940 * @param {Roo.XComponent} c the top level component.
49942 'buildcomplete' : true,
49946 Roo.XComponent.register(this);
49947 this.modules = false;
49948 this.el = false; // where the layout goes..
49952 Roo.extend(Roo.XComponent, Roo.util.Observable, {
49955 * The created element (with Roo.factory())
49956 * @type {Roo.Layout}
49962 * for BC - use el in new code
49963 * @type {Roo.Layout}
49969 * for BC - use el in new code
49970 * @type {Roo.Layout}
49975 * @cfg {Function|boolean} disabled
49976 * If this module is disabled by some rule, return true from the funtion
49981 * @cfg {String} parent
49982 * Name of parent element which it get xtype added to..
49987 * @cfg {String} order
49988 * Used to set the order in which elements are created (usefull for multiple tabs)
49993 * @cfg {String} name
49994 * String to display while loading.
49998 * @cfg {Array} items
49999 * A single item array - the first element is the root of the tree..
50000 * It's done this way to stay compatible with the Xtype system...
50008 Roo.apply(Roo.XComponent, {
50011 * @property buildCompleted
50012 * True when the builder has completed building the interface.
50015 buildCompleted : false,
50018 * @property topModule
50019 * the upper most module - uses document.element as it's constructor.
50026 * @property modules
50027 * array of modules to be created by registration system.
50028 * @type Roo.XComponent
50035 * Register components to be built later.
50037 * This solves the following issues
50038 * - Building is not done on page load, but after an authentication process has occured.
50039 * - Interface elements are registered on page load
50040 * - Parent Interface elements may not be loaded before child, so this handles that..
50047 module : 'Pman.Tab.projectMgr',
50049 parent : 'Pman.layout',
50050 disabled : false, // or use a function..
50053 * * @param {Object} details about module
50055 register : function(obj) {
50056 this.modules.push(obj);
50060 * convert a string to an object..
50064 toObject : function(str)
50066 if (!str || typeof(str) == 'object') {
50069 var ar = str.split('.');
50073 eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
50075 throw "Module not found : " + str;
50077 Roo.each(ar, function(e) {
50078 if (typeof(o[e]) == 'undefined') {
50079 throw "Module not found : " + str;
50089 * move modules into their correct place in the tree..
50092 preBuild : function ()
50095 Roo.each(this.modules , function (obj)
50097 obj.parent = this.toObject(obj.parent);
50100 this.topModule = obj;
50104 if (!obj.parent.modules) {
50105 obj.parent.modules = new Roo.util.MixedCollection(false,
50106 function(o) { return o.order + '' }
50110 obj.parent.modules.add(obj);
50115 * make a list of modules to build.
50116 * @return {Array} list of modules.
50119 buildOrder : function()
50122 var cmp = function(a,b) {
50123 return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
50126 if (!this.topModule || !this.topModule.modules) {
50127 throw "No top level modules to build";
50130 // make a flat list in order of modules to build.
50131 var mods = [ this.topModule ];
50134 // add modules to their parents..
50135 var addMod = function(m) {
50136 // console.log(m.modKey);
50140 m.modules.keySort('ASC', cmp );
50141 m.modules.each(addMod);
50143 // not sure if this is used any more..
50145 m.finalize.name = m.name + " (clean up) ";
50146 mods.push(m.finalize);
50150 this.topModule.modules.keySort('ASC', cmp );
50151 this.topModule.modules.each(addMod);
50156 * Build the registered modules.
50157 * @param {Object} parent element.
50158 * @param {Function} optional method to call after module has been added.
50166 var mods = this.buildOrder();
50168 //this.allmods = mods;
50169 //console.log(mods);
50171 if (!mods.length) { // should not happen
50172 throw "NO modules!!!";
50177 // flash it up as modal - so we store the mask!?
50178 Roo.MessageBox.show({ title: 'loading' });
50179 Roo.MessageBox.show({
50180 title: "Please wait...",
50181 msg: "Building Interface...",
50188 var total = mods.length;
50191 var progressRun = function() {
50192 if (!mods.length) {
50193 console.log('hide?');
50194 Roo.MessageBox.hide();
50195 _this.topModule.fireEvent('buildcomplete', _this.topModule);
50199 var m = mods.shift();
50201 if (typeof(m) == 'function') { // not sure if this is supported any more..
50203 return progressRun.defer(10, _this);
50206 Roo.MessageBox.updateProgress(
50207 (total - mods.length)/total, "Building Interface " + (total - mods.length) +
50209 (m.name ? (' - ' + m.name) : '')
50214 var disabled = (typeof(m.disabled) == 'function') ?
50215 m.disabled.call(m.module.disabled) : m.disabled;
50219 return progressRun(); // we do not update the display!
50223 // it's a top level one..
50224 var layoutbase = new Ext.BorderLayout(document.body, {
50230 tabPosition: 'top',
50231 //resizeTabs: true,
50232 alwaysShowTabs: true,
50236 var tree = m.tree();
50237 tree.region = 'center';
50238 m.el = layoutbase.addxtype(tree);
50240 m.layout = m.panel.layout;
50241 return progressRun.defer(10, _this);
50244 var tree = m.tree();
50245 tree.region = tree.region || m.region;
50246 m.el = m.parent.el.addxtype(tree);
50247 m.fireEvent('built', m);
50249 m.layout = m.panel.layout;
50250 progressRun.defer(10, _this);
50253 progressRun.defer(1, _this);
50263 //<script type="text/javascript">
50268 * @extends Roo.LayoutDialog
50269 * A generic Login Dialog..... - only one needed in theory!?!?
50271 * Fires XComponent builder on success...
50274 * username,password, lang = for login actions.
50275 * check = 1 for periodic checking that sesion is valid.
50276 * passwordRequest = email request password
50277 * logout = 1 = to logout
50279 * Affects: (this id="????" elements)
50280 * loading (removed) (used to indicate application is loading)
50281 * loading-mask (hides) (used to hide application when it's building loading)
50287 * Myapp.login = Roo.Login({
50303 Roo.Login = function(cfg)
50306 'refreshed' : true,
50309 Roo.apply(this,cfg);
50311 Roo.onReady(function() {
50317 Roo.Login.superclass.constructor.call(this, this);
50318 //this.addxtype(this.items[0]);
50324 Roo.extend(Roo.Login, Roo.LayoutDialog, {
50327 * @cfg {String} method
50328 * Method used to query for login details.
50333 * @cfg {String} url
50334 * URL to query login data. - eg. baseURL + '/Login.php'
50340 * The user data - if user.id < 0 then login will be bypassed. (used for inital setup situation.
50345 * @property checkFails
50346 * Number of times we have attempted to get authentication check, and failed.
50351 * @property intervalID
50352 * The window interval that does the constant login checking.
50358 onLoad : function() // called on page load...
50362 if (Roo.get('loading')) { // clear any loading indicator..
50363 Roo.get('loading').remove();
50366 //this.switchLang('en'); // set the language to english..
50369 success: function(response, opts) { // check successfull...
50371 var res = this.processResponse(response);
50372 this.checkFails =0;
50373 if (!res.success) { // error!
50374 this.checkFails = 5;
50375 //console.log('call failure');
50376 return this.failure(response,opts);
50379 if (!res.data.id) { // id=0 == login failure.
50380 return this.show();
50384 //console.log(success);
50385 this.fillAuth(res.data);
50386 this.checkFails =0;
50387 Roo.XComponent.build();
50389 failure : this.show
50395 check: function(cfg) // called every so often to refresh cookie etc..
50397 if (cfg.again) { // could be undefined..
50400 this.checkFails = 0;
50403 if (this.sending) {
50404 if ( this.checkFails > 4) {
50405 Roo.MessageBox.alert("Error",
50406 "Error getting authentication status. - try reloading, or wait a while", function() {
50407 _this.sending = false;
50412 _this.check.defer(10000, _this, [ cfg ]); // check in 10 secs.
50415 this.sending = true;
50422 method: this.method,
50423 success: cfg.success || this.success,
50424 failure : cfg.failure || this.failure,
50434 window.onbeforeunload = function() { }; // false does not work for IE..
50444 failure : function() {
50445 Roo.MessageBox.alert("Error", "Error logging out. - continuing anyway.", function() {
50446 document.location = document.location.toString() + '?ts=' + Math.random();
50450 success : function() {
50451 _this.user = false;
50452 this.checkFails =0;
50454 document.location = document.location.toString() + '?ts=' + Math.random();
50461 processResponse : function (response)
50465 res = Roo.decode(response.responseText);
50467 if (typeof(res) != 'object') {
50468 res = { success : false, errorMsg : res, errors : true };
50470 if (typeof(res.success) == 'undefined') {
50471 res.success = false;
50475 res = { success : false, errorMsg : response.responseText, errors : true };
50480 success : function(response, opts) // check successfull...
50482 this.sending = false;
50483 var res = this.processResponse(response);
50484 if (!res.success) {
50485 return this.failure(response, opts);
50487 if (!res.data || !res.data.id) {
50488 return this.failure(response,opts);
50490 //console.log(res);
50491 this.fillAuth(res.data);
50493 this.checkFails =0;
50498 failure : function (response, opts) // called if login 'check' fails.. (causes re-check)
50500 this.authUser = -1;
50501 this.sending = false;
50502 var res = this.processResponse(response);
50503 //console.log(res);
50504 if ( this.checkFails > 2) {
50506 Roo.MessageBox.alert("Error", res.errorMsg ? res.errorMsg :
50507 "Error getting authentication status. - try reloading");
50510 opts.callCfg.again = true;
50511 this.check.defer(1000, this, [ opts.callCfg ]);
50517 fillAuth: function(au) {
50518 this.startAuthCheck();
50519 this.authUserId = au.id;
50520 this.authUser = au;
50521 this.lastChecked = new Date();
50522 this.fireEvent('refreshed', au);
50523 //Pman.Tab.FaxQueue.newMaxId(au.faxMax);
50524 //Pman.Tab.FaxTab.setTitle(au.faxNumPending);
50525 au.lang = au.lang || 'en';
50526 //this.switchLang(Roo.state.Manager.get('Pman.Login.lang', 'en'));
50527 Roo.state.Manager.set( this.realm + 'lang' , au.lang);
50528 this.switchLang(au.lang );
50531 // open system... - -on setyp..
50532 if (this.authUserId < 0) {
50533 Roo.MessageBox.alert("Warning",
50534 "This is an open system - please set up a admin user with a password.");
50537 //Pman.onload(); // which should do nothing if it's a re-auth result...
50542 startAuthCheck : function() // starter for timeout checking..
50544 if (this.intervalID) { // timer already in place...
50548 this.intervalID = window.setInterval(function() {
50549 _this.check(false);
50550 }, 120000); // every 120 secs = 2mins..
50556 switchLang : function (lang)
50558 _T = typeof(_T) == 'undefined' ? false : _T;
50559 if (!_T || !lang.length) {
50563 if (!_T && lang != 'en') {
50564 Roo.MessageBox.alert("Sorry", "Language not available yet (" + lang +')');
50568 if (typeof(_T.en) == 'undefined') {
50570 Roo.apply(_T.en, _T);
50573 if (typeof(_T[lang]) == 'undefined') {
50574 Roo.MessageBox.alert("Sorry", "Language not available yet (" + lang +')');
50579 Roo.apply(_T, _T[lang]);
50580 // just need to set the text values for everything...
50582 /* this will not work ...
50586 function formLabel(name, val) {
50587 _this.form.findField(name).fieldEl.child('label').dom.innerHTML = val;
50590 formLabel('password', "Password"+':');
50591 formLabel('username', "Email Address"+':');
50592 formLabel('lang', "Language"+':');
50593 this.dialog.setTitle("Login");
50594 this.dialog.buttons[0].setText("Forgot Password");
50595 this.dialog.buttons[1].setText("Login");
50614 collapsible: false,
50616 center: { // needed??
50619 // tabPosition: 'top',
50622 alwaysShowTabs: false
50626 show : function(dlg)
50628 //console.log(this);
50629 this.form = this.layout.getRegion('center').activePanel.form;
50630 this.form.dialog = dlg;
50631 this.buttons[0].form = this.form;
50632 this.buttons[0].dialog = dlg
50633 this.buttons[1].form = this.form;
50634 this.buttons[1].dialog = dlg;
50636 //this.resizeToLogo.defer(1000,this);
50637 // this is all related to resizing for logos..
50638 //var sz = Roo.get(Pman.Login.form.el.query('img')[0]).getSize();
50640 // this.resizeToLogo.defer(1000,this);
50643 //var w = Ext.lib.Dom.getViewWidth() - 100;
50644 //var h = Ext.lib.Dom.getViewHeight() - 100;
50645 //this.resizeTo(Math.max(350, Math.min(sz.width + 30, w)),Math.min(sz.height+200, h));
50647 if (this.disabled) {
50652 if (this.user.id < 0) { // used for inital setup situations.
50656 if (this.intervalID) {
50657 // remove the timer
50658 window.clearInterval(this.intervalID);
50659 this.intervalID = false;
50663 if (Roo.get('loading')) {
50664 Roo.get('loading').remove();
50666 if (Roo.get('loading-mask')) {
50667 Roo.get('loading-mask').hide();
50670 //incomming._node = tnode;
50672 //this.dialog.modal = !modal;
50673 //this.dialog.show();
50677 this.form.setValues({
50678 'username' : Roo.state.Manager.get(this.realm + '.username', ''),
50679 'lang' : Roo.state.Manager.get(this.realm + '.lang', 'en')
50682 this.switchLang(Roo.state.Manager.get(this.realm + '.lang', 'en'));
50683 if (this.form.findField('username').getValue().length > 0 ){
50684 this.form.findField('password').focus();
50686 this.form.findField('username').focus();
50694 xtype : 'ContentPanel',
50706 style : 'margin: 10px;',
50709 actionfailed : function(f, act) {
50710 // form can return { errors: .... }
50712 //act.result.errors // invalid form element list...
50713 //act.result.errorMsg// invalid form element list...
50715 this.dialog.el.unmask();
50716 Roo.MessageBox.alert("Error", act.result.errorMsg ? act.result.errorMsg :
50717 "Login failed - communication error - try again.");
50720 actioncomplete: function(re, act) {
50722 Roo.state.Manager.set(
50723 this.dialog.realm + '.username',
50724 this.findField('username').getValue()
50726 Roo.state.Manager.set(
50727 this.dialog.realm + '.lang',
50728 this.findField('lang').getValue()
50731 this.dialog.fillAuth(act.result.data);
50733 this.dialog.hide();
50735 if (Roo.get('loading-mask')) {
50736 Roo.get('loading-mask').show();
50738 Roo.XComponent.build();
50746 xtype : 'TextField',
50748 fieldLabel: "Email Address",
50751 autoCreate : {tag: "input", type: "text", size: "20"}
50754 xtype : 'TextField',
50756 fieldLabel: "Password",
50757 inputType: 'password',
50760 autoCreate : {tag: "input", type: "text", size: "20"},
50762 specialkey : function(e,ev) {
50763 if (ev.keyCode == 13) {
50764 this.form.dialog.el.mask("Logging in");
50765 this.form.doAction('submit', {
50766 url: this.form.dialog.url,
50767 method: this.form.dialog.method,
50774 xtype : 'ComboBox',
50776 fieldLabel: "Language",
50779 xtype : 'SimpleStore',
50780 fields: ['lang', 'ldisp'],
50782 [ 'en', 'English' ],
50783 [ 'zh_HK' , '\u7E41\u4E2D' ],
50784 [ 'zh_CN', '\u7C21\u4E2D' ]
50788 valueField : 'lang',
50789 hiddenName: 'lang',
50791 displayField:'ldisp',
50795 triggerAction: 'all',
50796 emptyText:'Select a Language...',
50797 selectOnFocus:true,
50799 select : function(cb, rec, ix) {
50800 this.form.switchLang(rec.data.lang);
50816 text : "Forgot Password",
50818 click : function() {
50819 //console.log(this);
50820 var n = this.form.findField('username').getValue();
50822 Roo.MessageBox.alert("Error", "Fill in your email address");
50826 url: this.dialog.url,
50830 method: this.dialog.method,
50831 success: function(response, opts) { // check successfull...
50833 var res = this.dialog.processResponse(response);
50834 if (!res.success) { // error!
50835 Roo.MessageBox.alert("Error" ,
50836 res.errorMsg ? res.errorMsg : "Problem Requesting Password Reset");
50839 Roo.MessageBox.alert("Notice" ,
50840 "Please check you email for the Password Reset message");
50842 failure : function() {
50843 Roo.MessageBox.alert("Error" , "Problem Requesting Password Reset");
50856 click : function () {
50858 this.dialog.el.mask("Logging in");
50859 this.form.doAction('submit', {
50860 url: this.dialog.url,
50861 method: this.dialog.method