Roo/tree/TreeLoader.js
[roojs1] / roojs-core-debug.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11  
12
13
14
15
16 // for old browsers
17 window["undefined"] = window["undefined"];
18
19 /**
20  * @class Roo
21  * Roo core utilities and functions.
22  * @singleton
23  */
24 var Roo = {}; 
25 /**
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
31  * @member Roo apply
32  */
33
34  
35 Roo.apply = function(o, c, defaults){
36     if(defaults){
37         // no "this" reference for friendly out of scope calls
38         Roo.apply(o, defaults);
39     }
40     if(o && c && typeof c == 'object'){
41         for(var p in c){
42             o[p] = c[p];
43         }
44     }
45     return o;
46 };
47
48
49 (function(){
50     var idSeed = 0;
51     var ua = navigator.userAgent.toLowerCase();
52
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;
64
65     // remove css image flicker
66         if(isIE && !isIE7){
67         try{
68             document.execCommand("BackgroundImageCache", false, true);
69         }catch(e){}
70     }
71
72     Roo.apply(Roo, {
73         /**
74          * True if the browser is in strict mode
75          * @type Boolean
76          */
77         isStrict : isStrict,
78         /**
79          * True if the page is running over SSL
80          * @type Boolean
81          */
82         isSecure : isSecure,
83         /**
84          * True when the document is fully initialized and ready for action
85          * @type Boolean
86          */
87         isReady : false,
88         /**
89          * Turn on debugging output (currently only the factory uses this)
90          * @type Boolean
91          */
92         
93         debug: false,
94
95         /**
96          * True to automatically uncache orphaned Roo.Elements periodically (defaults to true)
97          * @type Boolean
98          */
99         enableGarbageCollector : true,
100
101         /**
102          * True to automatically purge event listeners after uncaching an element (defaults to false).
103          * Note: this only happens if enableGarbageCollector is true.
104          * @type Boolean
105          */
106         enableListenerCollection:false,
107
108         /**
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).
111          * @type String
112          */
113         SSL_SECURE_URL : "javascript:false",
114
115         /**
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).
118          * @type String
119          */
120         BLANK_IMAGE_URL : "http:/"+"/localhost/s.gif",
121
122         emptyFn : function(){},
123
124         /**
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
129          */
130         applyIf : function(o, c){
131             if(o && c){
132                 for(var p in c){
133                     if(typeof o[p] == "undefined"){ o[p] = c[p]; }
134                 }
135             }
136             return o;
137         },
138
139         /**
140          * Applies event listeners to elements by selectors when the document is ready.
141          * The event name is specified with an @ suffix.
142 <pre><code>
143 Roo.addBehaviors({
144    // add a listener for click on all anchors in element with id foo
145    '#foo a@click' : function(e, t){
146        // do something
147    },
148
149    // add the same listener to multiple selectors (separated by comma BEFORE the @)
150    '#foo a, #bar span.some-class@mouseover' : function(){
151        // do something
152    }
153 });
154 </code></pre>
155          * @param {Object} obj The list of behaviors to apply
156          */
157         addBehaviors : function(o){
158             if(!Roo.isReady){
159                 Roo.onReady(function(){
160                     Roo.addBehaviors(o);
161                 });
162                 return;
163             }
164             var cache = {}; // simple cache for applying multiple behaviors to same selector does query multiple times
165             for(var b in o){
166                 var parts = b.split('@');
167                 if(parts[1]){ // for Object prototype breakers
168                     var s = parts[0];
169                     if(!cache[s]){
170                         cache[s] = Roo.select(s);
171                     }
172                     cache[s].on(parts[1], o[b]);
173                 }
174             }
175             cache = null;
176         },
177
178         /**
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.
183          */
184         id : function(el, prefix){
185             prefix = prefix || "roo-gen";
186             el = Roo.getDom(el);
187             var id = prefix + (++idSeed);
188             return el ? (el.id ? el.id : (el.id = id)) : id;
189         },
190          
191        
192         /**
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
199          * @method extend
200          */
201         extend : function(){
202             // inline overrides
203             var io = function(o){
204                 for(var m in o){
205                     this[m] = o[m];
206                 }
207             };
208             return function(sb, sp, overrides){
209                 if(typeof sp == 'object'){ // eg. prototype, rather than function constructor..
210                     overrides = sp;
211                     sp = sb;
212                     sb = function(){sp.apply(this, arguments);};
213                 }
214                 var F = function(){}, sbp, spp = sp.prototype;
215                 F.prototype = spp;
216                 sbp = sb.prototype = new F();
217                 sbp.constructor=sb;
218                 sb.superclass=spp;
219                 
220                 if(spp.constructor == Object.prototype.constructor){
221                     spp.constructor=sp;
222                    
223                 }
224                 
225                 sb.override = function(o){
226                     Roo.override(sb, o);
227                 };
228                 sbp.override = io;
229                 Roo.override(sb, overrides);
230                 return sb;
231             };
232         }(),
233
234         /**
235          * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name.
236          * Usage:<pre><code>
237 Roo.override(MyClass, {
238     newMethod1: function(){
239         // etc.
240     },
241     newMethod2: function(foo){
242         // etc.
243     }
244 });
245  </code></pre>
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.
249          * @method override
250          */
251         override : function(origclass, overrides){
252             if(overrides){
253                 var p = origclass.prototype;
254                 for(var method in overrides){
255                     p[method] = overrides[method];
256                 }
257             }
258         },
259         /**
260          * Creates namespaces to be used for scoping variables and classes so that they are not global.  Usage:
261          * <pre><code>
262 Roo.namespace('Company', 'Company.data');
263 Company.Widget = function() { ... }
264 Company.data.CustomStore = function(config) { ... }
265 </code></pre>
266          * @param {String} namespace1
267          * @param {String} namespace2
268          * @param {String} etc
269          * @method namespace
270          */
271         namespace : function(){
272             var a=arguments, o=null, i, j, d, rt;
273             for (i=0; i<a.length; ++i) {
274                 d=a[i].split(".");
275                 rt = d[0];
276                 /** eval:var:o */
277                 eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
278                 for (j=1; j<d.length; ++j) {
279                     o[d[j]]=o[d[j]] || {};
280                     o=o[d[j]];
281                 }
282             }
283         },
284         /**
285          * Creates namespaces to be used for scoping variables and classes so that they are not global.  Usage:
286          * <pre><code>
287 Roo.factory({ xns: Roo.data, xtype : 'Store', .....});
288 Roo.factory(conf, Roo.data);
289 </code></pre>
290          * @param {String} classname
291          * @param {String} namespace (optional)
292          * @method factory
293          */
294          
295         factory : function(c, ns)
296         {
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...
299                 return c;
300             }
301             ns = c.xns ? c.xns : ns; // if c.xns is set, then use that..
302             if (c.constructor == ns[c.xtype]) {// already created...
303                 return c;
304             }
305             if (ns[c.xtype]) {
306                 if (Roo.debug) Roo.log("Roo.Factory(" + c.xtype + ")");
307                 var ret = new ns[c.xtype](c);
308                 ret.xns = false;
309                 return ret;
310             }
311             c.xns = false; // prevent recursion..
312             return c;
313         },
314          /**
315          * Logs to console if it can.
316          *
317          * @param {String|Object} string
318          * @method log
319          */
320         log : function(s)
321         {
322             if ((typeof(console) == 'undefined') || (typeof(console.log) == 'undefined')) {
323                 return; // alerT?
324             }
325             console.log(s);
326             
327         },
328         /**
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.
330          * @param {Object} o
331          * @return {String}
332          */
333         urlEncode : function(o){
334             if(!o){
335                 return "";
336             }
337             var buf = [];
338             for(var key in o){
339                 var ov = o[key], k = Roo.encodeURIComponent(key);
340                 var type = typeof ov;
341                 if(type == 'undefined'){
342                     buf.push(k, "=&");
343                 }else if(type != "function" && type != "object"){
344                     buf.push(k, "=", Roo.encodeURIComponent(ov), "&");
345                 }else if(ov instanceof Array){
346                     if (ov.length) {
347                             for(var i = 0, len = ov.length; i < len; i++) {
348                                 buf.push(k, "=", Roo.encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
349                             }
350                         } else {
351                             buf.push(k, "=&");
352                         }
353                 }
354             }
355             buf.pop();
356             return buf.join("");
357         },
358          /**
359          * Safe version of encodeURIComponent
360          * @param {String} data 
361          * @return {String} 
362          */
363         
364         encodeURIComponent : function (data)
365         {
366             try {
367                 return encodeURIComponent(data);
368             } catch(e) {} // should be an uri encode error.
369             
370             if (data == '' || data == null){
371                return '';
372             }
373             // http://stackoverflow.com/questions/2596483/unicode-and-uri-encoding-decoding-and-escaping-in-javascript
374             function nibble_to_hex(nibble){
375                 var chars = '0123456789ABCDEF';
376                 return chars.charAt(nibble);
377             }
378             data = data.toString();
379             var buffer = '';
380             for(var i=0; i<data.length; i++){
381                 var c = data.charCodeAt(i);
382                 var bs = new Array();
383                 if (c > 0x10000){
384                         // 4 bytes
385                     bs[0] = 0xF0 | ((c & 0x1C0000) >>> 18);
386                     bs[1] = 0x80 | ((c & 0x3F000) >>> 12);
387                     bs[2] = 0x80 | ((c & 0xFC0) >>> 6);
388                     bs[3] = 0x80 | (c & 0x3F);
389                 }else if (c > 0x800){
390                          // 3 bytes
391                     bs[0] = 0xE0 | ((c & 0xF000) >>> 12);
392                     bs[1] = 0x80 | ((c & 0xFC0) >>> 6);
393                     bs[2] = 0x80 | (c & 0x3F);
394                 }else if (c > 0x80){
395                        // 2 bytes
396                     bs[0] = 0xC0 | ((c & 0x7C0) >>> 6);
397                     bs[1] = 0x80 | (c & 0x3F);
398                 }else{
399                         // 1 byte
400                     bs[0] = c;
401                 }
402                 for(var j=0; j<bs.length; j++){
403                     var b = bs[j];
404                     var hex = nibble_to_hex((b & 0xF0) >>> 4) 
405                             + nibble_to_hex(b &0x0F);
406                     buffer += '%'+hex;
407                }
408             }
409             return buffer;    
410              
411         },
412
413         /**
414          * 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]}.
415          * @param {String} string
416          * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
417          * @return {Object} A literal with members
418          */
419         urlDecode : function(string, overwrite){
420             if(!string || !string.length){
421                 return {};
422             }
423             var obj = {};
424             var pairs = string.split('&');
425             var pair, name, value;
426             for(var i = 0, len = pairs.length; i < len; i++){
427                 pair = pairs[i].split('=');
428                 name = decodeURIComponent(pair[0]);
429                 value = decodeURIComponent(pair[1]);
430                 if(overwrite !== true){
431                     if(typeof obj[name] == "undefined"){
432                         obj[name] = value;
433                     }else if(typeof obj[name] == "string"){
434                         obj[name] = [obj[name]];
435                         obj[name].push(value);
436                     }else{
437                         obj[name].push(value);
438                     }
439                 }else{
440                     obj[name] = value;
441                 }
442             }
443             return obj;
444         },
445
446         /**
447          * Iterates an array calling the passed function with each item, stopping if your function returns false. If the
448          * passed array is not really an array, your function is called once with it.
449          * The supplied function is called with (Object item, Number index, Array allItems).
450          * @param {Array/NodeList/Mixed} array
451          * @param {Function} fn
452          * @param {Object} scope
453          */
454         each : function(array, fn, scope){
455             if(typeof array.length == "undefined" || typeof array == "string"){
456                 array = [array];
457             }
458             for(var i = 0, len = array.length; i < len; i++){
459                 if(fn.call(scope || array[i], array[i], i, array) === false){ return i; };
460             }
461         },
462
463         // deprecated
464         combine : function(){
465             var as = arguments, l = as.length, r = [];
466             for(var i = 0; i < l; i++){
467                 var a = as[i];
468                 if(a instanceof Array){
469                     r = r.concat(a);
470                 }else if(a.length !== undefined && !a.substr){
471                     r = r.concat(Array.prototype.slice.call(a, 0));
472                 }else{
473                     r.push(a);
474                 }
475             }
476             return r;
477         },
478
479         /**
480          * Escapes the passed string for use in a regular expression
481          * @param {String} str
482          * @return {String}
483          */
484         escapeRe : function(s) {
485             return s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1");
486         },
487
488         // internal
489         callback : function(cb, scope, args, delay){
490             if(typeof cb == "function"){
491                 if(delay){
492                     cb.defer(delay, scope, args || []);
493                 }else{
494                     cb.apply(scope, args || []);
495                 }
496             }
497         },
498
499         /**
500          * Return the dom node for the passed string (id), dom node, or Roo.Element
501          * @param {String/HTMLElement/Roo.Element} el
502          * @return HTMLElement
503          */
504         getDom : function(el){
505             if(!el){
506                 return null;
507             }
508             return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
509         },
510
511         /**
512         * Shorthand for {@link Roo.ComponentMgr#get}
513         * @param {String} id
514         * @return Roo.Component
515         */
516         getCmp : function(id){
517             return Roo.ComponentMgr.get(id);
518         },
519          
520         num : function(v, defaultValue){
521             if(typeof v != 'number'){
522                 return defaultValue;
523             }
524             return v;
525         },
526
527         destroy : function(){
528             for(var i = 0, a = arguments, len = a.length; i < len; i++) {
529                 var as = a[i];
530                 if(as){
531                     if(as.dom){
532                         as.removeAllListeners();
533                         as.remove();
534                         continue;
535                     }
536                     if(typeof as.purgeListeners == 'function'){
537                         as.purgeListeners();
538                     }
539                     if(typeof as.destroy == 'function'){
540                         as.destroy();
541                     }
542                 }
543             }
544         },
545
546         // inpired by a similar function in mootools library
547         /**
548          * Returns the type of object that is passed in. If the object passed in is null or undefined it
549          * return false otherwise it returns one of the following values:<ul>
550          * <li><b>string</b>: If the object passed is a string</li>
551          * <li><b>number</b>: If the object passed is a number</li>
552          * <li><b>boolean</b>: If the object passed is a boolean value</li>
553          * <li><b>function</b>: If the object passed is a function reference</li>
554          * <li><b>object</b>: If the object passed is an object</li>
555          * <li><b>array</b>: If the object passed is an array</li>
556          * <li><b>regexp</b>: If the object passed is a regular expression</li>
557          * <li><b>element</b>: If the object passed is a DOM Element</li>
558          * <li><b>nodelist</b>: If the object passed is a DOM NodeList</li>
559          * <li><b>textnode</b>: If the object passed is a DOM text node and contains something other than whitespace</li>
560          * <li><b>whitespace</b>: If the object passed is a DOM text node and contains only whitespace</li>
561          * @param {Mixed} object
562          * @return {String}
563          */
564         type : function(o){
565             if(o === undefined || o === null){
566                 return false;
567             }
568             if(o.htmlElement){
569                 return 'element';
570             }
571             var t = typeof o;
572             if(t == 'object' && o.nodeName) {
573                 switch(o.nodeType) {
574                     case 1: return 'element';
575                     case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace';
576                 }
577             }
578             if(t == 'object' || t == 'function') {
579                 switch(o.constructor) {
580                     case Array: return 'array';
581                     case RegExp: return 'regexp';
582                 }
583                 if(typeof o.length == 'number' && typeof o.item == 'function') {
584                     return 'nodelist';
585                 }
586             }
587             return t;
588         },
589
590         /**
591          * Returns true if the passed value is null, undefined or an empty string (optional).
592          * @param {Mixed} value The value to test
593          * @param {Boolean} allowBlank (optional) Pass true if an empty string is not considered empty
594          * @return {Boolean}
595          */
596         isEmpty : function(v, allowBlank){
597             return v === null || v === undefined || (!allowBlank ? v === '' : false);
598         },
599         
600         /** @type Boolean */
601         isOpera : isOpera,
602         /** @type Boolean */
603         isSafari : isSafari,
604         /** @type Boolean */
605         isIE : isIE,
606         /** @type Boolean */
607         isIE7 : isIE7,
608         /** @type Boolean */
609         isGecko : isGecko,
610         /** @type Boolean */
611         isBorderBox : isBorderBox,
612         /** @type Boolean */
613         isWindows : isWindows,
614         /** @type Boolean */
615         isLinux : isLinux,
616         /** @type Boolean */
617         isMac : isMac,
618
619         /**
620          * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
621          * you may want to set this to true.
622          * @type Boolean
623          */
624         useShims : ((isIE && !isIE7) || (isGecko && isMac)),
625         
626         
627                 
628         /**
629          * Selects a single element as a Roo Element
630          * This is about as close as you can get to jQuery's $('do crazy stuff')
631          * @param {String} selector The selector/xpath query
632          * @param {Node} root (optional) The start of the query (defaults to document).
633          * @return {Roo.Element}
634          */
635         selectNode : function(selector, root) 
636         {
637             var node = Roo.DomQuery.selectNode(selector,root);
638             return node ? Roo.get(node) : new Roo.Element(false);
639         }
640         
641     });
642
643
644 })();
645
646 Roo.namespace("Roo", "Roo.util", "Roo.grid", "Roo.dd", "Roo.tree", "Roo.data",
647                 "Roo.form", "Roo.menu", "Roo.state", "Roo.lib", "Roo.layout", "Roo.app", "Roo.ux");
648 /*
649  * Based on:
650  * Ext JS Library 1.1.1
651  * Copyright(c) 2006-2007, Ext JS, LLC.
652  *
653  * Originally Released Under LGPL - original licence link has changed is not relivant.
654  *
655  * Fork - LGPL
656  * <script type="text/javascript">
657  */
658
659 (function() {    
660     // wrappedn so fnCleanup is not in global scope...
661     if(Roo.isIE) {
662         function fnCleanUp() {
663             var p = Function.prototype;
664             delete p.createSequence;
665             delete p.defer;
666             delete p.createDelegate;
667             delete p.createCallback;
668             delete p.createInterceptor;
669
670             window.detachEvent("onunload", fnCleanUp);
671         }
672         window.attachEvent("onunload", fnCleanUp);
673     }
674 })();
675
676
677 /**
678  * @class Function
679  * These functions are available on every Function object (any JavaScript function).
680  */
681 Roo.apply(Function.prototype, {
682      /**
683      * Creates a callback that passes arguments[0], arguments[1], arguments[2], ...
684      * Call directly on any function. Example: <code>myFunction.createCallback(myarg, myarg2)</code>
685      * Will create a function that is bound to those 2 args.
686      * @return {Function} The new function
687     */
688     createCallback : function(/*args...*/){
689         // make args available, in function below
690         var args = arguments;
691         var method = this;
692         return function() {
693             return method.apply(window, args);
694         };
695     },
696
697     /**
698      * Creates a delegate (callback) that sets the scope to obj.
699      * Call directly on any function. Example: <code>this.myFunction.createDelegate(this)</code>
700      * Will create a function that is automatically scoped to this.
701      * @param {Object} obj (optional) The object for which the scope is set
702      * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
703      * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
704      *                                             if a number the args are inserted at the specified position
705      * @return {Function} The new function
706      */
707     createDelegate : function(obj, args, appendArgs){
708         var method = this;
709         return function() {
710             var callArgs = args || arguments;
711             if(appendArgs === true){
712                 callArgs = Array.prototype.slice.call(arguments, 0);
713                 callArgs = callArgs.concat(args);
714             }else if(typeof appendArgs == "number"){
715                 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
716                 var applyArgs = [appendArgs, 0].concat(args); // create method call params
717                 Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
718             }
719             return method.apply(obj || window, callArgs);
720         };
721     },
722
723     /**
724      * Calls this function after the number of millseconds specified.
725      * @param {Number} millis The number of milliseconds for the setTimeout call (if 0 the function is executed immediately)
726      * @param {Object} obj (optional) The object for which the scope is set
727      * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
728      * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
729      *                                             if a number the args are inserted at the specified position
730      * @return {Number} The timeout id that can be used with clearTimeout
731      */
732     defer : function(millis, obj, args, appendArgs){
733         var fn = this.createDelegate(obj, args, appendArgs);
734         if(millis){
735             return setTimeout(fn, millis);
736         }
737         fn();
738         return 0;
739     },
740     /**
741      * Create a combined function call sequence of the original function + the passed function.
742      * The resulting function returns the results of the original function.
743      * The passed fcn is called with the parameters of the original function
744      * @param {Function} fcn The function to sequence
745      * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
746      * @return {Function} The new function
747      */
748     createSequence : function(fcn, scope){
749         if(typeof fcn != "function"){
750             return this;
751         }
752         var method = this;
753         return function() {
754             var retval = method.apply(this || window, arguments);
755             fcn.apply(scope || this || window, arguments);
756             return retval;
757         };
758     },
759
760     /**
761      * Creates an interceptor function. The passed fcn is called before the original one. If it returns false, the original one is not called.
762      * The resulting function returns the results of the original function.
763      * The passed fcn is called with the parameters of the original function.
764      * @addon
765      * @param {Function} fcn The function to call before the original
766      * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
767      * @return {Function} The new function
768      */
769     createInterceptor : function(fcn, scope){
770         if(typeof fcn != "function"){
771             return this;
772         }
773         var method = this;
774         return function() {
775             fcn.target = this;
776             fcn.method = method;
777             if(fcn.apply(scope || this || window, arguments) === false){
778                 return;
779             }
780             return method.apply(this || window, arguments);
781         };
782     }
783 });
784 /*
785  * Based on:
786  * Ext JS Library 1.1.1
787  * Copyright(c) 2006-2007, Ext JS, LLC.
788  *
789  * Originally Released Under LGPL - original licence link has changed is not relivant.
790  *
791  * Fork - LGPL
792  * <script type="text/javascript">
793  */
794
795 Roo.applyIf(String, {
796     
797     /** @scope String */
798     
799     /**
800      * Escapes the passed string for ' and \
801      * @param {String} string The string to escape
802      * @return {String} The escaped string
803      * @static
804      */
805     escape : function(string) {
806         return string.replace(/('|\\)/g, "\\$1");
807     },
808
809     /**
810      * Pads the left side of a string with a specified character.  This is especially useful
811      * for normalizing number and date strings.  Example usage:
812      * <pre><code>
813 var s = String.leftPad('123', 5, '0');
814 // s now contains the string: '00123'
815 </code></pre>
816      * @param {String} string The original string
817      * @param {Number} size The total length of the output string
818      * @param {String} char (optional) The character with which to pad the original string (defaults to empty string " ")
819      * @return {String} The padded string
820      * @static
821      */
822     leftPad : function (val, size, ch) {
823         var result = new String(val);
824         if(ch === null || ch === undefined || ch === '') {
825             ch = " ";
826         }
827         while (result.length < size) {
828             result = ch + result;
829         }
830         return result;
831     },
832
833     /**
834      * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens.  Each
835      * token must be unique, and must increment in the format {0}, {1}, etc.  Example usage:
836      * <pre><code>
837 var cls = 'my-class', text = 'Some text';
838 var s = String.format('<div class="{0}">{1}</div>', cls, text);
839 // s now contains the string: '<div class="my-class">Some text</div>'
840 </code></pre>
841      * @param {String} string The tokenized string to be formatted
842      * @param {String} value1 The value to replace token {0}
843      * @param {String} value2 Etc...
844      * @return {String} The formatted string
845      * @static
846      */
847     format : function(format){
848         var args = Array.prototype.slice.call(arguments, 1);
849         return format.replace(/\{(\d+)\}/g, function(m, i){
850             return Roo.util.Format.htmlEncode(args[i]);
851         });
852     }
853 });
854
855 /**
856  * Utility function that allows you to easily switch a string between two alternating values.  The passed value
857  * is compared to the current string, and if they are equal, the other value that was passed in is returned.  If
858  * they are already different, the first value passed in is returned.  Note that this method returns the new value
859  * but does not change the current string.
860  * <pre><code>
861 // alternate sort directions
862 sort = sort.toggle('ASC', 'DESC');
863
864 // instead of conditional logic:
865 sort = (sort == 'ASC' ? 'DESC' : 'ASC');
866 </code></pre>
867  * @param {String} value The value to compare to the current string
868  * @param {String} other The new value to use if the string already equals the first value passed in
869  * @return {String} The new value
870  */
871  
872 String.prototype.toggle = function(value, other){
873     return this == value ? other : value;
874 };/*
875  * Based on:
876  * Ext JS Library 1.1.1
877  * Copyright(c) 2006-2007, Ext JS, LLC.
878  *
879  * Originally Released Under LGPL - original licence link has changed is not relivant.
880  *
881  * Fork - LGPL
882  * <script type="text/javascript">
883  */
884
885  /**
886  * @class Number
887  */
888 Roo.applyIf(Number.prototype, {
889     /**
890      * Checks whether or not the current number is within a desired range.  If the number is already within the
891      * range it is returned, otherwise the min or max value is returned depending on which side of the range is
892      * exceeded.  Note that this method returns the constrained value but does not change the current number.
893      * @param {Number} min The minimum number in the range
894      * @param {Number} max The maximum number in the range
895      * @return {Number} The constrained value if outside the range, otherwise the current value
896      */
897     constrain : function(min, max){
898         return Math.min(Math.max(this, min), max);
899     }
900 });/*
901  * Based on:
902  * Ext JS Library 1.1.1
903  * Copyright(c) 2006-2007, Ext JS, LLC.
904  *
905  * Originally Released Under LGPL - original licence link has changed is not relivant.
906  *
907  * Fork - LGPL
908  * <script type="text/javascript">
909  */
910  /**
911  * @class Array
912  */
913 Roo.applyIf(Array.prototype, {
914     /**
915      * Checks whether or not the specified object exists in the array.
916      * @param {Object} o The object to check for
917      * @return {Number} The index of o in the array (or -1 if it is not found)
918      */
919     indexOf : function(o){
920        for (var i = 0, len = this.length; i < len; i++){
921               if(this[i] == o) return i;
922        }
923            return -1;
924     },
925
926     /**
927      * Removes the specified object from the array.  If the object is not found nothing happens.
928      * @param {Object} o The object to remove
929      */
930     remove : function(o){
931        var index = this.indexOf(o);
932        if(index != -1){
933            this.splice(index, 1);
934        }
935     },
936     /**
937      * Map (JS 1.6 compatibility)
938      * @param {Function} function  to call
939      */
940     map : function(fun )
941     {
942         var len = this.length >>> 0;
943         if (typeof fun != "function")
944             throw new TypeError();
945
946         var res = new Array(len);
947         var thisp = arguments[1];
948         for (var i = 0; i < len; i++)
949         {
950             if (i in this)
951                 res[i] = fun.call(thisp, this[i], i, this);
952         }
953
954         return res;
955     }
956     
957 });
958
959
960  /*
961  * Based on:
962  * Ext JS Library 1.1.1
963  * Copyright(c) 2006-2007, Ext JS, LLC.
964  *
965  * Originally Released Under LGPL - original licence link has changed is not relivant.
966  *
967  * Fork - LGPL
968  * <script type="text/javascript">
969  */
970
971 /**
972  * @class Date
973  *
974  * The date parsing and format syntax is a subset of
975  * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
976  * supported will provide results equivalent to their PHP versions.
977  *
978  * Following is the list of all currently supported formats:
979  *<pre>
980 Sample date:
981 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
982
983 Format  Output      Description
984 ------  ----------  --------------------------------------------------------------
985   d      10         Day of the month, 2 digits with leading zeros
986   D      Wed        A textual representation of a day, three letters
987   j      10         Day of the month without leading zeros
988   l      Wednesday  A full textual representation of the day of the week
989   S      th         English ordinal day of month suffix, 2 chars (use with j)
990   w      3          Numeric representation of the day of the week
991   z      9          The julian date, or day of the year (0-365)
992   W      01         ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
993   F      January    A full textual representation of the month
994   m      01         Numeric representation of a month, with leading zeros
995   M      Jan        Month name abbreviation, three letters
996   n      1          Numeric representation of a month, without leading zeros
997   t      31         Number of days in the given month
998   L      0          Whether it's a leap year (1 if it is a leap year, else 0)
999   Y      2007       A full numeric representation of a year, 4 digits
1000   y      07         A two digit representation of a year
1001   a      pm         Lowercase Ante meridiem and Post meridiem
1002   A      PM         Uppercase Ante meridiem and Post meridiem
1003   g      3          12-hour format of an hour without leading zeros
1004   G      15         24-hour format of an hour without leading zeros
1005   h      03         12-hour format of an hour with leading zeros
1006   H      15         24-hour format of an hour with leading zeros
1007   i      05         Minutes with leading zeros
1008   s      01         Seconds, with leading zeros
1009   O      -0600      Difference to Greenwich time (GMT) in hours
1010   P      -06:00     Difference to Greenwich time (GMT) with colon between hours and minutes
1011   T      CST        Timezone setting of the machine running the code
1012   Z      -21600     Timezone offset in seconds (negative if west of UTC, positive if east)
1013 </pre>
1014  *
1015  * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
1016  * <pre><code>
1017 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
1018 document.write(dt.format('Y-m-d'));                         //2007-01-10
1019 document.write(dt.format('F j, Y, g:i a'));                 //January 10, 2007, 3:05 pm
1020 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
1021  </code></pre>
1022  *
1023  * Here are some standard date/time patterns that you might find helpful.  They
1024  * are not part of the source of Date.js, but to use them you can simply copy this
1025  * block of code into any script that is included after Date.js and they will also become
1026  * globally available on the Date object.  Feel free to add or remove patterns as needed in your code.
1027  * <pre><code>
1028 Date.patterns = {
1029     ISO8601Long:"Y-m-d H:i:s",
1030     ISO8601Short:"Y-m-d",
1031     ShortDate: "n/j/Y",
1032     LongDate: "l, F d, Y",
1033     FullDateTime: "l, F d, Y g:i:s A",
1034     MonthDay: "F d",
1035     ShortTime: "g:i A",
1036     LongTime: "g:i:s A",
1037     SortableDateTime: "Y-m-d\\TH:i:s",
1038     UniversalSortableDateTime: "Y-m-d H:i:sO",
1039     YearMonth: "F, Y"
1040 };
1041 </code></pre>
1042  *
1043  * Example usage:
1044  * <pre><code>
1045 var dt = new Date();
1046 document.write(dt.format(Date.patterns.ShortDate));
1047  </code></pre>
1048  */
1049
1050 /*
1051  * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
1052  * They generate precompiled functions from date formats instead of parsing and
1053  * processing the pattern every time you format a date.  These functions are available
1054  * on every Date object (any javascript function).
1055  *
1056  * The original article and download are here:
1057  * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
1058  *
1059  */
1060  
1061  
1062  // was in core
1063 /**
1064  Returns the number of milliseconds between this date and date
1065  @param {Date} date (optional) Defaults to now
1066  @return {Number} The diff in milliseconds
1067  @member Date getElapsed
1068  */
1069 Date.prototype.getElapsed = function(date) {
1070         return Math.abs((date || new Date()).getTime()-this.getTime());
1071 };
1072 // was in date file..
1073
1074
1075 // private
1076 Date.parseFunctions = {count:0};
1077 // private
1078 Date.parseRegexes = [];
1079 // private
1080 Date.formatFunctions = {count:0};
1081
1082 // private
1083 Date.prototype.dateFormat = function(format) {
1084     if (Date.formatFunctions[format] == null) {
1085         Date.createNewFormat(format);
1086     }
1087     var func = Date.formatFunctions[format];
1088     return this[func]();
1089 };
1090
1091
1092 /**
1093  * Formats a date given the supplied format string
1094  * @param {String} format The format string
1095  * @return {String} The formatted date
1096  * @method
1097  */
1098 Date.prototype.format = Date.prototype.dateFormat;
1099
1100 // private
1101 Date.createNewFormat = function(format) {
1102     var funcName = "format" + Date.formatFunctions.count++;
1103     Date.formatFunctions[format] = funcName;
1104     var code = "Date.prototype." + funcName + " = function(){return ";
1105     var special = false;
1106     var ch = '';
1107     for (var i = 0; i < format.length; ++i) {
1108         ch = format.charAt(i);
1109         if (!special && ch == "\\") {
1110             special = true;
1111         }
1112         else if (special) {
1113             special = false;
1114             code += "'" + String.escape(ch) + "' + ";
1115         }
1116         else {
1117             code += Date.getFormatCode(ch);
1118         }
1119     }
1120     /** eval:var:zzzzzzzzzzzzz */
1121     eval(code.substring(0, code.length - 3) + ";}");
1122 };
1123
1124 // private
1125 Date.getFormatCode = function(character) {
1126     switch (character) {
1127     case "d":
1128         return "String.leftPad(this.getDate(), 2, '0') + ";
1129     case "D":
1130         return "Date.dayNames[this.getDay()].substring(0, 3) + ";
1131     case "j":
1132         return "this.getDate() + ";
1133     case "l":
1134         return "Date.dayNames[this.getDay()] + ";
1135     case "S":
1136         return "this.getSuffix() + ";
1137     case "w":
1138         return "this.getDay() + ";
1139     case "z":
1140         return "this.getDayOfYear() + ";
1141     case "W":
1142         return "this.getWeekOfYear() + ";
1143     case "F":
1144         return "Date.monthNames[this.getMonth()] + ";
1145     case "m":
1146         return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
1147     case "M":
1148         return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
1149     case "n":
1150         return "(this.getMonth() + 1) + ";
1151     case "t":
1152         return "this.getDaysInMonth() + ";
1153     case "L":
1154         return "(this.isLeapYear() ? 1 : 0) + ";
1155     case "Y":
1156         return "this.getFullYear() + ";
1157     case "y":
1158         return "('' + this.getFullYear()).substring(2, 4) + ";
1159     case "a":
1160         return "(this.getHours() < 12 ? 'am' : 'pm') + ";
1161     case "A":
1162         return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
1163     case "g":
1164         return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
1165     case "G":
1166         return "this.getHours() + ";
1167     case "h":
1168         return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
1169     case "H":
1170         return "String.leftPad(this.getHours(), 2, '0') + ";
1171     case "i":
1172         return "String.leftPad(this.getMinutes(), 2, '0') + ";
1173     case "s":
1174         return "String.leftPad(this.getSeconds(), 2, '0') + ";
1175     case "O":
1176         return "this.getGMTOffset() + ";
1177     case "P":
1178         return "this.getGMTColonOffset() + ";
1179     case "T":
1180         return "this.getTimezone() + ";
1181     case "Z":
1182         return "(this.getTimezoneOffset() * -60) + ";
1183     default:
1184         return "'" + String.escape(character) + "' + ";
1185     }
1186 };
1187
1188 /**
1189  * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
1190  * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates.  Any part of
1191  * the date format that is not specified will default to the current date value for that part.  Time parts can also
1192  * be specified, but default to 0.  Keep in mind that the input date string must precisely match the specified format
1193  * string or the parse operation will fail.
1194  * Example Usage:
1195 <pre><code>
1196 //dt = Fri May 25 2007 (current date)
1197 var dt = new Date();
1198
1199 //dt = Thu May 25 2006 (today's month/day in 2006)
1200 dt = Date.parseDate("2006", "Y");
1201
1202 //dt = Sun Jan 15 2006 (all date parts specified)
1203 dt = Date.parseDate("2006-1-15", "Y-m-d");
1204
1205 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
1206 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
1207 </code></pre>
1208  * @param {String} input The unparsed date as a string
1209  * @param {String} format The format the date is in
1210  * @return {Date} The parsed date
1211  * @static
1212  */
1213 Date.parseDate = function(input, format) {
1214     if (Date.parseFunctions[format] == null) {
1215         Date.createParser(format);
1216     }
1217     var func = Date.parseFunctions[format];
1218     return Date[func](input);
1219 };
1220 /**
1221  * @private
1222  */
1223 Date.createParser = function(format) {
1224     var funcName = "parse" + Date.parseFunctions.count++;
1225     var regexNum = Date.parseRegexes.length;
1226     var currentGroup = 1;
1227     Date.parseFunctions[format] = funcName;
1228
1229     var code = "Date." + funcName + " = function(input){\n"
1230         + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
1231         + "var d = new Date();\n"
1232         + "y = d.getFullYear();\n"
1233         + "m = d.getMonth();\n"
1234         + "d = d.getDate();\n"
1235         + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
1236         + "if (results && results.length > 0) {";
1237     var regex = "";
1238
1239     var special = false;
1240     var ch = '';
1241     for (var i = 0; i < format.length; ++i) {
1242         ch = format.charAt(i);
1243         if (!special && ch == "\\") {
1244             special = true;
1245         }
1246         else if (special) {
1247             special = false;
1248             regex += String.escape(ch);
1249         }
1250         else {
1251             var obj = Date.formatCodeToRegex(ch, currentGroup);
1252             currentGroup += obj.g;
1253             regex += obj.s;
1254             if (obj.g && obj.c) {
1255                 code += obj.c;
1256             }
1257         }
1258     }
1259
1260     code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
1261         + "{v = new Date(y, m, d, h, i, s);}\n"
1262         + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
1263         + "{v = new Date(y, m, d, h, i);}\n"
1264         + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
1265         + "{v = new Date(y, m, d, h);}\n"
1266         + "else if (y >= 0 && m >= 0 && d > 0)\n"
1267         + "{v = new Date(y, m, d);}\n"
1268         + "else if (y >= 0 && m >= 0)\n"
1269         + "{v = new Date(y, m);}\n"
1270         + "else if (y >= 0)\n"
1271         + "{v = new Date(y);}\n"
1272         + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
1273         + "    ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
1274         + "        v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
1275         + ";}";
1276
1277     Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
1278     /** eval:var:zzzzzzzzzzzzz */
1279     eval(code);
1280 };
1281
1282 // private
1283 Date.formatCodeToRegex = function(character, currentGroup) {
1284     switch (character) {
1285     case "D":
1286         return {g:0,
1287         c:null,
1288         s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
1289     case "j":
1290         return {g:1,
1291             c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1292             s:"(\\d{1,2})"}; // day of month without leading zeroes
1293     case "d":
1294         return {g:1,
1295             c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1296             s:"(\\d{2})"}; // day of month with leading zeroes
1297     case "l":
1298         return {g:0,
1299             c:null,
1300             s:"(?:" + Date.dayNames.join("|") + ")"};
1301     case "S":
1302         return {g:0,
1303             c:null,
1304             s:"(?:st|nd|rd|th)"};
1305     case "w":
1306         return {g:0,
1307             c:null,
1308             s:"\\d"};
1309     case "z":
1310         return {g:0,
1311             c:null,
1312             s:"(?:\\d{1,3})"};
1313     case "W":
1314         return {g:0,
1315             c:null,
1316             s:"(?:\\d{2})"};
1317     case "F":
1318         return {g:1,
1319             c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
1320             s:"(" + Date.monthNames.join("|") + ")"};
1321     case "M":
1322         return {g:1,
1323             c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
1324             s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
1325     case "n":
1326         return {g:1,
1327             c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1328             s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
1329     case "m":
1330         return {g:1,
1331             c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1332             s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
1333     case "t":
1334         return {g:0,
1335             c:null,
1336             s:"\\d{1,2}"};
1337     case "L":
1338         return {g:0,
1339             c:null,
1340             s:"(?:1|0)"};
1341     case "Y":
1342         return {g:1,
1343             c:"y = parseInt(results[" + currentGroup + "], 10);\n",
1344             s:"(\\d{4})"};
1345     case "y":
1346         return {g:1,
1347             c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
1348                 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
1349             s:"(\\d{1,2})"};
1350     case "a":
1351         return {g:1,
1352             c:"if (results[" + currentGroup + "] == 'am') {\n"
1353                 + "if (h == 12) { h = 0; }\n"
1354                 + "} else { if (h < 12) { h += 12; }}",
1355             s:"(am|pm)"};
1356     case "A":
1357         return {g:1,
1358             c:"if (results[" + currentGroup + "] == 'AM') {\n"
1359                 + "if (h == 12) { h = 0; }\n"
1360                 + "} else { if (h < 12) { h += 12; }}",
1361             s:"(AM|PM)"};
1362     case "g":
1363     case "G":
1364         return {g:1,
1365             c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1366             s:"(\\d{1,2})"}; // 12/24-hr format  format of an hour without leading zeroes
1367     case "h":
1368     case "H":
1369         return {g:1,
1370             c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1371             s:"(\\d{2})"}; //  12/24-hr format  format of an hour with leading zeroes
1372     case "i":
1373         return {g:1,
1374             c:"i = parseInt(results[" + currentGroup + "], 10);\n",
1375             s:"(\\d{2})"};
1376     case "s":
1377         return {g:1,
1378             c:"s = parseInt(results[" + currentGroup + "], 10);\n",
1379             s:"(\\d{2})"};
1380     case "O":
1381         return {g:1,
1382             c:[
1383                 "o = results[", currentGroup, "];\n",
1384                 "var sn = o.substring(0,1);\n", // get + / - sign
1385                 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
1386                 "var mn = o.substring(3,5) % 60;\n", // get minutes
1387                 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
1388                 "    (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1389             ].join(""),
1390             s:"([+\-]\\d{4})"};
1391     case "P":
1392         return {g:1,
1393                 c:[
1394                    "o = results[", currentGroup, "];\n",
1395                    "var sn = o.substring(0,1);\n",
1396                    "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n",
1397                    "var mn = o.substring(4,6) % 60;\n",
1398                    "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n",
1399                         "    (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1400             ].join(""),
1401             s:"([+\-]\\d{4})"};
1402     case "T":
1403         return {g:0,
1404             c:null,
1405             s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
1406     case "Z":
1407         return {g:1,
1408             c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
1409                   + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
1410             s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
1411     default:
1412         return {g:0,
1413             c:null,
1414             s:String.escape(character)};
1415     }
1416 };
1417
1418 /**
1419  * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
1420  * @return {String} The abbreviated timezone name (e.g. 'CST')
1421  */
1422 Date.prototype.getTimezone = function() {
1423     return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
1424 };
1425
1426 /**
1427  * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
1428  * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
1429  */
1430 Date.prototype.getGMTOffset = function() {
1431     return (this.getTimezoneOffset() > 0 ? "-" : "+")
1432         + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1433         + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
1434 };
1435
1436 /**
1437  * Get the offset from GMT of the current date (equivalent to the format specifier 'P').
1438  * @return {String} 2-characters representing hours and 2-characters representing minutes
1439  * seperated by a colon and prefixed with + or - (e.g. '-06:00')
1440  */
1441 Date.prototype.getGMTColonOffset = function() {
1442         return (this.getTimezoneOffset() > 0 ? "-" : "+")
1443                 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1444                 + ":"
1445                 + String.leftPad(this.getTimezoneOffset() %60, 2, "0");
1446 }
1447
1448 /**
1449  * Get the numeric day number of the year, adjusted for leap year.
1450  * @return {Number} 0 through 364 (365 in leap years)
1451  */
1452 Date.prototype.getDayOfYear = function() {
1453     var num = 0;
1454     Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1455     for (var i = 0; i < this.getMonth(); ++i) {
1456         num += Date.daysInMonth[i];
1457     }
1458     return num + this.getDate() - 1;
1459 };
1460
1461 /**
1462  * Get the string representation of the numeric week number of the year
1463  * (equivalent to the format specifier 'W').
1464  * @return {String} '00' through '52'
1465  */
1466 Date.prototype.getWeekOfYear = function() {
1467     // Skip to Thursday of this week
1468     var now = this.getDayOfYear() + (4 - this.getDay());
1469     // Find the first Thursday of the year
1470     var jan1 = new Date(this.getFullYear(), 0, 1);
1471     var then = (7 - jan1.getDay() + 4);
1472     return String.leftPad(((now - then) / 7) + 1, 2, "0");
1473 };
1474
1475 /**
1476  * Whether or not the current date is in a leap year.
1477  * @return {Boolean} True if the current date is in a leap year, else false
1478  */
1479 Date.prototype.isLeapYear = function() {
1480     var year = this.getFullYear();
1481     return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
1482 };
1483
1484 /**
1485  * Get the first day of the current month, adjusted for leap year.  The returned value
1486  * is the numeric day index within the week (0-6) which can be used in conjunction with
1487  * the {@link #monthNames} array to retrieve the textual day name.
1488  * Example:
1489  *<pre><code>
1490 var dt = new Date('1/10/2007');
1491 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
1492 </code></pre>
1493  * @return {Number} The day number (0-6)
1494  */
1495 Date.prototype.getFirstDayOfMonth = function() {
1496     var day = (this.getDay() - (this.getDate() - 1)) % 7;
1497     return (day < 0) ? (day + 7) : day;
1498 };
1499
1500 /**
1501  * Get the last day of the current month, adjusted for leap year.  The returned value
1502  * is the numeric day index within the week (0-6) which can be used in conjunction with
1503  * the {@link #monthNames} array to retrieve the textual day name.
1504  * Example:
1505  *<pre><code>
1506 var dt = new Date('1/10/2007');
1507 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
1508 </code></pre>
1509  * @return {Number} The day number (0-6)
1510  */
1511 Date.prototype.getLastDayOfMonth = function() {
1512     var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
1513     return (day < 0) ? (day + 7) : day;
1514 };
1515
1516
1517 /**
1518  * Get the first date of this date's month
1519  * @return {Date}
1520  */
1521 Date.prototype.getFirstDateOfMonth = function() {
1522     return new Date(this.getFullYear(), this.getMonth(), 1);
1523 };
1524
1525 /**
1526  * Get the last date of this date's month
1527  * @return {Date}
1528  */
1529 Date.prototype.getLastDateOfMonth = function() {
1530     return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
1531 };
1532 /**
1533  * Get the number of days in the current month, adjusted for leap year.
1534  * @return {Number} The number of days in the month
1535  */
1536 Date.prototype.getDaysInMonth = function() {
1537     Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1538     return Date.daysInMonth[this.getMonth()];
1539 };
1540
1541 /**
1542  * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
1543  * @return {String} 'st, 'nd', 'rd' or 'th'
1544  */
1545 Date.prototype.getSuffix = function() {
1546     switch (this.getDate()) {
1547         case 1:
1548         case 21:
1549         case 31:
1550             return "st";
1551         case 2:
1552         case 22:
1553             return "nd";
1554         case 3:
1555         case 23:
1556             return "rd";
1557         default:
1558             return "th";
1559     }
1560 };
1561
1562 // private
1563 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
1564
1565 /**
1566  * An array of textual month names.
1567  * Override these values for international dates, for example...
1568  * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
1569  * @type Array
1570  * @static
1571  */
1572 Date.monthNames =
1573    ["January",
1574     "February",
1575     "March",
1576     "April",
1577     "May",
1578     "June",
1579     "July",
1580     "August",
1581     "September",
1582     "October",
1583     "November",
1584     "December"];
1585
1586 /**
1587  * An array of textual day names.
1588  * Override these values for international dates, for example...
1589  * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
1590  * @type Array
1591  * @static
1592  */
1593 Date.dayNames =
1594    ["Sunday",
1595     "Monday",
1596     "Tuesday",
1597     "Wednesday",
1598     "Thursday",
1599     "Friday",
1600     "Saturday"];
1601
1602 // private
1603 Date.y2kYear = 50;
1604 // private
1605 Date.monthNumbers = {
1606     Jan:0,
1607     Feb:1,
1608     Mar:2,
1609     Apr:3,
1610     May:4,
1611     Jun:5,
1612     Jul:6,
1613     Aug:7,
1614     Sep:8,
1615     Oct:9,
1616     Nov:10,
1617     Dec:11};
1618
1619 /**
1620  * Creates and returns a new Date instance with the exact same date value as the called instance.
1621  * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
1622  * variable will also be changed.  When the intention is to create a new variable that will not
1623  * modify the original instance, you should create a clone.
1624  *
1625  * Example of correctly cloning a date:
1626  * <pre><code>
1627 //wrong way:
1628 var orig = new Date('10/1/2006');
1629 var copy = orig;
1630 copy.setDate(5);
1631 document.write(orig);  //returns 'Thu Oct 05 2006'!
1632
1633 //correct way:
1634 var orig = new Date('10/1/2006');
1635 var copy = orig.clone();
1636 copy.setDate(5);
1637 document.write(orig);  //returns 'Thu Oct 01 2006'
1638 </code></pre>
1639  * @return {Date} The new Date instance
1640  */
1641 Date.prototype.clone = function() {
1642         return new Date(this.getTime());
1643 };
1644
1645 /**
1646  * Clears any time information from this date
1647  @param {Boolean} clone true to create a clone of this date, clear the time and return it
1648  @return {Date} this or the clone
1649  */
1650 Date.prototype.clearTime = function(clone){
1651     if(clone){
1652         return this.clone().clearTime();
1653     }
1654     this.setHours(0);
1655     this.setMinutes(0);
1656     this.setSeconds(0);
1657     this.setMilliseconds(0);
1658     return this;
1659 };
1660
1661 // private
1662 // safari setMonth is broken
1663 if(Roo.isSafari){
1664     Date.brokenSetMonth = Date.prototype.setMonth;
1665         Date.prototype.setMonth = function(num){
1666                 if(num <= -1){
1667                         var n = Math.ceil(-num);
1668                         var back_year = Math.ceil(n/12);
1669                         var month = (n % 12) ? 12 - n % 12 : 0 ;
1670                         this.setFullYear(this.getFullYear() - back_year);
1671                         return Date.brokenSetMonth.call(this, month);
1672                 } else {
1673                         return Date.brokenSetMonth.apply(this, arguments);
1674                 }
1675         };
1676 }
1677
1678 /** Date interval constant 
1679 * @static 
1680 * @type String */
1681 Date.MILLI = "ms";
1682 /** Date interval constant 
1683 * @static 
1684 * @type String */
1685 Date.SECOND = "s";
1686 /** Date interval constant 
1687 * @static 
1688 * @type String */
1689 Date.MINUTE = "mi";
1690 /** Date interval constant 
1691 * @static 
1692 * @type String */
1693 Date.HOUR = "h";
1694 /** Date interval constant 
1695 * @static 
1696 * @type String */
1697 Date.DAY = "d";
1698 /** Date interval constant 
1699 * @static 
1700 * @type String */
1701 Date.MONTH = "mo";
1702 /** Date interval constant 
1703 * @static 
1704 * @type String */
1705 Date.YEAR = "y";
1706
1707 /**
1708  * Provides a convenient method of performing basic date arithmetic.  This method
1709  * does not modify the Date instance being called - it creates and returns
1710  * a new Date instance containing the resulting date value.
1711  *
1712  * Examples:
1713  * <pre><code>
1714 //Basic usage:
1715 var dt = new Date('10/29/2006').add(Date.DAY, 5);
1716 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
1717
1718 //Negative values will subtract correctly:
1719 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
1720 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
1721
1722 //You can even chain several calls together in one line!
1723 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
1724 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
1725  </code></pre>
1726  *
1727  * @param {String} interval   A valid date interval enum value
1728  * @param {Number} value      The amount to add to the current date
1729  * @return {Date} The new Date instance
1730  */
1731 Date.prototype.add = function(interval, value){
1732   var d = this.clone();
1733   if (!interval || value === 0) return d;
1734   switch(interval.toLowerCase()){
1735     case Date.MILLI:
1736       d.setMilliseconds(this.getMilliseconds() + value);
1737       break;
1738     case Date.SECOND:
1739       d.setSeconds(this.getSeconds() + value);
1740       break;
1741     case Date.MINUTE:
1742       d.setMinutes(this.getMinutes() + value);
1743       break;
1744     case Date.HOUR:
1745       d.setHours(this.getHours() + value);
1746       break;
1747     case Date.DAY:
1748       d.setDate(this.getDate() + value);
1749       break;
1750     case Date.MONTH:
1751       var day = this.getDate();
1752       if(day > 28){
1753           day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
1754       }
1755       d.setDate(day);
1756       d.setMonth(this.getMonth() + value);
1757       break;
1758     case Date.YEAR:
1759       d.setFullYear(this.getFullYear() + value);
1760       break;
1761   }
1762   return d;
1763 };
1764 /*
1765  * Based on:
1766  * Ext JS Library 1.1.1
1767  * Copyright(c) 2006-2007, Ext JS, LLC.
1768  *
1769  * Originally Released Under LGPL - original licence link has changed is not relivant.
1770  *
1771  * Fork - LGPL
1772  * <script type="text/javascript">
1773  */
1774
1775 Roo.lib.Dom = {
1776     getViewWidth : function(full) {
1777         return full ? this.getDocumentWidth() : this.getViewportWidth();
1778     },
1779
1780     getViewHeight : function(full) {
1781         return full ? this.getDocumentHeight() : this.getViewportHeight();
1782     },
1783
1784     getDocumentHeight: function() {
1785         var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
1786         return Math.max(scrollHeight, this.getViewportHeight());
1787     },
1788
1789     getDocumentWidth: function() {
1790         var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
1791         return Math.max(scrollWidth, this.getViewportWidth());
1792     },
1793
1794     getViewportHeight: function() {
1795         var height = self.innerHeight;
1796         var mode = document.compatMode;
1797
1798         if ((mode || Roo.isIE) && !Roo.isOpera) {
1799             height = (mode == "CSS1Compat") ?
1800                      document.documentElement.clientHeight :
1801                      document.body.clientHeight;
1802         }
1803
1804         return height;
1805     },
1806
1807     getViewportWidth: function() {
1808         var width = self.innerWidth;
1809         var mode = document.compatMode;
1810
1811         if (mode || Roo.isIE) {
1812             width = (mode == "CSS1Compat") ?
1813                     document.documentElement.clientWidth :
1814                     document.body.clientWidth;
1815         }
1816         return width;
1817     },
1818
1819     isAncestor : function(p, c) {
1820         p = Roo.getDom(p);
1821         c = Roo.getDom(c);
1822         if (!p || !c) {
1823             return false;
1824         }
1825
1826         if (p.contains && !Roo.isSafari) {
1827             return p.contains(c);
1828         } else if (p.compareDocumentPosition) {
1829             return !!(p.compareDocumentPosition(c) & 16);
1830         } else {
1831             var parent = c.parentNode;
1832             while (parent) {
1833                 if (parent == p) {
1834                     return true;
1835                 }
1836                 else if (!parent.tagName || parent.tagName.toUpperCase() == "HTML") {
1837                     return false;
1838                 }
1839                 parent = parent.parentNode;
1840             }
1841             return false;
1842         }
1843     },
1844
1845     getRegion : function(el) {
1846         return Roo.lib.Region.getRegion(el);
1847     },
1848
1849     getY : function(el) {
1850         return this.getXY(el)[1];
1851     },
1852
1853     getX : function(el) {
1854         return this.getXY(el)[0];
1855     },
1856
1857     getXY : function(el) {
1858         var p, pe, b, scroll, bd = document.body;
1859         el = Roo.getDom(el);
1860         var fly = Roo.lib.AnimBase.fly;
1861         if (el.getBoundingClientRect) {
1862             b = el.getBoundingClientRect();
1863             scroll = fly(document).getScroll();
1864             return [b.left + scroll.left, b.top + scroll.top];
1865         }
1866         var x = 0, y = 0;
1867
1868         p = el;
1869
1870         var hasAbsolute = fly(el).getStyle("position") == "absolute";
1871
1872         while (p) {
1873
1874             x += p.offsetLeft;
1875             y += p.offsetTop;
1876
1877             if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
1878                 hasAbsolute = true;
1879             }
1880
1881             if (Roo.isGecko) {
1882                 pe = fly(p);
1883
1884                 var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
1885                 var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
1886
1887
1888                 x += bl;
1889                 y += bt;
1890
1891
1892                 if (p != el && pe.getStyle('overflow') != 'visible') {
1893                     x += bl;
1894                     y += bt;
1895                 }
1896             }
1897             p = p.offsetParent;
1898         }
1899
1900         if (Roo.isSafari && hasAbsolute) {
1901             x -= bd.offsetLeft;
1902             y -= bd.offsetTop;
1903         }
1904
1905         if (Roo.isGecko && !hasAbsolute) {
1906             var dbd = fly(bd);
1907             x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
1908             y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
1909         }
1910
1911         p = el.parentNode;
1912         while (p && p != bd) {
1913             if (!Roo.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
1914                 x -= p.scrollLeft;
1915                 y -= p.scrollTop;
1916             }
1917             p = p.parentNode;
1918         }
1919         return [x, y];
1920     },
1921  
1922   
1923
1924
1925     setXY : function(el, xy) {
1926         el = Roo.fly(el, '_setXY');
1927         el.position();
1928         var pts = el.translatePoints(xy);
1929         if (xy[0] !== false) {
1930             el.dom.style.left = pts.left + "px";
1931         }
1932         if (xy[1] !== false) {
1933             el.dom.style.top = pts.top + "px";
1934         }
1935     },
1936
1937     setX : function(el, x) {
1938         this.setXY(el, [x, false]);
1939     },
1940
1941     setY : function(el, y) {
1942         this.setXY(el, [false, y]);
1943     }
1944 };
1945 /*
1946  * Portions of this file are based on pieces of Yahoo User Interface Library
1947  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
1948  * YUI licensed under the BSD License:
1949  * http://developer.yahoo.net/yui/license.txt
1950  * <script type="text/javascript">
1951  *
1952  */
1953
1954 Roo.lib.Event = function() {
1955     var loadComplete = false;
1956     var listeners = [];
1957     var unloadListeners = [];
1958     var retryCount = 0;
1959     var onAvailStack = [];
1960     var counter = 0;
1961     var lastError = null;
1962
1963     return {
1964         POLL_RETRYS: 200,
1965         POLL_INTERVAL: 20,
1966         EL: 0,
1967         TYPE: 1,
1968         FN: 2,
1969         WFN: 3,
1970         OBJ: 3,
1971         ADJ_SCOPE: 4,
1972         _interval: null,
1973
1974         startInterval: function() {
1975             if (!this._interval) {
1976                 var self = this;
1977                 var callback = function() {
1978                     self._tryPreloadAttach();
1979                 };
1980                 this._interval = setInterval(callback, this.POLL_INTERVAL);
1981
1982             }
1983         },
1984
1985         onAvailable: function(p_id, p_fn, p_obj, p_override) {
1986             onAvailStack.push({ id:         p_id,
1987                 fn:         p_fn,
1988                 obj:        p_obj,
1989                 override:   p_override,
1990                 checkReady: false    });
1991
1992             retryCount = this.POLL_RETRYS;
1993             this.startInterval();
1994         },
1995
1996
1997         addListener: function(el, eventName, fn) {
1998             el = Roo.getDom(el);
1999             if (!el || !fn) {
2000                 return false;
2001             }
2002
2003             if ("unload" == eventName) {
2004                 unloadListeners[unloadListeners.length] =
2005                 [el, eventName, fn];
2006                 return true;
2007             }
2008
2009             var wrappedFn = function(e) {
2010                 return fn(Roo.lib.Event.getEvent(e));
2011             };
2012
2013             var li = [el, eventName, fn, wrappedFn];
2014
2015             var index = listeners.length;
2016             listeners[index] = li;
2017
2018             this.doAdd(el, eventName, wrappedFn, false);
2019             return true;
2020
2021         },
2022
2023
2024         removeListener: function(el, eventName, fn) {
2025             var i, len;
2026
2027             el = Roo.getDom(el);
2028
2029             if(!fn) {
2030                 return this.purgeElement(el, false, eventName);
2031             }
2032
2033
2034             if ("unload" == eventName) {
2035
2036                 for (i = 0,len = unloadListeners.length; i < len; i++) {
2037                     var li = unloadListeners[i];
2038                     if (li &&
2039                         li[0] == el &&
2040                         li[1] == eventName &&
2041                         li[2] == fn) {
2042                         unloadListeners.splice(i, 1);
2043                         return true;
2044                     }
2045                 }
2046
2047                 return false;
2048             }
2049
2050             var cacheItem = null;
2051
2052
2053             var index = arguments[3];
2054
2055             if ("undefined" == typeof index) {
2056                 index = this._getCacheIndex(el, eventName, fn);
2057             }
2058
2059             if (index >= 0) {
2060                 cacheItem = listeners[index];
2061             }
2062
2063             if (!el || !cacheItem) {
2064                 return false;
2065             }
2066
2067             this.doRemove(el, eventName, cacheItem[this.WFN], false);
2068
2069             delete listeners[index][this.WFN];
2070             delete listeners[index][this.FN];
2071             listeners.splice(index, 1);
2072
2073             return true;
2074
2075         },
2076
2077
2078         getTarget: function(ev, resolveTextNode) {
2079             ev = ev.browserEvent || ev;
2080             var t = ev.target || ev.srcElement;
2081             return this.resolveTextNode(t);
2082         },
2083
2084
2085         resolveTextNode: function(node) {
2086             if (Roo.isSafari && node && 3 == node.nodeType) {
2087                 return node.parentNode;
2088             } else {
2089                 return node;
2090             }
2091         },
2092
2093
2094         getPageX: function(ev) {
2095             ev = ev.browserEvent || ev;
2096             var x = ev.pageX;
2097             if (!x && 0 !== x) {
2098                 x = ev.clientX || 0;
2099
2100                 if (Roo.isIE) {
2101                     x += this.getScroll()[1];
2102                 }
2103             }
2104
2105             return x;
2106         },
2107
2108
2109         getPageY: function(ev) {
2110             ev = ev.browserEvent || ev;
2111             var y = ev.pageY;
2112             if (!y && 0 !== y) {
2113                 y = ev.clientY || 0;
2114
2115                 if (Roo.isIE) {
2116                     y += this.getScroll()[0];
2117                 }
2118             }
2119
2120
2121             return y;
2122         },
2123
2124
2125         getXY: function(ev) {
2126             ev = ev.browserEvent || ev;
2127             return [this.getPageX(ev), this.getPageY(ev)];
2128         },
2129
2130
2131         getRelatedTarget: function(ev) {
2132             ev = ev.browserEvent || ev;
2133             var t = ev.relatedTarget;
2134             if (!t) {
2135                 if (ev.type == "mouseout") {
2136                     t = ev.toElement;
2137                 } else if (ev.type == "mouseover") {
2138                     t = ev.fromElement;
2139                 }
2140             }
2141
2142             return this.resolveTextNode(t);
2143         },
2144
2145
2146         getTime: function(ev) {
2147             ev = ev.browserEvent || ev;
2148             if (!ev.time) {
2149                 var t = new Date().getTime();
2150                 try {
2151                     ev.time = t;
2152                 } catch(ex) {
2153                     this.lastError = ex;
2154                     return t;
2155                 }
2156             }
2157
2158             return ev.time;
2159         },
2160
2161
2162         stopEvent: function(ev) {
2163             this.stopPropagation(ev);
2164             this.preventDefault(ev);
2165         },
2166
2167
2168         stopPropagation: function(ev) {
2169             ev = ev.browserEvent || ev;
2170             if (ev.stopPropagation) {
2171                 ev.stopPropagation();
2172             } else {
2173                 ev.cancelBubble = true;
2174             }
2175         },
2176
2177
2178         preventDefault: function(ev) {
2179             ev = ev.browserEvent || ev;
2180             if(ev.preventDefault) {
2181                 ev.preventDefault();
2182             } else {
2183                 ev.returnValue = false;
2184             }
2185         },
2186
2187
2188         getEvent: function(e) {
2189             var ev = e || window.event;
2190             if (!ev) {
2191                 var c = this.getEvent.caller;
2192                 while (c) {
2193                     ev = c.arguments[0];
2194                     if (ev && Event == ev.constructor) {
2195                         break;
2196                     }
2197                     c = c.caller;
2198                 }
2199             }
2200             return ev;
2201         },
2202
2203
2204         getCharCode: function(ev) {
2205             ev = ev.browserEvent || ev;
2206             return ev.charCode || ev.keyCode || 0;
2207         },
2208
2209
2210         _getCacheIndex: function(el, eventName, fn) {
2211             for (var i = 0,len = listeners.length; i < len; ++i) {
2212                 var li = listeners[i];
2213                 if (li &&
2214                     li[this.FN] == fn &&
2215                     li[this.EL] == el &&
2216                     li[this.TYPE] == eventName) {
2217                     return i;
2218                 }
2219             }
2220
2221             return -1;
2222         },
2223
2224
2225         elCache: {},
2226
2227
2228         getEl: function(id) {
2229             return document.getElementById(id);
2230         },
2231
2232
2233         clearCache: function() {
2234         },
2235
2236
2237         _load: function(e) {
2238             loadComplete = true;
2239             var EU = Roo.lib.Event;
2240
2241
2242             if (Roo.isIE) {
2243                 EU.doRemove(window, "load", EU._load);
2244             }
2245         },
2246
2247
2248         _tryPreloadAttach: function() {
2249
2250             if (this.locked) {
2251                 return false;
2252             }
2253
2254             this.locked = true;
2255
2256
2257             var tryAgain = !loadComplete;
2258             if (!tryAgain) {
2259                 tryAgain = (retryCount > 0);
2260             }
2261
2262
2263             var notAvail = [];
2264             for (var i = 0,len = onAvailStack.length; i < len; ++i) {
2265                 var item = onAvailStack[i];
2266                 if (item) {
2267                     var el = this.getEl(item.id);
2268
2269                     if (el) {
2270                         if (!item.checkReady ||
2271                             loadComplete ||
2272                             el.nextSibling ||
2273                             (document && document.body)) {
2274
2275                             var scope = el;
2276                             if (item.override) {
2277                                 if (item.override === true) {
2278                                     scope = item.obj;
2279                                 } else {
2280                                     scope = item.override;
2281                                 }
2282                             }
2283                             item.fn.call(scope, item.obj);
2284                             onAvailStack[i] = null;
2285                         }
2286                     } else {
2287                         notAvail.push(item);
2288                     }
2289                 }
2290             }
2291
2292             retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;
2293
2294             if (tryAgain) {
2295
2296                 this.startInterval();
2297             } else {
2298                 clearInterval(this._interval);
2299                 this._interval = null;
2300             }
2301
2302             this.locked = false;
2303
2304             return true;
2305
2306         },
2307
2308
2309         purgeElement: function(el, recurse, eventName) {
2310             var elListeners = this.getListeners(el, eventName);
2311             if (elListeners) {
2312                 for (var i = 0,len = elListeners.length; i < len; ++i) {
2313                     var l = elListeners[i];
2314                     this.removeListener(el, l.type, l.fn);
2315                 }
2316             }
2317
2318             if (recurse && el && el.childNodes) {
2319                 for (i = 0,len = el.childNodes.length; i < len; ++i) {
2320                     this.purgeElement(el.childNodes[i], recurse, eventName);
2321                 }
2322             }
2323         },
2324
2325
2326         getListeners: function(el, eventName) {
2327             var results = [], searchLists;
2328             if (!eventName) {
2329                 searchLists = [listeners, unloadListeners];
2330             } else if (eventName == "unload") {
2331                 searchLists = [unloadListeners];
2332             } else {
2333                 searchLists = [listeners];
2334             }
2335
2336             for (var j = 0; j < searchLists.length; ++j) {
2337                 var searchList = searchLists[j];
2338                 if (searchList && searchList.length > 0) {
2339                     for (var i = 0,len = searchList.length; i < len; ++i) {
2340                         var l = searchList[i];
2341                         if (l && l[this.EL] === el &&
2342                             (!eventName || eventName === l[this.TYPE])) {
2343                             results.push({
2344                                 type:   l[this.TYPE],
2345                                 fn:     l[this.FN],
2346                                 obj:    l[this.OBJ],
2347                                 adjust: l[this.ADJ_SCOPE],
2348                                 index:  i
2349                             });
2350                         }
2351                     }
2352                 }
2353             }
2354
2355             return (results.length) ? results : null;
2356         },
2357
2358
2359         _unload: function(e) {
2360
2361             var EU = Roo.lib.Event, i, j, l, len, index;
2362
2363             for (i = 0,len = unloadListeners.length; i < len; ++i) {
2364                 l = unloadListeners[i];
2365                 if (l) {
2366                     var scope = window;
2367                     if (l[EU.ADJ_SCOPE]) {
2368                         if (l[EU.ADJ_SCOPE] === true) {
2369                             scope = l[EU.OBJ];
2370                         } else {
2371                             scope = l[EU.ADJ_SCOPE];
2372                         }
2373                     }
2374                     l[EU.FN].call(scope, EU.getEvent(e), l[EU.OBJ]);
2375                     unloadListeners[i] = null;
2376                     l = null;
2377                     scope = null;
2378                 }
2379             }
2380
2381             unloadListeners = null;
2382
2383             if (listeners && listeners.length > 0) {
2384                 j = listeners.length;
2385                 while (j) {
2386                     index = j - 1;
2387                     l = listeners[index];
2388                     if (l) {
2389                         EU.removeListener(l[EU.EL], l[EU.TYPE],
2390                                 l[EU.FN], index);
2391                     }
2392                     j = j - 1;
2393                 }
2394                 l = null;
2395
2396                 EU.clearCache();
2397             }
2398
2399             EU.doRemove(window, "unload", EU._unload);
2400
2401         },
2402
2403
2404         getScroll: function() {
2405             var dd = document.documentElement, db = document.body;
2406             if (dd && (dd.scrollTop || dd.scrollLeft)) {
2407                 return [dd.scrollTop, dd.scrollLeft];
2408             } else if (db) {
2409                 return [db.scrollTop, db.scrollLeft];
2410             } else {
2411                 return [0, 0];
2412             }
2413         },
2414
2415
2416         doAdd: function () {
2417             if (window.addEventListener) {
2418                 return function(el, eventName, fn, capture) {
2419                     el.addEventListener(eventName, fn, (capture));
2420                 };
2421             } else if (window.attachEvent) {
2422                 return function(el, eventName, fn, capture) {
2423                     el.attachEvent("on" + eventName, fn);
2424                 };
2425             } else {
2426                 return function() {
2427                 };
2428             }
2429         }(),
2430
2431
2432         doRemove: function() {
2433             if (window.removeEventListener) {
2434                 return function (el, eventName, fn, capture) {
2435                     el.removeEventListener(eventName, fn, (capture));
2436                 };
2437             } else if (window.detachEvent) {
2438                 return function (el, eventName, fn) {
2439                     el.detachEvent("on" + eventName, fn);
2440                 };
2441             } else {
2442                 return function() {
2443                 };
2444             }
2445         }()
2446     };
2447     
2448 }();
2449 (function() {     
2450    
2451     var E = Roo.lib.Event;
2452     E.on = E.addListener;
2453     E.un = E.removeListener;
2454
2455     if (document && document.body) {
2456         E._load();
2457     } else {
2458         E.doAdd(window, "load", E._load);
2459     }
2460     E.doAdd(window, "unload", E._unload);
2461     E._tryPreloadAttach();
2462 })();
2463
2464 /*
2465  * Portions of this file are based on pieces of Yahoo User Interface Library
2466  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2467  * YUI licensed under the BSD License:
2468  * http://developer.yahoo.net/yui/license.txt
2469  * <script type="text/javascript">
2470  *
2471  */
2472
2473 (function() {
2474     
2475     Roo.lib.Ajax = {
2476         request : function(method, uri, cb, data, options) {
2477             if(options){
2478                 var hs = options.headers;
2479                 if(hs){
2480                     for(var h in hs){
2481                         if(hs.hasOwnProperty(h)){
2482                             this.initHeader(h, hs[h], false);
2483                         }
2484                     }
2485                 }
2486                 if(options.xmlData){
2487                     this.initHeader('Content-Type', 'text/xml', false);
2488                     method = 'POST';
2489                     data = options.xmlData;
2490                 }
2491             }
2492
2493             return this.asyncRequest(method, uri, cb, data);
2494         },
2495
2496         serializeForm : function(form) {
2497             if(typeof form == 'string') {
2498                 form = (document.getElementById(form) || document.forms[form]);
2499             }
2500
2501             var el, name, val, disabled, data = '', hasSubmit = false;
2502             for (var i = 0; i < form.elements.length; i++) {
2503                 el = form.elements[i];
2504                 disabled = form.elements[i].disabled;
2505                 name = form.elements[i].name;
2506                 val = form.elements[i].value;
2507
2508                 if (!disabled && name){
2509                     switch (el.type)
2510                             {
2511                         case 'select-one':
2512                         case 'select-multiple':
2513                             for (var j = 0; j < el.options.length; j++) {
2514                                 if (el.options[j].selected) {
2515                                     if (Roo.isIE) {
2516                                         data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].attributes['value'].specified ? el.options[j].value : el.options[j].text) + '&';
2517                                     }
2518                                     else {
2519                                         data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].hasAttribute('value') ? el.options[j].value : el.options[j].text) + '&';
2520                                     }
2521                                 }
2522                             }
2523                             break;
2524                         case 'radio':
2525                         case 'checkbox':
2526                             if (el.checked) {
2527                                 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2528                             }
2529                             break;
2530                         case 'file':
2531
2532                         case undefined:
2533
2534                         case 'reset':
2535
2536                         case 'button':
2537
2538                             break;
2539                         case 'submit':
2540                             if(hasSubmit == false) {
2541                                 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2542                                 hasSubmit = true;
2543                             }
2544                             break;
2545                         default:
2546                             data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2547                             break;
2548                     }
2549                 }
2550             }
2551             data = data.substr(0, data.length - 1);
2552             return data;
2553         },
2554
2555         headers:{},
2556
2557         hasHeaders:false,
2558
2559         useDefaultHeader:true,
2560
2561         defaultPostHeader:'application/x-www-form-urlencoded',
2562
2563         useDefaultXhrHeader:true,
2564
2565         defaultXhrHeader:'XMLHttpRequest',
2566
2567         hasDefaultHeaders:true,
2568
2569         defaultHeaders:{},
2570
2571         poll:{},
2572
2573         timeout:{},
2574
2575         pollInterval:50,
2576
2577         transactionId:0,
2578
2579         setProgId:function(id)
2580         {
2581             this.activeX.unshift(id);
2582         },
2583
2584         setDefaultPostHeader:function(b)
2585         {
2586             this.useDefaultHeader = b;
2587         },
2588
2589         setDefaultXhrHeader:function(b)
2590         {
2591             this.useDefaultXhrHeader = b;
2592         },
2593
2594         setPollingInterval:function(i)
2595         {
2596             if (typeof i == 'number' && isFinite(i)) {
2597                 this.pollInterval = i;
2598             }
2599         },
2600
2601         createXhrObject:function(transactionId)
2602         {
2603             var obj,http;
2604             try
2605             {
2606
2607                 http = new XMLHttpRequest();
2608
2609                 obj = { conn:http, tId:transactionId };
2610             }
2611             catch(e)
2612             {
2613                 for (var i = 0; i < this.activeX.length; ++i) {
2614                     try
2615                     {
2616
2617                         http = new ActiveXObject(this.activeX[i]);
2618
2619                         obj = { conn:http, tId:transactionId };
2620                         break;
2621                     }
2622                     catch(e) {
2623                     }
2624                 }
2625             }
2626             finally
2627             {
2628                 return obj;
2629             }
2630         },
2631
2632         getConnectionObject:function()
2633         {
2634             var o;
2635             var tId = this.transactionId;
2636
2637             try
2638             {
2639                 o = this.createXhrObject(tId);
2640                 if (o) {
2641                     this.transactionId++;
2642                 }
2643             }
2644             catch(e) {
2645             }
2646             finally
2647             {
2648                 return o;
2649             }
2650         },
2651
2652         asyncRequest:function(method, uri, callback, postData)
2653         {
2654             var o = this.getConnectionObject();
2655
2656             if (!o) {
2657                 return null;
2658             }
2659             else {
2660                 o.conn.open(method, uri, true);
2661
2662                 if (this.useDefaultXhrHeader) {
2663                     if (!this.defaultHeaders['X-Requested-With']) {
2664                         this.initHeader('X-Requested-With', this.defaultXhrHeader, true);
2665                     }
2666                 }
2667
2668                 if(postData && this.useDefaultHeader){
2669                     this.initHeader('Content-Type', this.defaultPostHeader);
2670                 }
2671
2672                  if (this.hasDefaultHeaders || this.hasHeaders) {
2673                     this.setHeader(o);
2674                 }
2675
2676                 this.handleReadyState(o, callback);
2677                 o.conn.send(postData || null);
2678
2679                 return o;
2680             }
2681         },
2682
2683         handleReadyState:function(o, callback)
2684         {
2685             var oConn = this;
2686
2687             if (callback && callback.timeout) {
2688                 this.timeout[o.tId] = window.setTimeout(function() {
2689                     oConn.abort(o, callback, true);
2690                 }, callback.timeout);
2691             }
2692
2693             this.poll[o.tId] = window.setInterval(
2694                     function() {
2695                         if (o.conn && o.conn.readyState == 4) {
2696                             window.clearInterval(oConn.poll[o.tId]);
2697                             delete oConn.poll[o.tId];
2698
2699                             if(callback && callback.timeout) {
2700                                 window.clearTimeout(oConn.timeout[o.tId]);
2701                                 delete oConn.timeout[o.tId];
2702                             }
2703
2704                             oConn.handleTransactionResponse(o, callback);
2705                         }
2706                     }
2707                     , this.pollInterval);
2708         },
2709
2710         handleTransactionResponse:function(o, callback, isAbort)
2711         {
2712
2713             if (!callback) {
2714                 this.releaseObject(o);
2715                 return;
2716             }
2717
2718             var httpStatus, responseObject;
2719
2720             try
2721             {
2722                 if (o.conn.status !== undefined && o.conn.status != 0) {
2723                     httpStatus = o.conn.status;
2724                 }
2725                 else {
2726                     httpStatus = 13030;
2727                 }
2728             }
2729             catch(e) {
2730
2731
2732                 httpStatus = 13030;
2733             }
2734
2735             if (httpStatus >= 200 && httpStatus < 300) {
2736                 responseObject = this.createResponseObject(o, callback.argument);
2737                 if (callback.success) {
2738                     if (!callback.scope) {
2739                         callback.success(responseObject);
2740                     }
2741                     else {
2742
2743
2744                         callback.success.apply(callback.scope, [responseObject]);
2745                     }
2746                 }
2747             }
2748             else {
2749                 switch (httpStatus) {
2750
2751                     case 12002:
2752                     case 12029:
2753                     case 12030:
2754                     case 12031:
2755                     case 12152:
2756                     case 13030:
2757                         responseObject = this.createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false));
2758                         if (callback.failure) {
2759                             if (!callback.scope) {
2760                                 callback.failure(responseObject);
2761                             }
2762                             else {
2763                                 callback.failure.apply(callback.scope, [responseObject]);
2764                             }
2765                         }
2766                         break;
2767                     default:
2768                         responseObject = this.createResponseObject(o, callback.argument);
2769                         if (callback.failure) {
2770                             if (!callback.scope) {
2771                                 callback.failure(responseObject);
2772                             }
2773                             else {
2774                                 callback.failure.apply(callback.scope, [responseObject]);
2775                             }
2776                         }
2777                 }
2778             }
2779
2780             this.releaseObject(o);
2781             responseObject = null;
2782         },
2783
2784         createResponseObject:function(o, callbackArg)
2785         {
2786             var obj = {};
2787             var headerObj = {};
2788
2789             try
2790             {
2791                 var headerStr = o.conn.getAllResponseHeaders();
2792                 var header = headerStr.split('\n');
2793                 for (var i = 0; i < header.length; i++) {
2794                     var delimitPos = header[i].indexOf(':');
2795                     if (delimitPos != -1) {
2796                         headerObj[header[i].substring(0, delimitPos)] = header[i].substring(delimitPos + 2);
2797                     }
2798                 }
2799             }
2800             catch(e) {
2801             }
2802
2803             obj.tId = o.tId;
2804             obj.status = o.conn.status;
2805             obj.statusText = o.conn.statusText;
2806             obj.getResponseHeader = headerObj;
2807             obj.getAllResponseHeaders = headerStr;
2808             obj.responseText = o.conn.responseText;
2809             obj.responseXML = o.conn.responseXML;
2810
2811             if (typeof callbackArg !== undefined) {
2812                 obj.argument = callbackArg;
2813             }
2814
2815             return obj;
2816         },
2817
2818         createExceptionObject:function(tId, callbackArg, isAbort)
2819         {
2820             var COMM_CODE = 0;
2821             var COMM_ERROR = 'communication failure';
2822             var ABORT_CODE = -1;
2823             var ABORT_ERROR = 'transaction aborted';
2824
2825             var obj = {};
2826
2827             obj.tId = tId;
2828             if (isAbort) {
2829                 obj.status = ABORT_CODE;
2830                 obj.statusText = ABORT_ERROR;
2831             }
2832             else {
2833                 obj.status = COMM_CODE;
2834                 obj.statusText = COMM_ERROR;
2835             }
2836
2837             if (callbackArg) {
2838                 obj.argument = callbackArg;
2839             }
2840
2841             return obj;
2842         },
2843
2844         initHeader:function(label, value, isDefault)
2845         {
2846             var headerObj = (isDefault) ? this.defaultHeaders : this.headers;
2847
2848             if (headerObj[label] === undefined) {
2849                 headerObj[label] = value;
2850             }
2851             else {
2852
2853
2854                 headerObj[label] = value + "," + headerObj[label];
2855             }
2856
2857             if (isDefault) {
2858                 this.hasDefaultHeaders = true;
2859             }
2860             else {
2861                 this.hasHeaders = true;
2862             }
2863         },
2864
2865
2866         setHeader:function(o)
2867         {
2868             if (this.hasDefaultHeaders) {
2869                 for (var prop in this.defaultHeaders) {
2870                     if (this.defaultHeaders.hasOwnProperty(prop)) {
2871                         o.conn.setRequestHeader(prop, this.defaultHeaders[prop]);
2872                     }
2873                 }
2874             }
2875
2876             if (this.hasHeaders) {
2877                 for (var prop in this.headers) {
2878                     if (this.headers.hasOwnProperty(prop)) {
2879                         o.conn.setRequestHeader(prop, this.headers[prop]);
2880                     }
2881                 }
2882                 this.headers = {};
2883                 this.hasHeaders = false;
2884             }
2885         },
2886
2887         resetDefaultHeaders:function() {
2888             delete this.defaultHeaders;
2889             this.defaultHeaders = {};
2890             this.hasDefaultHeaders = false;
2891         },
2892
2893         abort:function(o, callback, isTimeout)
2894         {
2895             if(this.isCallInProgress(o)) {
2896                 o.conn.abort();
2897                 window.clearInterval(this.poll[o.tId]);
2898                 delete this.poll[o.tId];
2899                 if (isTimeout) {
2900                     delete this.timeout[o.tId];
2901                 }
2902
2903                 this.handleTransactionResponse(o, callback, true);
2904
2905                 return true;
2906             }
2907             else {
2908                 return false;
2909             }
2910         },
2911
2912
2913         isCallInProgress:function(o)
2914         {
2915             if (o && o.conn) {
2916                 return o.conn.readyState != 4 && o.conn.readyState != 0;
2917             }
2918             else {
2919
2920                 return false;
2921             }
2922         },
2923
2924
2925         releaseObject:function(o)
2926         {
2927
2928             o.conn = null;
2929
2930             o = null;
2931         },
2932
2933         activeX:[
2934         'MSXML2.XMLHTTP.3.0',
2935         'MSXML2.XMLHTTP',
2936         'Microsoft.XMLHTTP'
2937         ]
2938
2939
2940     };
2941 })();/*
2942  * Portions of this file are based on pieces of Yahoo User Interface Library
2943  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2944  * YUI licensed under the BSD License:
2945  * http://developer.yahoo.net/yui/license.txt
2946  * <script type="text/javascript">
2947  *
2948  */
2949
2950 Roo.lib.Region = function(t, r, b, l) {
2951     this.top = t;
2952     this[1] = t;
2953     this.right = r;
2954     this.bottom = b;
2955     this.left = l;
2956     this[0] = l;
2957 };
2958
2959
2960 Roo.lib.Region.prototype = {
2961     contains : function(region) {
2962         return ( region.left >= this.left &&
2963                  region.right <= this.right &&
2964                  region.top >= this.top &&
2965                  region.bottom <= this.bottom    );
2966
2967     },
2968
2969     getArea : function() {
2970         return ( (this.bottom - this.top) * (this.right - this.left) );
2971     },
2972
2973     intersect : function(region) {
2974         var t = Math.max(this.top, region.top);
2975         var r = Math.min(this.right, region.right);
2976         var b = Math.min(this.bottom, region.bottom);
2977         var l = Math.max(this.left, region.left);
2978
2979         if (b >= t && r >= l) {
2980             return new Roo.lib.Region(t, r, b, l);
2981         } else {
2982             return null;
2983         }
2984     },
2985     union : function(region) {
2986         var t = Math.min(this.top, region.top);
2987         var r = Math.max(this.right, region.right);
2988         var b = Math.max(this.bottom, region.bottom);
2989         var l = Math.min(this.left, region.left);
2990
2991         return new Roo.lib.Region(t, r, b, l);
2992     },
2993
2994     adjust : function(t, l, b, r) {
2995         this.top += t;
2996         this.left += l;
2997         this.right += r;
2998         this.bottom += b;
2999         return this;
3000     }
3001 };
3002
3003 Roo.lib.Region.getRegion = function(el) {
3004     var p = Roo.lib.Dom.getXY(el);
3005
3006     var t = p[1];
3007     var r = p[0] + el.offsetWidth;
3008     var b = p[1] + el.offsetHeight;
3009     var l = p[0];
3010
3011     return new Roo.lib.Region(t, r, b, l);
3012 };
3013 /*
3014  * Portions of this file are based on pieces of Yahoo User Interface Library
3015  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3016  * YUI licensed under the BSD License:
3017  * http://developer.yahoo.net/yui/license.txt
3018  * <script type="text/javascript">
3019  *
3020  */
3021 //@@dep Roo.lib.Region
3022
3023
3024 Roo.lib.Point = function(x, y) {
3025     if (x instanceof Array) {
3026         y = x[1];
3027         x = x[0];
3028     }
3029     this.x = this.right = this.left = this[0] = x;
3030     this.y = this.top = this.bottom = this[1] = y;
3031 };
3032
3033 Roo.lib.Point.prototype = new Roo.lib.Region();
3034 /*
3035  * Portions of this file are based on pieces of Yahoo User Interface Library
3036  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3037  * YUI licensed under the BSD License:
3038  * http://developer.yahoo.net/yui/license.txt
3039  * <script type="text/javascript">
3040  *
3041  */
3042  
3043 (function() {   
3044
3045     Roo.lib.Anim = {
3046         scroll : function(el, args, duration, easing, cb, scope) {
3047             this.run(el, args, duration, easing, cb, scope, Roo.lib.Scroll);
3048         },
3049
3050         motion : function(el, args, duration, easing, cb, scope) {
3051             this.run(el, args, duration, easing, cb, scope, Roo.lib.Motion);
3052         },
3053
3054         color : function(el, args, duration, easing, cb, scope) {
3055             this.run(el, args, duration, easing, cb, scope, Roo.lib.ColorAnim);
3056         },
3057
3058         run : function(el, args, duration, easing, cb, scope, type) {
3059             type = type || Roo.lib.AnimBase;
3060             if (typeof easing == "string") {
3061                 easing = Roo.lib.Easing[easing];
3062             }
3063             var anim = new type(el, args, duration, easing);
3064             anim.animateX(function() {
3065                 Roo.callback(cb, scope);
3066             });
3067             return anim;
3068         }
3069     };
3070 })();/*
3071  * Portions of this file are based on pieces of Yahoo User Interface Library
3072  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3073  * YUI licensed under the BSD License:
3074  * http://developer.yahoo.net/yui/license.txt
3075  * <script type="text/javascript">
3076  *
3077  */
3078
3079 (function() {    
3080     var libFlyweight;
3081     
3082     function fly(el) {
3083         if (!libFlyweight) {
3084             libFlyweight = new Roo.Element.Flyweight();
3085         }
3086         libFlyweight.dom = el;
3087         return libFlyweight;
3088     }
3089
3090     // since this uses fly! - it cant be in DOM (which does not have fly yet..)
3091     
3092    
3093     
3094     Roo.lib.AnimBase = function(el, attributes, duration, method) {
3095         if (el) {
3096             this.init(el, attributes, duration, method);
3097         }
3098     };
3099
3100     Roo.lib.AnimBase.fly = fly;
3101     
3102     
3103     
3104     Roo.lib.AnimBase.prototype = {
3105
3106         toString: function() {
3107             var el = this.getEl();
3108             var id = el.id || el.tagName;
3109             return ("Anim " + id);
3110         },
3111
3112         patterns: {
3113             noNegatives:        /width|height|opacity|padding/i,
3114             offsetAttribute:  /^((width|height)|(top|left))$/,
3115             defaultUnit:        /width|height|top$|bottom$|left$|right$/i,
3116             offsetUnit:         /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i
3117         },
3118
3119
3120         doMethod: function(attr, start, end) {
3121             return this.method(this.currentFrame, start, end - start, this.totalFrames);
3122         },
3123
3124
3125         setAttribute: function(attr, val, unit) {
3126             if (this.patterns.noNegatives.test(attr)) {
3127                 val = (val > 0) ? val : 0;
3128             }
3129
3130             Roo.fly(this.getEl(), '_anim').setStyle(attr, val + unit);
3131         },
3132
3133
3134         getAttribute: function(attr) {
3135             var el = this.getEl();
3136             var val = fly(el).getStyle(attr);
3137
3138             if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) {
3139                 return parseFloat(val);
3140             }
3141
3142             var a = this.patterns.offsetAttribute.exec(attr) || [];
3143             var pos = !!( a[3] );
3144             var box = !!( a[2] );
3145
3146
3147             if (box || (fly(el).getStyle('position') == 'absolute' && pos)) {
3148                 val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)];
3149             } else {
3150                 val = 0;
3151             }
3152
3153             return val;
3154         },
3155
3156
3157         getDefaultUnit: function(attr) {
3158             if (this.patterns.defaultUnit.test(attr)) {
3159                 return 'px';
3160             }
3161
3162             return '';
3163         },
3164
3165         animateX : function(callback, scope) {
3166             var f = function() {
3167                 this.onComplete.removeListener(f);
3168                 if (typeof callback == "function") {
3169                     callback.call(scope || this, this);
3170                 }
3171             };
3172             this.onComplete.addListener(f, this);
3173             this.animate();
3174         },
3175
3176
3177         setRuntimeAttribute: function(attr) {
3178             var start;
3179             var end;
3180             var attributes = this.attributes;
3181
3182             this.runtimeAttributes[attr] = {};
3183
3184             var isset = function(prop) {
3185                 return (typeof prop !== 'undefined');
3186             };
3187
3188             if (!isset(attributes[attr]['to']) && !isset(attributes[attr]['by'])) {
3189                 return false;
3190             }
3191
3192             start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr);
3193
3194
3195             if (isset(attributes[attr]['to'])) {
3196                 end = attributes[attr]['to'];
3197             } else if (isset(attributes[attr]['by'])) {
3198                 if (start.constructor == Array) {
3199                     end = [];
3200                     for (var i = 0, len = start.length; i < len; ++i) {
3201                         end[i] = start[i] + attributes[attr]['by'][i];
3202                     }
3203                 } else {
3204                     end = start + attributes[attr]['by'];
3205                 }
3206             }
3207
3208             this.runtimeAttributes[attr].start = start;
3209             this.runtimeAttributes[attr].end = end;
3210
3211
3212             this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr);
3213         },
3214
3215
3216         init: function(el, attributes, duration, method) {
3217
3218             var isAnimated = false;
3219
3220
3221             var startTime = null;
3222
3223
3224             var actualFrames = 0;
3225
3226
3227             el = Roo.getDom(el);
3228
3229
3230             this.attributes = attributes || {};
3231
3232
3233             this.duration = duration || 1;
3234
3235
3236             this.method = method || Roo.lib.Easing.easeNone;
3237
3238
3239             this.useSeconds = true;
3240
3241
3242             this.currentFrame = 0;
3243
3244
3245             this.totalFrames = Roo.lib.AnimMgr.fps;
3246
3247
3248             this.getEl = function() {
3249                 return el;
3250             };
3251
3252
3253             this.isAnimated = function() {
3254                 return isAnimated;
3255             };
3256
3257
3258             this.getStartTime = function() {
3259                 return startTime;
3260             };
3261
3262             this.runtimeAttributes = {};
3263
3264
3265             this.animate = function() {
3266                 if (this.isAnimated()) {
3267                     return false;
3268                 }
3269
3270                 this.currentFrame = 0;
3271
3272                 this.totalFrames = ( this.useSeconds ) ? Math.ceil(Roo.lib.AnimMgr.fps * this.duration) : this.duration;
3273
3274                 Roo.lib.AnimMgr.registerElement(this);
3275             };
3276
3277
3278             this.stop = function(finish) {
3279                 if (finish) {
3280                     this.currentFrame = this.totalFrames;
3281                     this._onTween.fire();
3282                 }
3283                 Roo.lib.AnimMgr.stop(this);
3284             };
3285
3286             var onStart = function() {
3287                 this.onStart.fire();
3288
3289                 this.runtimeAttributes = {};
3290                 for (var attr in this.attributes) {
3291                     this.setRuntimeAttribute(attr);
3292                 }
3293
3294                 isAnimated = true;
3295                 actualFrames = 0;
3296                 startTime = new Date();
3297             };
3298
3299
3300             var onTween = function() {
3301                 var data = {
3302                     duration: new Date() - this.getStartTime(),
3303                     currentFrame: this.currentFrame
3304                 };
3305
3306                 data.toString = function() {
3307                     return (
3308                             'duration: ' + data.duration +
3309                             ', currentFrame: ' + data.currentFrame
3310                             );
3311                 };
3312
3313                 this.onTween.fire(data);
3314
3315                 var runtimeAttributes = this.runtimeAttributes;
3316
3317                 for (var attr in runtimeAttributes) {
3318                     this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit);
3319                 }
3320
3321                 actualFrames += 1;
3322             };
3323
3324             var onComplete = function() {
3325                 var actual_duration = (new Date() - startTime) / 1000 ;
3326
3327                 var data = {
3328                     duration: actual_duration,
3329                     frames: actualFrames,
3330                     fps: actualFrames / actual_duration
3331                 };
3332
3333                 data.toString = function() {
3334                     return (
3335                             'duration: ' + data.duration +
3336                             ', frames: ' + data.frames +
3337                             ', fps: ' + data.fps
3338                             );
3339                 };
3340
3341                 isAnimated = false;
3342                 actualFrames = 0;
3343                 this.onComplete.fire(data);
3344             };
3345
3346
3347             this._onStart = new Roo.util.Event(this);
3348             this.onStart = new Roo.util.Event(this);
3349             this.onTween = new Roo.util.Event(this);
3350             this._onTween = new Roo.util.Event(this);
3351             this.onComplete = new Roo.util.Event(this);
3352             this._onComplete = new Roo.util.Event(this);
3353             this._onStart.addListener(onStart);
3354             this._onTween.addListener(onTween);
3355             this._onComplete.addListener(onComplete);
3356         }
3357     };
3358 })();
3359 /*
3360  * Portions of this file are based on pieces of Yahoo User Interface Library
3361  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3362  * YUI licensed under the BSD License:
3363  * http://developer.yahoo.net/yui/license.txt
3364  * <script type="text/javascript">
3365  *
3366  */
3367
3368 Roo.lib.AnimMgr = new function() {
3369
3370         var thread = null;
3371
3372
3373         var queue = [];
3374
3375
3376         var tweenCount = 0;
3377
3378
3379         this.fps = 1000;
3380
3381
3382         this.delay = 1;
3383
3384
3385         this.registerElement = function(tween) {
3386             queue[queue.length] = tween;
3387             tweenCount += 1;
3388             tween._onStart.fire();
3389             this.start();
3390         };
3391
3392
3393         this.unRegister = function(tween, index) {
3394             tween._onComplete.fire();
3395             index = index || getIndex(tween);
3396             if (index != -1) {
3397                 queue.splice(index, 1);
3398             }
3399
3400             tweenCount -= 1;
3401             if (tweenCount <= 0) {
3402                 this.stop();
3403             }
3404         };
3405
3406
3407         this.start = function() {
3408             if (thread === null) {
3409                 thread = setInterval(this.run, this.delay);
3410             }
3411         };
3412
3413
3414         this.stop = function(tween) {
3415             if (!tween) {
3416                 clearInterval(thread);
3417
3418                 for (var i = 0, len = queue.length; i < len; ++i) {
3419                     if (queue[0].isAnimated()) {
3420                         this.unRegister(queue[0], 0);
3421                     }
3422                 }
3423
3424                 queue = [];
3425                 thread = null;
3426                 tweenCount = 0;
3427             }
3428             else {
3429                 this.unRegister(tween);
3430             }
3431         };
3432
3433
3434         this.run = function() {
3435             for (var i = 0, len = queue.length; i < len; ++i) {
3436                 var tween = queue[i];
3437                 if (!tween || !tween.isAnimated()) {
3438                     continue;
3439                 }
3440
3441                 if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null)
3442                 {
3443                     tween.currentFrame += 1;
3444
3445                     if (tween.useSeconds) {
3446                         correctFrame(tween);
3447                     }
3448                     tween._onTween.fire();
3449                 }
3450                 else {
3451                     Roo.lib.AnimMgr.stop(tween, i);
3452                 }
3453             }
3454         };
3455
3456         var getIndex = function(anim) {
3457             for (var i = 0, len = queue.length; i < len; ++i) {
3458                 if (queue[i] == anim) {
3459                     return i;
3460                 }
3461             }
3462             return -1;
3463         };
3464
3465
3466         var correctFrame = function(tween) {
3467             var frames = tween.totalFrames;
3468             var frame = tween.currentFrame;
3469             var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames);
3470             var elapsed = (new Date() - tween.getStartTime());
3471             var tweak = 0;
3472
3473             if (elapsed < tween.duration * 1000) {
3474                 tweak = Math.round((elapsed / expected - 1) * tween.currentFrame);
3475             } else {
3476                 tweak = frames - (frame + 1);
3477             }
3478             if (tweak > 0 && isFinite(tweak)) {
3479                 if (tween.currentFrame + tweak >= frames) {
3480                     tweak = frames - (frame + 1);
3481                 }
3482
3483                 tween.currentFrame += tweak;
3484             }
3485         };
3486     };/*
3487  * Portions of this file are based on pieces of Yahoo User Interface Library
3488  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3489  * YUI licensed under the BSD License:
3490  * http://developer.yahoo.net/yui/license.txt
3491  * <script type="text/javascript">
3492  *
3493  */
3494 Roo.lib.Bezier = new function() {
3495
3496         this.getPosition = function(points, t) {
3497             var n = points.length;
3498             var tmp = [];
3499
3500             for (var i = 0; i < n; ++i) {
3501                 tmp[i] = [points[i][0], points[i][1]];
3502             }
3503
3504             for (var j = 1; j < n; ++j) {
3505                 for (i = 0; i < n - j; ++i) {
3506                     tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
3507                     tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
3508                 }
3509             }
3510
3511             return [ tmp[0][0], tmp[0][1] ];
3512
3513         };
3514     };/*
3515  * Portions of this file are based on pieces of Yahoo User Interface Library
3516  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3517  * YUI licensed under the BSD License:
3518  * http://developer.yahoo.net/yui/license.txt
3519  * <script type="text/javascript">
3520  *
3521  */
3522 (function() {
3523
3524     Roo.lib.ColorAnim = function(el, attributes, duration, method) {
3525         Roo.lib.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method);
3526     };
3527
3528     Roo.extend(Roo.lib.ColorAnim, Roo.lib.AnimBase);
3529
3530     var fly = Roo.lib.AnimBase.fly;
3531     var Y = Roo.lib;
3532     var superclass = Y.ColorAnim.superclass;
3533     var proto = Y.ColorAnim.prototype;
3534
3535     proto.toString = function() {
3536         var el = this.getEl();
3537         var id = el.id || el.tagName;
3538         return ("ColorAnim " + id);
3539     };
3540
3541     proto.patterns.color = /color$/i;
3542     proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;
3543     proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;
3544     proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;
3545     proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/;
3546
3547
3548     proto.parseColor = function(s) {
3549         if (s.length == 3) {
3550             return s;
3551         }
3552
3553         var c = this.patterns.hex.exec(s);
3554         if (c && c.length == 4) {
3555             return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ];
3556         }
3557
3558         c = this.patterns.rgb.exec(s);
3559         if (c && c.length == 4) {
3560             return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ];
3561         }
3562
3563         c = this.patterns.hex3.exec(s);
3564         if (c && c.length == 4) {
3565             return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ];
3566         }
3567
3568         return null;
3569     };
3570     // since this uses fly! - it cant be in ColorAnim (which does not have fly yet..)
3571     proto.getAttribute = function(attr) {
3572         var el = this.getEl();
3573         if (this.patterns.color.test(attr)) {
3574             var val = fly(el).getStyle(attr);
3575
3576             if (this.patterns.transparent.test(val)) {
3577                 var parent = el.parentNode;
3578                 val = fly(parent).getStyle(attr);
3579
3580                 while (parent && this.patterns.transparent.test(val)) {
3581                     parent = parent.parentNode;
3582                     val = fly(parent).getStyle(attr);
3583                     if (parent.tagName.toUpperCase() == 'HTML') {
3584                         val = '#fff';
3585                     }
3586                 }
3587             }
3588         } else {
3589             val = superclass.getAttribute.call(this, attr);
3590         }
3591
3592         return val;
3593     };
3594     proto.getAttribute = function(attr) {
3595         var el = this.getEl();
3596         if (this.patterns.color.test(attr)) {
3597             var val = fly(el).getStyle(attr);
3598
3599             if (this.patterns.transparent.test(val)) {
3600                 var parent = el.parentNode;
3601                 val = fly(parent).getStyle(attr);
3602
3603                 while (parent && this.patterns.transparent.test(val)) {
3604                     parent = parent.parentNode;
3605                     val = fly(parent).getStyle(attr);
3606                     if (parent.tagName.toUpperCase() == 'HTML') {
3607                         val = '#fff';
3608                     }
3609                 }
3610             }
3611         } else {
3612             val = superclass.getAttribute.call(this, attr);
3613         }
3614
3615         return val;
3616     };
3617
3618     proto.doMethod = function(attr, start, end) {
3619         var val;
3620
3621         if (this.patterns.color.test(attr)) {
3622             val = [];
3623             for (var i = 0, len = start.length; i < len; ++i) {
3624                 val[i] = superclass.doMethod.call(this, attr, start[i], end[i]);
3625             }
3626
3627             val = 'rgb(' + Math.floor(val[0]) + ',' + Math.floor(val[1]) + ',' + Math.floor(val[2]) + ')';
3628         }
3629         else {
3630             val = superclass.doMethod.call(this, attr, start, end);
3631         }
3632
3633         return val;
3634     };
3635
3636     proto.setRuntimeAttribute = function(attr) {
3637         superclass.setRuntimeAttribute.call(this, attr);
3638
3639         if (this.patterns.color.test(attr)) {
3640             var attributes = this.attributes;
3641             var start = this.parseColor(this.runtimeAttributes[attr].start);
3642             var end = this.parseColor(this.runtimeAttributes[attr].end);
3643
3644             if (typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined') {
3645                 end = this.parseColor(attributes[attr].by);
3646
3647                 for (var i = 0, len = start.length; i < len; ++i) {
3648                     end[i] = start[i] + end[i];
3649                 }
3650             }
3651
3652             this.runtimeAttributes[attr].start = start;
3653             this.runtimeAttributes[attr].end = end;
3654         }
3655     };
3656 })();
3657
3658 /*
3659  * Portions of this file are based on pieces of Yahoo User Interface Library
3660  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3661  * YUI licensed under the BSD License:
3662  * http://developer.yahoo.net/yui/license.txt
3663  * <script type="text/javascript">
3664  *
3665  */
3666 Roo.lib.Easing = {
3667
3668
3669     easeNone: function (t, b, c, d) {
3670         return c * t / d + b;
3671     },
3672
3673
3674     easeIn: function (t, b, c, d) {
3675         return c * (t /= d) * t + b;
3676     },
3677
3678
3679     easeOut: function (t, b, c, d) {
3680         return -c * (t /= d) * (t - 2) + b;
3681     },
3682
3683
3684     easeBoth: function (t, b, c, d) {
3685         if ((t /= d / 2) < 1) {
3686             return c / 2 * t * t + b;
3687         }
3688
3689         return -c / 2 * ((--t) * (t - 2) - 1) + b;
3690     },
3691
3692
3693     easeInStrong: function (t, b, c, d) {
3694         return c * (t /= d) * t * t * t + b;
3695     },
3696
3697
3698     easeOutStrong: function (t, b, c, d) {
3699         return -c * ((t = t / d - 1) * t * t * t - 1) + b;
3700     },
3701
3702
3703     easeBothStrong: function (t, b, c, d) {
3704         if ((t /= d / 2) < 1) {
3705             return c / 2 * t * t * t * t + b;
3706         }
3707
3708         return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
3709     },
3710
3711
3712
3713     elasticIn: function (t, b, c, d, a, p) {
3714         if (t == 0) {
3715             return b;
3716         }
3717         if ((t /= d) == 1) {
3718             return b + c;
3719         }
3720         if (!p) {
3721             p = d * .3;
3722         }
3723
3724         if (!a || a < Math.abs(c)) {
3725             a = c;
3726             var s = p / 4;
3727         }
3728         else {
3729             var s = p / (2 * Math.PI) * Math.asin(c / a);
3730         }
3731
3732         return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
3733     },
3734
3735
3736     elasticOut: function (t, b, c, d, a, p) {
3737         if (t == 0) {
3738             return b;
3739         }
3740         if ((t /= d) == 1) {
3741             return b + c;
3742         }
3743         if (!p) {
3744             p = d * .3;
3745         }
3746
3747         if (!a || a < Math.abs(c)) {
3748             a = c;
3749             var s = p / 4;
3750         }
3751         else {
3752             var s = p / (2 * Math.PI) * Math.asin(c / a);
3753         }
3754
3755         return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
3756     },
3757
3758
3759     elasticBoth: function (t, b, c, d, a, p) {
3760         if (t == 0) {
3761             return b;
3762         }
3763
3764         if ((t /= d / 2) == 2) {
3765             return b + c;
3766         }
3767
3768         if (!p) {
3769             p = d * (.3 * 1.5);
3770         }
3771
3772         if (!a || a < Math.abs(c)) {
3773             a = c;
3774             var s = p / 4;
3775         }
3776         else {
3777             var s = p / (2 * Math.PI) * Math.asin(c / a);
3778         }
3779
3780         if (t < 1) {
3781             return -.5 * (a * Math.pow(2, 10 * (t -= 1)) *
3782                           Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
3783         }
3784         return a * Math.pow(2, -10 * (t -= 1)) *
3785                Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
3786     },
3787
3788
3789
3790     backIn: function (t, b, c, d, s) {
3791         if (typeof s == 'undefined') {
3792             s = 1.70158;
3793         }
3794         return c * (t /= d) * t * ((s + 1) * t - s) + b;
3795     },
3796
3797
3798     backOut: function (t, b, c, d, s) {
3799         if (typeof s == 'undefined') {
3800             s = 1.70158;
3801         }
3802         return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
3803     },
3804
3805
3806     backBoth: function (t, b, c, d, s) {
3807         if (typeof s == 'undefined') {
3808             s = 1.70158;
3809         }
3810
3811         if ((t /= d / 2 ) < 1) {
3812             return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
3813         }
3814         return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
3815     },
3816
3817
3818     bounceIn: function (t, b, c, d) {
3819         return c - Roo.lib.Easing.bounceOut(d - t, 0, c, d) + b;
3820     },
3821
3822
3823     bounceOut: function (t, b, c, d) {
3824         if ((t /= d) < (1 / 2.75)) {
3825             return c * (7.5625 * t * t) + b;
3826         } else if (t < (2 / 2.75)) {
3827             return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
3828         } else if (t < (2.5 / 2.75)) {
3829             return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
3830         }
3831         return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
3832     },
3833
3834
3835     bounceBoth: function (t, b, c, d) {
3836         if (t < d / 2) {
3837             return Roo.lib.Easing.bounceIn(t * 2, 0, c, d) * .5 + b;
3838         }
3839         return Roo.lib.Easing.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
3840     }
3841 };/*
3842  * Portions of this file are based on pieces of Yahoo User Interface Library
3843  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3844  * YUI licensed under the BSD License:
3845  * http://developer.yahoo.net/yui/license.txt
3846  * <script type="text/javascript">
3847  *
3848  */
3849     (function() {
3850         Roo.lib.Motion = function(el, attributes, duration, method) {
3851             if (el) {
3852                 Roo.lib.Motion.superclass.constructor.call(this, el, attributes, duration, method);
3853             }
3854         };
3855
3856         Roo.extend(Roo.lib.Motion, Roo.lib.ColorAnim);
3857
3858
3859         var Y = Roo.lib;
3860         var superclass = Y.Motion.superclass;
3861         var proto = Y.Motion.prototype;
3862
3863         proto.toString = function() {
3864             var el = this.getEl();
3865             var id = el.id || el.tagName;
3866             return ("Motion " + id);
3867         };
3868
3869         proto.patterns.points = /^points$/i;
3870
3871         proto.setAttribute = function(attr, val, unit) {
3872             if (this.patterns.points.test(attr)) {
3873                 unit = unit || 'px';
3874                 superclass.setAttribute.call(this, 'left', val[0], unit);
3875                 superclass.setAttribute.call(this, 'top', val[1], unit);
3876             } else {
3877                 superclass.setAttribute.call(this, attr, val, unit);
3878             }
3879         };
3880
3881         proto.getAttribute = function(attr) {
3882             if (this.patterns.points.test(attr)) {
3883                 var val = [
3884                         superclass.getAttribute.call(this, 'left'),
3885                         superclass.getAttribute.call(this, 'top')
3886                         ];
3887             } else {
3888                 val = superclass.getAttribute.call(this, attr);
3889             }
3890
3891             return val;
3892         };
3893
3894         proto.doMethod = function(attr, start, end) {
3895             var val = null;
3896
3897             if (this.patterns.points.test(attr)) {
3898                 var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100;
3899                 val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t);
3900             } else {
3901                 val = superclass.doMethod.call(this, attr, start, end);
3902             }
3903             return val;
3904         };
3905
3906         proto.setRuntimeAttribute = function(attr) {
3907             if (this.patterns.points.test(attr)) {
3908                 var el = this.getEl();
3909                 var attributes = this.attributes;
3910                 var start;
3911                 var control = attributes['points']['control'] || [];
3912                 var end;
3913                 var i, len;
3914
3915                 if (control.length > 0 && !(control[0] instanceof Array)) {
3916                     control = [control];
3917                 } else {
3918                     var tmp = [];
3919                     for (i = 0,len = control.length; i < len; ++i) {
3920                         tmp[i] = control[i];
3921                     }
3922                     control = tmp;
3923                 }
3924
3925                 Roo.fly(el).position();
3926
3927                 if (isset(attributes['points']['from'])) {
3928                     Roo.lib.Dom.setXY(el, attributes['points']['from']);
3929                 }
3930                 else {
3931                     Roo.lib.Dom.setXY(el, Roo.lib.Dom.getXY(el));
3932                 }
3933
3934                 start = this.getAttribute('points');
3935
3936
3937                 if (isset(attributes['points']['to'])) {
3938                     end = translateValues.call(this, attributes['points']['to'], start);
3939
3940                     var pageXY = Roo.lib.Dom.getXY(this.getEl());
3941                     for (i = 0,len = control.length; i < len; ++i) {
3942                         control[i] = translateValues.call(this, control[i], start);
3943                     }
3944
3945
3946                 } else if (isset(attributes['points']['by'])) {
3947                     end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ];
3948
3949                     for (i = 0,len = control.length; i < len; ++i) {
3950                         control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ];
3951                     }
3952                 }
3953
3954                 this.runtimeAttributes[attr] = [start];
3955
3956                 if (control.length > 0) {
3957                     this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control);
3958                 }
3959
3960                 this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end;
3961             }
3962             else {
3963                 superclass.setRuntimeAttribute.call(this, attr);
3964             }
3965         };
3966
3967         var translateValues = function(val, start) {
3968             var pageXY = Roo.lib.Dom.getXY(this.getEl());
3969             val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ];
3970
3971             return val;
3972         };
3973
3974         var isset = function(prop) {
3975             return (typeof prop !== 'undefined');
3976         };
3977     })();
3978 /*
3979  * Portions of this file are based on pieces of Yahoo User Interface Library
3980  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3981  * YUI licensed under the BSD License:
3982  * http://developer.yahoo.net/yui/license.txt
3983  * <script type="text/javascript">
3984  *
3985  */
3986     (function() {
3987         Roo.lib.Scroll = function(el, attributes, duration, method) {
3988             if (el) {
3989                 Roo.lib.Scroll.superclass.constructor.call(this, el, attributes, duration, method);
3990             }
3991         };
3992
3993         Roo.extend(Roo.lib.Scroll, Roo.lib.ColorAnim);
3994
3995
3996         var Y = Roo.lib;
3997         var superclass = Y.Scroll.superclass;
3998         var proto = Y.Scroll.prototype;
3999
4000         proto.toString = function() {
4001             var el = this.getEl();
4002             var id = el.id || el.tagName;
4003             return ("Scroll " + id);
4004         };
4005
4006         proto.doMethod = function(attr, start, end) {
4007             var val = null;
4008
4009             if (attr == 'scroll') {
4010                 val = [
4011                         this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames),
4012                         this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames)
4013                         ];
4014
4015             } else {
4016                 val = superclass.doMethod.call(this, attr, start, end);
4017             }
4018             return val;
4019         };
4020
4021         proto.getAttribute = function(attr) {
4022             var val = null;
4023             var el = this.getEl();
4024
4025             if (attr == 'scroll') {
4026                 val = [ el.scrollLeft, el.scrollTop ];
4027             } else {
4028                 val = superclass.getAttribute.call(this, attr);
4029             }
4030
4031             return val;
4032         };
4033
4034         proto.setAttribute = function(attr, val, unit) {
4035             var el = this.getEl();
4036
4037             if (attr == 'scroll') {
4038                 el.scrollLeft = val[0];
4039                 el.scrollTop = val[1];
4040             } else {
4041                 superclass.setAttribute.call(this, attr, val, unit);
4042             }
4043         };
4044     })();
4045 /*
4046  * Based on:
4047  * Ext JS Library 1.1.1
4048  * Copyright(c) 2006-2007, Ext JS, LLC.
4049  *
4050  * Originally Released Under LGPL - original licence link has changed is not relivant.
4051  *
4052  * Fork - LGPL
4053  * <script type="text/javascript">
4054  */
4055
4056
4057 // nasty IE9 hack - what a pile of crap that is..
4058
4059  if (typeof Range != "undefined" && typeof Range.prototype.createContextualFragment == "undefined") {
4060     Range.prototype.createContextualFragment = function (html) {
4061         var doc = window.document;
4062         var container = doc.createElement("div");
4063         container.innerHTML = html;
4064         var frag = doc.createDocumentFragment(), n;
4065         while ((n = container.firstChild)) {
4066             frag.appendChild(n);
4067         }
4068         return frag;
4069     };
4070 }
4071
4072 /**
4073  * @class Roo.DomHelper
4074  * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.
4075  * 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>.
4076  * @singleton
4077  */
4078 Roo.DomHelper = function(){
4079     var tempTableEl = null;
4080     var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
4081     var tableRe = /^table|tbody|tr|td$/i;
4082     var xmlns = {};
4083     // build as innerHTML where available
4084     /** @ignore */
4085     var createHtml = function(o){
4086         if(typeof o == 'string'){
4087             return o;
4088         }
4089         var b = "";
4090         if(!o.tag){
4091             o.tag = "div";
4092         }
4093         b += "<" + o.tag;
4094         for(var attr in o){
4095             if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") continue;
4096             if(attr == "style"){
4097                 var s = o["style"];
4098                 if(typeof s == "function"){
4099                     s = s.call();
4100                 }
4101                 if(typeof s == "string"){
4102                     b += ' style="' + s + '"';
4103                 }else if(typeof s == "object"){
4104                     b += ' style="';
4105                     for(var key in s){
4106                         if(typeof s[key] != "function"){
4107                             b += key + ":" + s[key] + ";";
4108                         }
4109                     }
4110                     b += '"';
4111                 }
4112             }else{
4113                 if(attr == "cls"){
4114                     b += ' class="' + o["cls"] + '"';
4115                 }else if(attr == "htmlFor"){
4116                     b += ' for="' + o["htmlFor"] + '"';
4117                 }else{
4118                     b += " " + attr + '="' + o[attr] + '"';
4119                 }
4120             }
4121         }
4122         if(emptyTags.test(o.tag)){
4123             b += "/>";
4124         }else{
4125             b += ">";
4126             var cn = o.children || o.cn;
4127             if(cn){
4128                 //http://bugs.kde.org/show_bug.cgi?id=71506
4129                 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4130                     for(var i = 0, len = cn.length; i < len; i++) {
4131                         b += createHtml(cn[i], b);
4132                     }
4133                 }else{
4134                     b += createHtml(cn, b);
4135                 }
4136             }
4137             if(o.html){
4138                 b += o.html;
4139             }
4140             b += "</" + o.tag + ">";
4141         }
4142         return b;
4143     };
4144
4145     // build as dom
4146     /** @ignore */
4147     var createDom = function(o, parentNode){
4148          
4149         // defininition craeted..
4150         var ns = false;
4151         if (o.ns && o.ns != 'html') {
4152                
4153             if (o.xmlns && typeof(xmlns[o.ns]) == 'undefined') {
4154                 xmlns[o.ns] = o.xmlns;
4155                 ns = o.xmlns;
4156             }
4157             if (typeof(xmlns[o.ns]) == 'undefined') {
4158                 console.log("Trying to create namespace element " + o.ns + ", however no xmlns was sent to builder previously");
4159             }
4160             ns = xmlns[o.ns];
4161         }
4162         
4163         
4164         if (typeof(o) == 'string') {
4165             return parentNode.appendChild(document.createTextNode(o));
4166         }
4167         o.tag = o.tag || div;
4168         if (o.ns && Roo.isIE) {
4169             ns = false;
4170             o.tag = o.ns + ':' + o.tag;
4171             
4172         }
4173         var el = ns ? document.createElementNS( ns, o.tag||'div') :  document.createElement(o.tag||'div');
4174         var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
4175         for(var attr in o){
4176             
4177             if(attr == "tag" || attr == "ns" ||attr == "xmlns" ||attr == "children" || attr == "cn" || attr == "html" || 
4178                     attr == "style" || typeof o[attr] == "function") continue;
4179                     
4180             if(attr=="cls" && Roo.isIE){
4181                 el.className = o["cls"];
4182             }else{
4183                 if(useSet) el.setAttribute(attr=="cls" ? 'class' : attr, o[attr]);
4184                 else el[attr] = o[attr];
4185             }
4186         }
4187         Roo.DomHelper.applyStyles(el, o.style);
4188         var cn = o.children || o.cn;
4189         if(cn){
4190             //http://bugs.kde.org/show_bug.cgi?id=71506
4191              if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4192                 for(var i = 0, len = cn.length; i < len; i++) {
4193                     createDom(cn[i], el);
4194                 }
4195             }else{
4196                 createDom(cn, el);
4197             }
4198         }
4199         if(o.html){
4200             el.innerHTML = o.html;
4201         }
4202         if(parentNode){
4203            parentNode.appendChild(el);
4204         }
4205         return el;
4206     };
4207
4208     var ieTable = function(depth, s, h, e){
4209         tempTableEl.innerHTML = [s, h, e].join('');
4210         var i = -1, el = tempTableEl;
4211         while(++i < depth){
4212             el = el.firstChild;
4213         }
4214         return el;
4215     };
4216
4217     // kill repeat to save bytes
4218     var ts = '<table>',
4219         te = '</table>',
4220         tbs = ts+'<tbody>',
4221         tbe = '</tbody>'+te,
4222         trs = tbs + '<tr>',
4223         tre = '</tr>'+tbe;
4224
4225     /**
4226      * @ignore
4227      * Nasty code for IE's broken table implementation
4228      */
4229     var insertIntoTable = function(tag, where, el, html){
4230         if(!tempTableEl){
4231             tempTableEl = document.createElement('div');
4232         }
4233         var node;
4234         var before = null;
4235         if(tag == 'td'){
4236             if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
4237                 return;
4238             }
4239             if(where == 'beforebegin'){
4240                 before = el;
4241                 el = el.parentNode;
4242             } else{
4243                 before = el.nextSibling;
4244                 el = el.parentNode;
4245             }
4246             node = ieTable(4, trs, html, tre);
4247         }
4248         else if(tag == 'tr'){
4249             if(where == 'beforebegin'){
4250                 before = el;
4251                 el = el.parentNode;
4252                 node = ieTable(3, tbs, html, tbe);
4253             } else if(where == 'afterend'){
4254                 before = el.nextSibling;
4255                 el = el.parentNode;
4256                 node = ieTable(3, tbs, html, tbe);
4257             } else{ // INTO a TR
4258                 if(where == 'afterbegin'){
4259                     before = el.firstChild;
4260                 }
4261                 node = ieTable(4, trs, html, tre);
4262             }
4263         } else if(tag == 'tbody'){
4264             if(where == 'beforebegin'){
4265                 before = el;
4266                 el = el.parentNode;
4267                 node = ieTable(2, ts, html, te);
4268             } else if(where == 'afterend'){
4269                 before = el.nextSibling;
4270                 el = el.parentNode;
4271                 node = ieTable(2, ts, html, te);
4272             } else{
4273                 if(where == 'afterbegin'){
4274                     before = el.firstChild;
4275                 }
4276                 node = ieTable(3, tbs, html, tbe);
4277             }
4278         } else{ // TABLE
4279             if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
4280                 return;
4281             }
4282             if(where == 'afterbegin'){
4283                 before = el.firstChild;
4284             }
4285             node = ieTable(2, ts, html, te);
4286         }
4287         el.insertBefore(node, before);
4288         return node;
4289     };
4290
4291     return {
4292     /** True to force the use of DOM instead of html fragments @type Boolean */
4293     useDom : false,
4294
4295     /**
4296      * Returns the markup for the passed Element(s) config
4297      * @param {Object} o The Dom object spec (and children)
4298      * @return {String}
4299      */
4300     markup : function(o){
4301         return createHtml(o);
4302     },
4303
4304     /**
4305      * Applies a style specification to an element
4306      * @param {String/HTMLElement} el The element to apply styles to
4307      * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
4308      * a function which returns such a specification.
4309      */
4310     applyStyles : function(el, styles){
4311         if(styles){
4312            el = Roo.fly(el);
4313            if(typeof styles == "string"){
4314                var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
4315                var matches;
4316                while ((matches = re.exec(styles)) != null){
4317                    el.setStyle(matches[1], matches[2]);
4318                }
4319            }else if (typeof styles == "object"){
4320                for (var style in styles){
4321                   el.setStyle(style, styles[style]);
4322                }
4323            }else if (typeof styles == "function"){
4324                 Roo.DomHelper.applyStyles(el, styles.call());
4325            }
4326         }
4327     },
4328
4329     /**
4330      * Inserts an HTML fragment into the Dom
4331      * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
4332      * @param {HTMLElement} el The context element
4333      * @param {String} html The HTML fragmenet
4334      * @return {HTMLElement} The new node
4335      */
4336     insertHtml : function(where, el, html){
4337         where = where.toLowerCase();
4338         if(el.insertAdjacentHTML){
4339             if(tableRe.test(el.tagName)){
4340                 var rs;
4341                 if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
4342                     return rs;
4343                 }
4344             }
4345             switch(where){
4346                 case "beforebegin":
4347                     el.insertAdjacentHTML('BeforeBegin', html);
4348                     return el.previousSibling;
4349                 case "afterbegin":
4350                     el.insertAdjacentHTML('AfterBegin', html);
4351                     return el.firstChild;
4352                 case "beforeend":
4353                     el.insertAdjacentHTML('BeforeEnd', html);
4354                     return el.lastChild;
4355                 case "afterend":
4356                     el.insertAdjacentHTML('AfterEnd', html);
4357                     return el.nextSibling;
4358             }
4359             throw 'Illegal insertion point -> "' + where + '"';
4360         }
4361         var range = el.ownerDocument.createRange();
4362         var frag;
4363         switch(where){
4364              case "beforebegin":
4365                 range.setStartBefore(el);
4366                 frag = range.createContextualFragment(html);
4367                 el.parentNode.insertBefore(frag, el);
4368                 return el.previousSibling;
4369              case "afterbegin":
4370                 if(el.firstChild){
4371                     range.setStartBefore(el.firstChild);
4372                     frag = range.createContextualFragment(html);
4373                     el.insertBefore(frag, el.firstChild);
4374                     return el.firstChild;
4375                 }else{
4376                     el.innerHTML = html;
4377                     return el.firstChild;
4378                 }
4379             case "beforeend":
4380                 if(el.lastChild){
4381                     range.setStartAfter(el.lastChild);
4382                     frag = range.createContextualFragment(html);
4383                     el.appendChild(frag);
4384                     return el.lastChild;
4385                 }else{
4386                     el.innerHTML = html;
4387                     return el.lastChild;
4388                 }
4389             case "afterend":
4390                 range.setStartAfter(el);
4391                 frag = range.createContextualFragment(html);
4392                 el.parentNode.insertBefore(frag, el.nextSibling);
4393                 return el.nextSibling;
4394             }
4395             throw 'Illegal insertion point -> "' + where + '"';
4396     },
4397
4398     /**
4399      * Creates new Dom element(s) and inserts them before el
4400      * @param {String/HTMLElement/Element} el The context element
4401      * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4402      * @param {Boolean} returnElement (optional) true to return a Roo.Element
4403      * @return {HTMLElement/Roo.Element} The new node
4404      */
4405     insertBefore : function(el, o, returnElement){
4406         return this.doInsert(el, o, returnElement, "beforeBegin");
4407     },
4408
4409     /**
4410      * Creates new Dom element(s) and inserts them after el
4411      * @param {String/HTMLElement/Element} el The context element
4412      * @param {Object} o The Dom object spec (and children)
4413      * @param {Boolean} returnElement (optional) true to return a Roo.Element
4414      * @return {HTMLElement/Roo.Element} The new node
4415      */
4416     insertAfter : function(el, o, returnElement){
4417         return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
4418     },
4419
4420     /**
4421      * Creates new Dom element(s) and inserts them as the first child of el
4422      * @param {String/HTMLElement/Element} el The context element
4423      * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4424      * @param {Boolean} returnElement (optional) true to return a Roo.Element
4425      * @return {HTMLElement/Roo.Element} The new node
4426      */
4427     insertFirst : function(el, o, returnElement){
4428         return this.doInsert(el, o, returnElement, "afterBegin");
4429     },
4430
4431     // private
4432     doInsert : function(el, o, returnElement, pos, sibling){
4433         el = Roo.getDom(el);
4434         var newNode;
4435         if(this.useDom || o.ns){
4436             newNode = createDom(o, null);
4437             el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
4438         }else{
4439             var html = createHtml(o);
4440             newNode = this.insertHtml(pos, el, html);
4441         }
4442         return returnElement ? Roo.get(newNode, true) : newNode;
4443     },
4444
4445     /**
4446      * Creates new Dom element(s) and appends them to el
4447      * @param {String/HTMLElement/Element} el The context element
4448      * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4449      * @param {Boolean} returnElement (optional) true to return a Roo.Element
4450      * @return {HTMLElement/Roo.Element} The new node
4451      */
4452     append : function(el, o, returnElement){
4453         el = Roo.getDom(el);
4454         var newNode;
4455         if(this.useDom || o.ns){
4456             newNode = createDom(o, null);
4457             el.appendChild(newNode);
4458         }else{
4459             var html = createHtml(o);
4460             newNode = this.insertHtml("beforeEnd", el, html);
4461         }
4462         return returnElement ? Roo.get(newNode, true) : newNode;
4463     },
4464
4465     /**
4466      * Creates new Dom element(s) and overwrites the contents of el with them
4467      * @param {String/HTMLElement/Element} el The context element
4468      * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4469      * @param {Boolean} returnElement (optional) true to return a Roo.Element
4470      * @return {HTMLElement/Roo.Element} The new node
4471      */
4472     overwrite : function(el, o, returnElement){
4473         el = Roo.getDom(el);
4474         if (o.ns) {
4475           
4476             while (el.childNodes.length) {
4477                 el.removeChild(el.firstChild);
4478             }
4479             createDom(o, el);
4480         } else {
4481             el.innerHTML = createHtml(o);   
4482         }
4483         
4484         return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
4485     },
4486
4487     /**
4488      * Creates a new Roo.DomHelper.Template from the Dom object spec
4489      * @param {Object} o The Dom object spec (and children)
4490      * @return {Roo.DomHelper.Template} The new template
4491      */
4492     createTemplate : function(o){
4493         var html = createHtml(o);
4494         return new Roo.Template(html);
4495     }
4496     };
4497 }();
4498 /*
4499  * Based on:
4500  * Ext JS Library 1.1.1
4501  * Copyright(c) 2006-2007, Ext JS, LLC.
4502  *
4503  * Originally Released Under LGPL - original licence link has changed is not relivant.
4504  *
4505  * Fork - LGPL
4506  * <script type="text/javascript">
4507  */
4508  
4509 /**
4510 * @class Roo.Template
4511 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
4512 * For a list of available format functions, see {@link Roo.util.Format}.<br />
4513 * Usage:
4514 <pre><code>
4515 var t = new Roo.Template({
4516     html :  '&lt;div name="{id}"&gt;' + 
4517         '&lt;span class="{cls}"&gt;{name:trim} {someval:this.myformat}{value:ellipsis(10)}&lt;/span&gt;' +
4518         '&lt;/div&gt;',
4519     myformat: function (value, allValues) {
4520         return 'XX' + value;
4521     }
4522 });
4523 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
4524 </code></pre>
4525 * 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>. 
4526 * @constructor
4527 * @param {Object} cfg - Configuration object.
4528 */
4529 Roo.Template = function(cfg){
4530     // BC!
4531     if(cfg instanceof Array){
4532         cfg = cfg.join("");
4533     }else if(arguments.length > 1){
4534         cfg = Array.prototype.join.call(arguments, "");
4535     }
4536     
4537     
4538     if (typeof(cfg) == 'object') {
4539         Roo.apply(this,cfg)
4540     } else {
4541         // bc
4542         this.html = cfg;
4543     }
4544     
4545     
4546 };
4547 Roo.Template.prototype = {
4548     
4549     /**
4550      * @cfg {String} html  The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
4551      */
4552     html : '',
4553     /**
4554      * Returns an HTML fragment of this template with the specified values applied.
4555      * @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'})
4556      * @return {String} The HTML fragment
4557      */
4558     applyTemplate : function(values){
4559         try {
4560             
4561             if(this.compiled){
4562                 return this.compiled(values);
4563             }
4564             var useF = this.disableFormats !== true;
4565             var fm = Roo.util.Format, tpl = this;
4566             var fn = function(m, name, format, args){
4567                 if(format && useF){
4568                     if(format.substr(0, 5) == "this."){
4569                         return tpl.call(format.substr(5), values[name], values);
4570                     }else{
4571                         if(args){
4572                             // quoted values are required for strings in compiled templates, 
4573                             // but for non compiled we need to strip them
4574                             // quoted reversed for jsmin
4575                             var re = /^\s*['"](.*)["']\s*$/;
4576                             args = args.split(',');
4577                             for(var i = 0, len = args.length; i < len; i++){
4578                                 args[i] = args[i].replace(re, "$1");
4579                             }
4580                             args = [values[name]].concat(args);
4581                         }else{
4582                             args = [values[name]];
4583                         }
4584                         return fm[format].apply(fm, args);
4585                     }
4586                 }else{
4587                     return values[name] !== undefined ? values[name] : "";
4588                 }
4589             };
4590             return this.html.replace(this.re, fn);
4591         } catch (e) {
4592             Roo.log(e);
4593             throw e;
4594         }
4595          
4596     },
4597     
4598     /**
4599      * Sets the HTML used as the template and optionally compiles it.
4600      * @param {String} html
4601      * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
4602      * @return {Roo.Template} this
4603      */
4604     set : function(html, compile){
4605         this.html = html;
4606         this.compiled = null;
4607         if(compile){
4608             this.compile();
4609         }
4610         return this;
4611     },
4612     
4613     /**
4614      * True to disable format functions (defaults to false)
4615      * @type Boolean
4616      */
4617     disableFormats : false,
4618     
4619     /**
4620     * The regular expression used to match template variables 
4621     * @type RegExp
4622     * @property 
4623     */
4624     re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
4625     
4626     /**
4627      * Compiles the template into an internal function, eliminating the RegEx overhead.
4628      * @return {Roo.Template} this
4629      */
4630     compile : function(){
4631         var fm = Roo.util.Format;
4632         var useF = this.disableFormats !== true;
4633         var sep = Roo.isGecko ? "+" : ",";
4634         var fn = function(m, name, format, args){
4635             if(format && useF){
4636                 args = args ? ',' + args : "";
4637                 if(format.substr(0, 5) != "this."){
4638                     format = "fm." + format + '(';
4639                 }else{
4640                     format = 'this.call("'+ format.substr(5) + '", ';
4641                     args = ", values";
4642                 }
4643             }else{
4644                 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
4645             }
4646             return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
4647         };
4648         var body;
4649         // branched to use + in gecko and [].join() in others
4650         if(Roo.isGecko){
4651             body = "this.compiled = function(values){ return '" +
4652                    this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
4653                     "';};";
4654         }else{
4655             body = ["this.compiled = function(values){ return ['"];
4656             body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
4657             body.push("'].join('');};");
4658             body = body.join('');
4659         }
4660         /**
4661          * eval:var:values
4662          * eval:var:fm
4663          */
4664         eval(body);
4665         return this;
4666     },
4667     
4668     // private function used to call members
4669     call : function(fnName, value, allValues){
4670         return this[fnName](value, allValues);
4671     },
4672     
4673     /**
4674      * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
4675      * @param {String/HTMLElement/Roo.Element} el The context element
4676      * @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'})
4677      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4678      * @return {HTMLElement/Roo.Element} The new node or Element
4679      */
4680     insertFirst: function(el, values, returnElement){
4681         return this.doInsert('afterBegin', el, values, returnElement);
4682     },
4683
4684     /**
4685      * Applies the supplied values to the template and inserts the new node(s) before el.
4686      * @param {String/HTMLElement/Roo.Element} el The context element
4687      * @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'})
4688      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4689      * @return {HTMLElement/Roo.Element} The new node or Element
4690      */
4691     insertBefore: function(el, values, returnElement){
4692         return this.doInsert('beforeBegin', el, values, returnElement);
4693     },
4694
4695     /**
4696      * Applies the supplied values to the template and inserts the new node(s) after el.
4697      * @param {String/HTMLElement/Roo.Element} el The context element
4698      * @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'})
4699      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4700      * @return {HTMLElement/Roo.Element} The new node or Element
4701      */
4702     insertAfter : function(el, values, returnElement){
4703         return this.doInsert('afterEnd', el, values, returnElement);
4704     },
4705     
4706     /**
4707      * Applies the supplied values to the template and appends the new node(s) to el.
4708      * @param {String/HTMLElement/Roo.Element} el The context element
4709      * @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'})
4710      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4711      * @return {HTMLElement/Roo.Element} The new node or Element
4712      */
4713     append : function(el, values, returnElement){
4714         return this.doInsert('beforeEnd', el, values, returnElement);
4715     },
4716
4717     doInsert : function(where, el, values, returnEl){
4718         el = Roo.getDom(el);
4719         var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
4720         return returnEl ? Roo.get(newNode, true) : newNode;
4721     },
4722
4723     /**
4724      * Applies the supplied values to the template and overwrites the content of el with the new node(s).
4725      * @param {String/HTMLElement/Roo.Element} el The context element
4726      * @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'})
4727      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4728      * @return {HTMLElement/Roo.Element} The new node or Element
4729      */
4730     overwrite : function(el, values, returnElement){
4731         el = Roo.getDom(el);
4732         el.innerHTML = this.applyTemplate(values);
4733         return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
4734     }
4735 };
4736 /**
4737  * Alias for {@link #applyTemplate}
4738  * @method
4739  */
4740 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
4741
4742 // backwards compat
4743 Roo.DomHelper.Template = Roo.Template;
4744
4745 /**
4746  * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
4747  * @param {String/HTMLElement} el A DOM element or its id
4748  * @returns {Roo.Template} The created template
4749  * @static
4750  */
4751 Roo.Template.from = function(el){
4752     el = Roo.getDom(el);
4753     return new Roo.Template(el.value || el.innerHTML);
4754 };/*
4755  * Based on:
4756  * Ext JS Library 1.1.1
4757  * Copyright(c) 2006-2007, Ext JS, LLC.
4758  *
4759  * Originally Released Under LGPL - original licence link has changed is not relivant.
4760  *
4761  * Fork - LGPL
4762  * <script type="text/javascript">
4763  */
4764  
4765
4766 /*
4767  * This is code is also distributed under MIT license for use
4768  * with jQuery and prototype JavaScript libraries.
4769  */
4770 /**
4771  * @class Roo.DomQuery
4772 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).
4773 <p>
4774 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>
4775
4776 <p>
4777 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.
4778 </p>
4779 <h4>Element Selectors:</h4>
4780 <ul class="list">
4781     <li> <b>*</b> any element</li>
4782     <li> <b>E</b> an element with the tag E</li>
4783     <li> <b>E F</b> All descendent elements of E that have the tag F</li>
4784     <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
4785     <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
4786     <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
4787 </ul>
4788 <h4>Attribute Selectors:</h4>
4789 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
4790 <ul class="list">
4791     <li> <b>E[foo]</b> has an attribute "foo"</li>
4792     <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
4793     <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
4794     <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
4795     <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
4796     <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
4797     <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
4798 </ul>
4799 <h4>Pseudo Classes:</h4>
4800 <ul class="list">
4801     <li> <b>E:first-child</b> E is the first child of its parent</li>
4802     <li> <b>E:last-child</b> E is the last child of its parent</li>
4803     <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>
4804     <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
4805     <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
4806     <li> <b>E:only-child</b> E is the only child of its parent</li>
4807     <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>
4808     <li> <b>E:first</b> the first E in the resultset</li>
4809     <li> <b>E:last</b> the last E in the resultset</li>
4810     <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
4811     <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
4812     <li> <b>E:even</b> shortcut for :nth-child(even)</li>
4813     <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
4814     <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
4815     <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
4816     <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
4817     <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
4818     <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
4819 </ul>
4820 <h4>CSS Value Selectors:</h4>
4821 <ul class="list">
4822     <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
4823     <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
4824     <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
4825     <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
4826     <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
4827     <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
4828 </ul>
4829  * @singleton
4830  */
4831 Roo.DomQuery = function(){
4832     var cache = {}, simpleCache = {}, valueCache = {};
4833     var nonSpace = /\S/;
4834     var trimRe = /^\s+|\s+$/g;
4835     var tplRe = /\{(\d+)\}/g;
4836     var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
4837     var tagTokenRe = /^(#)?([\w-\*]+)/;
4838     var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
4839
4840     function child(p, index){
4841         var i = 0;
4842         var n = p.firstChild;
4843         while(n){
4844             if(n.nodeType == 1){
4845                if(++i == index){
4846                    return n;
4847                }
4848             }
4849             n = n.nextSibling;
4850         }
4851         return null;
4852     };
4853
4854     function next(n){
4855         while((n = n.nextSibling) && n.nodeType != 1);
4856         return n;
4857     };
4858
4859     function prev(n){
4860         while((n = n.previousSibling) && n.nodeType != 1);
4861         return n;
4862     };
4863
4864     function children(d){
4865         var n = d.firstChild, ni = -1;
4866             while(n){
4867                 var nx = n.nextSibling;
4868                 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
4869                     d.removeChild(n);
4870                 }else{
4871                     n.nodeIndex = ++ni;
4872                 }
4873                 n = nx;
4874             }
4875             return this;
4876         };
4877
4878     function byClassName(c, a, v){
4879         if(!v){
4880             return c;
4881         }
4882         var r = [], ri = -1, cn;
4883         for(var i = 0, ci; ci = c[i]; i++){
4884             if((' '+ci.className+' ').indexOf(v) != -1){
4885                 r[++ri] = ci;
4886             }
4887         }
4888         return r;
4889     };
4890
4891     function attrValue(n, attr){
4892         if(!n.tagName && typeof n.length != "undefined"){
4893             n = n[0];
4894         }
4895         if(!n){
4896             return null;
4897         }
4898         if(attr == "for"){
4899             return n.htmlFor;
4900         }
4901         if(attr == "class" || attr == "className"){
4902             return n.className;
4903         }
4904         return n.getAttribute(attr) || n[attr];
4905
4906     };
4907
4908     function getNodes(ns, mode, tagName){
4909         var result = [], ri = -1, cs;
4910         if(!ns){
4911             return result;
4912         }
4913         tagName = tagName || "*";
4914         if(typeof ns.getElementsByTagName != "undefined"){
4915             ns = [ns];
4916         }
4917         if(!mode){
4918             for(var i = 0, ni; ni = ns[i]; i++){
4919                 cs = ni.getElementsByTagName(tagName);
4920                 for(var j = 0, ci; ci = cs[j]; j++){
4921                     result[++ri] = ci;
4922                 }
4923             }
4924         }else if(mode == "/" || mode == ">"){
4925             var utag = tagName.toUpperCase();
4926             for(var i = 0, ni, cn; ni = ns[i]; i++){
4927                 cn = ni.children || ni.childNodes;
4928                 for(var j = 0, cj; cj = cn[j]; j++){
4929                     if(cj.nodeName == utag || cj.nodeName == tagName  || tagName == '*'){
4930                         result[++ri] = cj;
4931                     }
4932                 }
4933             }
4934         }else if(mode == "+"){
4935             var utag = tagName.toUpperCase();
4936             for(var i = 0, n; n = ns[i]; i++){
4937                 while((n = n.nextSibling) && n.nodeType != 1);
4938                 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
4939                     result[++ri] = n;
4940                 }
4941             }
4942         }else if(mode == "~"){
4943             for(var i = 0, n; n = ns[i]; i++){
4944                 while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
4945                 if(n){
4946                     result[++ri] = n;
4947                 }
4948             }
4949         }
4950         return result;
4951     };
4952
4953     function concat(a, b){
4954         if(b.slice){
4955             return a.concat(b);
4956         }
4957         for(var i = 0, l = b.length; i < l; i++){
4958             a[a.length] = b[i];
4959         }
4960         return a;
4961     }
4962
4963     function byTag(cs, tagName){
4964         if(cs.tagName || cs == document){
4965             cs = [cs];
4966         }
4967         if(!tagName){
4968             return cs;
4969         }
4970         var r = [], ri = -1;
4971         tagName = tagName.toLowerCase();
4972         for(var i = 0, ci; ci = cs[i]; i++){
4973             if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
4974                 r[++ri] = ci;
4975             }
4976         }
4977         return r;
4978     };
4979
4980     function byId(cs, attr, id){
4981         if(cs.tagName || cs == document){
4982             cs = [cs];
4983         }
4984         if(!id){
4985             return cs;
4986         }
4987         var r = [], ri = -1;
4988         for(var i = 0,ci; ci = cs[i]; i++){
4989             if(ci && ci.id == id){
4990                 r[++ri] = ci;
4991                 return r;
4992             }
4993         }
4994         return r;
4995     };
4996
4997     function byAttribute(cs, attr, value, op, custom){
4998         var r = [], ri = -1, st = custom=="{";
4999         var f = Roo.DomQuery.operators[op];
5000         for(var i = 0, ci; ci = cs[i]; i++){
5001             var a;
5002             if(st){
5003                 a = Roo.DomQuery.getStyle(ci, attr);
5004             }
5005             else if(attr == "class" || attr == "className"){
5006                 a = ci.className;
5007             }else if(attr == "for"){
5008                 a = ci.htmlFor;
5009             }else if(attr == "href"){
5010                 a = ci.getAttribute("href", 2);
5011             }else{
5012                 a = ci.getAttribute(attr);
5013             }
5014             if((f && f(a, value)) || (!f && a)){
5015                 r[++ri] = ci;
5016             }
5017         }
5018         return r;
5019     };
5020
5021     function byPseudo(cs, name, value){
5022         return Roo.DomQuery.pseudos[name](cs, value);
5023     };
5024
5025     // This is for IE MSXML which does not support expandos.
5026     // IE runs the same speed using setAttribute, however FF slows way down
5027     // and Safari completely fails so they need to continue to use expandos.
5028     var isIE = window.ActiveXObject ? true : false;
5029
5030     // this eval is stop the compressor from
5031     // renaming the variable to something shorter
5032     
5033     /** eval:var:batch */
5034     var batch = 30803; 
5035
5036     var key = 30803;
5037
5038     function nodupIEXml(cs){
5039         var d = ++key;
5040         cs[0].setAttribute("_nodup", d);
5041         var r = [cs[0]];
5042         for(var i = 1, len = cs.length; i < len; i++){
5043             var c = cs[i];
5044             if(!c.getAttribute("_nodup") != d){
5045                 c.setAttribute("_nodup", d);
5046                 r[r.length] = c;
5047             }
5048         }
5049         for(var i = 0, len = cs.length; i < len; i++){
5050             cs[i].removeAttribute("_nodup");
5051         }
5052         return r;
5053     }
5054
5055     function nodup(cs){
5056         if(!cs){
5057             return [];
5058         }
5059         var len = cs.length, c, i, r = cs, cj, ri = -1;
5060         if(!len || typeof cs.nodeType != "undefined" || len == 1){
5061             return cs;
5062         }
5063         if(isIE && typeof cs[0].selectSingleNode != "undefined"){
5064             return nodupIEXml(cs);
5065         }
5066         var d = ++key;
5067         cs[0]._nodup = d;
5068         for(i = 1; c = cs[i]; i++){
5069             if(c._nodup != d){
5070                 c._nodup = d;
5071             }else{
5072                 r = [];
5073                 for(var j = 0; j < i; j++){
5074                     r[++ri] = cs[j];
5075                 }
5076                 for(j = i+1; cj = cs[j]; j++){
5077                     if(cj._nodup != d){
5078                         cj._nodup = d;
5079                         r[++ri] = cj;
5080                     }
5081                 }
5082                 return r;
5083             }
5084         }
5085         return r;
5086     }
5087
5088     function quickDiffIEXml(c1, c2){
5089         var d = ++key;
5090         for(var i = 0, len = c1.length; i < len; i++){
5091             c1[i].setAttribute("_qdiff", d);
5092         }
5093         var r = [];
5094         for(var i = 0, len = c2.length; i < len; i++){
5095             if(c2[i].getAttribute("_qdiff") != d){
5096                 r[r.length] = c2[i];
5097             }
5098         }
5099         for(var i = 0, len = c1.length; i < len; i++){
5100            c1[i].removeAttribute("_qdiff");
5101         }
5102         return r;
5103     }
5104
5105     function quickDiff(c1, c2){
5106         var len1 = c1.length;
5107         if(!len1){
5108             return c2;
5109         }
5110         if(isIE && c1[0].selectSingleNode){
5111             return quickDiffIEXml(c1, c2);
5112         }
5113         var d = ++key;
5114         for(var i = 0; i < len1; i++){
5115             c1[i]._qdiff = d;
5116         }
5117         var r = [];
5118         for(var i = 0, len = c2.length; i < len; i++){
5119             if(c2[i]._qdiff != d){
5120                 r[r.length] = c2[i];
5121             }
5122         }
5123         return r;
5124     }
5125
5126     function quickId(ns, mode, root, id){
5127         if(ns == root){
5128            var d = root.ownerDocument || root;
5129            return d.getElementById(id);
5130         }
5131         ns = getNodes(ns, mode, "*");
5132         return byId(ns, null, id);
5133     }
5134
5135     return {
5136         getStyle : function(el, name){
5137             return Roo.fly(el).getStyle(name);
5138         },
5139         /**
5140          * Compiles a selector/xpath query into a reusable function. The returned function
5141          * takes one parameter "root" (optional), which is the context node from where the query should start.
5142          * @param {String} selector The selector/xpath query
5143          * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
5144          * @return {Function}
5145          */
5146         compile : function(path, type){
5147             type = type || "select";
5148             
5149             var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
5150             var q = path, mode, lq;
5151             var tk = Roo.DomQuery.matchers;
5152             var tklen = tk.length;
5153             var mm;
5154
5155             // accept leading mode switch
5156             var lmode = q.match(modeRe);
5157             if(lmode && lmode[1]){
5158                 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
5159                 q = q.replace(lmode[1], "");
5160             }
5161             // strip leading slashes
5162             while(path.substr(0, 1)=="/"){
5163                 path = path.substr(1);
5164             }
5165
5166             while(q && lq != q){
5167                 lq = q;
5168                 var tm = q.match(tagTokenRe);
5169                 if(type == "select"){
5170                     if(tm){
5171                         if(tm[1] == "#"){
5172                             fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
5173                         }else{
5174                             fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
5175                         }
5176                         q = q.replace(tm[0], "");
5177                     }else if(q.substr(0, 1) != '@'){
5178                         fn[fn.length] = 'n = getNodes(n, mode, "*");';
5179                     }
5180                 }else{
5181                     if(tm){
5182                         if(tm[1] == "#"){
5183                             fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
5184                         }else{
5185                             fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
5186                         }
5187                         q = q.replace(tm[0], "");
5188                     }
5189                 }
5190                 while(!(mm = q.match(modeRe))){
5191                     var matched = false;
5192                     for(var j = 0; j < tklen; j++){
5193                         var t = tk[j];
5194                         var m = q.match(t.re);
5195                         if(m){
5196                             fn[fn.length] = t.select.replace(tplRe, function(x, i){
5197                                                     return m[i];
5198                                                 });
5199                             q = q.replace(m[0], "");
5200                             matched = true;
5201                             break;
5202                         }
5203                     }
5204                     // prevent infinite loop on bad selector
5205                     if(!matched){
5206                         throw 'Error parsing selector, parsing failed at "' + q + '"';
5207                     }
5208                 }
5209                 if(mm[1]){
5210                     fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
5211                     q = q.replace(mm[1], "");
5212                 }
5213             }
5214             fn[fn.length] = "return nodup(n);\n}";
5215             
5216              /** 
5217               * list of variables that need from compression as they are used by eval.
5218              *  eval:var:batch 
5219              *  eval:var:nodup
5220              *  eval:var:byTag
5221              *  eval:var:ById
5222              *  eval:var:getNodes
5223              *  eval:var:quickId
5224              *  eval:var:mode
5225              *  eval:var:root
5226              *  eval:var:n
5227              *  eval:var:byClassName
5228              *  eval:var:byPseudo
5229              *  eval:var:byAttribute
5230              *  eval:var:attrValue
5231              * 
5232              **/ 
5233             eval(fn.join(""));
5234             return f;
5235         },
5236
5237         /**
5238          * Selects a group of elements.
5239          * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
5240          * @param {Node} root (optional) The start of the query (defaults to document).
5241          * @return {Array}
5242          */
5243         select : function(path, root, type){
5244             if(!root || root == document){
5245                 root = document;
5246             }
5247             if(typeof root == "string"){
5248                 root = document.getElementById(root);
5249             }
5250             var paths = path.split(",");
5251             var results = [];
5252             for(var i = 0, len = paths.length; i < len; i++){
5253                 var p = paths[i].replace(trimRe, "");
5254                 if(!cache[p]){
5255                     cache[p] = Roo.DomQuery.compile(p);
5256                     if(!cache[p]){
5257                         throw p + " is not a valid selector";
5258                     }
5259                 }
5260                 var result = cache[p](root);
5261                 if(result && result != document){
5262                     results = results.concat(result);
5263                 }
5264             }
5265             if(paths.length > 1){
5266                 return nodup(results);
5267             }
5268             return results;
5269         },
5270
5271         /**
5272          * Selects a single element.
5273          * @param {String} selector The selector/xpath query
5274          * @param {Node} root (optional) The start of the query (defaults to document).
5275          * @return {Element}
5276          */
5277         selectNode : function(path, root){
5278             return Roo.DomQuery.select(path, root)[0];
5279         },
5280
5281         /**
5282          * Selects the value of a node, optionally replacing null with the defaultValue.
5283          * @param {String} selector The selector/xpath query
5284          * @param {Node} root (optional) The start of the query (defaults to document).
5285          * @param {String} defaultValue
5286          */
5287         selectValue : function(path, root, defaultValue){
5288             path = path.replace(trimRe, "");
5289             if(!valueCache[path]){
5290                 valueCache[path] = Roo.DomQuery.compile(path, "select");
5291             }
5292             var n = valueCache[path](root);
5293             n = n[0] ? n[0] : n;
5294             var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
5295             return ((v === null||v === undefined||v==='') ? defaultValue : v);
5296         },
5297
5298         /**
5299          * Selects the value of a node, parsing integers and floats.
5300          * @param {String} selector The selector/xpath query
5301          * @param {Node} root (optional) The start of the query (defaults to document).
5302          * @param {Number} defaultValue
5303          * @return {Number}
5304          */
5305         selectNumber : function(path, root, defaultValue){
5306             var v = Roo.DomQuery.selectValue(path, root, defaultValue || 0);
5307             return parseFloat(v);
5308         },
5309
5310         /**
5311          * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
5312          * @param {String/HTMLElement/Array} el An element id, element or array of elements
5313          * @param {String} selector The simple selector to test
5314          * @return {Boolean}
5315          */
5316         is : function(el, ss){
5317             if(typeof el == "string"){
5318                 el = document.getElementById(el);
5319             }
5320             var isArray = (el instanceof Array);
5321             var result = Roo.DomQuery.filter(isArray ? el : [el], ss);
5322             return isArray ? (result.length == el.length) : (result.length > 0);
5323         },
5324
5325         /**
5326          * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
5327          * @param {Array} el An array of elements to filter
5328          * @param {String} selector The simple selector to test
5329          * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
5330          * the selector instead of the ones that match
5331          * @return {Array}
5332          */
5333         filter : function(els, ss, nonMatches){
5334             ss = ss.replace(trimRe, "");
5335             if(!simpleCache[ss]){
5336                 simpleCache[ss] = Roo.DomQuery.compile(ss, "simple");
5337             }
5338             var result = simpleCache[ss](els);
5339             return nonMatches ? quickDiff(result, els) : result;
5340         },
5341
5342         /**
5343          * Collection of matching regular expressions and code snippets.
5344          */
5345         matchers : [{
5346                 re: /^\.([\w-]+)/,
5347                 select: 'n = byClassName(n, null, " {1} ");'
5348             }, {
5349                 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
5350                 select: 'n = byPseudo(n, "{1}", "{2}");'
5351             },{
5352                 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
5353                 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
5354             }, {
5355                 re: /^#([\w-]+)/,
5356                 select: 'n = byId(n, null, "{1}");'
5357             },{
5358                 re: /^@([\w-]+)/,
5359                 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
5360             }
5361         ],
5362
5363         /**
5364          * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
5365          * 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, &gt; &lt;.
5366          */
5367         operators : {
5368             "=" : function(a, v){
5369                 return a == v;
5370             },
5371             "!=" : function(a, v){
5372                 return a != v;
5373             },
5374             "^=" : function(a, v){
5375                 return a && a.substr(0, v.length) == v;
5376             },
5377             "$=" : function(a, v){
5378                 return a && a.substr(a.length-v.length) == v;
5379             },
5380             "*=" : function(a, v){
5381                 return a && a.indexOf(v) !== -1;
5382             },
5383             "%=" : function(a, v){
5384                 return (a % v) == 0;
5385             },
5386             "|=" : function(a, v){
5387                 return a && (a == v || a.substr(0, v.length+1) == v+'-');
5388             },
5389             "~=" : function(a, v){
5390                 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
5391             }
5392         },
5393
5394         /**
5395          * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
5396          * and the argument (if any) supplied in the selector.
5397          */
5398         pseudos : {
5399             "first-child" : function(c){
5400                 var r = [], ri = -1, n;
5401                 for(var i = 0, ci; ci = n = c[i]; i++){
5402                     while((n = n.previousSibling) && n.nodeType != 1);
5403                     if(!n){
5404                         r[++ri] = ci;
5405                     }
5406                 }
5407                 return r;
5408             },
5409
5410             "last-child" : function(c){
5411                 var r = [], ri = -1, n;
5412                 for(var i = 0, ci; ci = n = c[i]; i++){
5413                     while((n = n.nextSibling) && n.nodeType != 1);
5414                     if(!n){
5415                         r[++ri] = ci;
5416                     }
5417                 }
5418                 return r;
5419             },
5420
5421             "nth-child" : function(c, a) {
5422                 var r = [], ri = -1;
5423                 var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
5424                 var f = (m[1] || 1) - 0, l = m[2] - 0;
5425                 for(var i = 0, n; n = c[i]; i++){
5426                     var pn = n.parentNode;
5427                     if (batch != pn._batch) {
5428                         var j = 0;
5429                         for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
5430                             if(cn.nodeType == 1){
5431                                cn.nodeIndex = ++j;
5432                             }
5433                         }
5434                         pn._batch = batch;
5435                     }
5436                     if (f == 1) {
5437                         if (l == 0 || n.nodeIndex == l){
5438                             r[++ri] = n;
5439                         }
5440                     } else if ((n.nodeIndex + l) % f == 0){
5441                         r[++ri] = n;
5442                     }
5443                 }
5444
5445                 return r;
5446             },
5447
5448             "only-child" : function(c){
5449                 var r = [], ri = -1;;
5450                 for(var i = 0, ci; ci = c[i]; i++){
5451                     if(!prev(ci) && !next(ci)){
5452                         r[++ri] = ci;
5453                     }
5454                 }
5455                 return r;
5456             },
5457
5458             "empty" : function(c){
5459                 var r = [], ri = -1;
5460                 for(var i = 0, ci; ci = c[i]; i++){
5461                     var cns = ci.childNodes, j = 0, cn, empty = true;
5462                     while(cn = cns[j]){
5463                         ++j;
5464                         if(cn.nodeType == 1 || cn.nodeType == 3){
5465                             empty = false;
5466                             break;
5467                         }
5468                     }
5469                     if(empty){
5470                         r[++ri] = ci;
5471                     }
5472                 }
5473                 return r;
5474             },
5475
5476             "contains" : function(c, v){
5477                 var r = [], ri = -1;
5478                 for(var i = 0, ci; ci = c[i]; i++){
5479                     if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
5480                         r[++ri] = ci;
5481                     }
5482                 }
5483                 return r;
5484             },
5485
5486             "nodeValue" : function(c, v){
5487                 var r = [], ri = -1;
5488                 for(var i = 0, ci; ci = c[i]; i++){
5489                     if(ci.firstChild && ci.firstChild.nodeValue == v){
5490                         r[++ri] = ci;
5491                     }
5492                 }
5493                 return r;
5494             },
5495
5496             "checked" : function(c){
5497                 var r = [], ri = -1;
5498                 for(var i = 0, ci; ci = c[i]; i++){
5499                     if(ci.checked == true){
5500                         r[++ri] = ci;
5501                     }
5502                 }
5503                 return r;
5504             },
5505
5506             "not" : function(c, ss){
5507                 return Roo.DomQuery.filter(c, ss, true);
5508             },
5509
5510             "odd" : function(c){
5511                 return this["nth-child"](c, "odd");
5512             },
5513
5514             "even" : function(c){
5515                 return this["nth-child"](c, "even");
5516             },
5517
5518             "nth" : function(c, a){
5519                 return c[a-1] || [];
5520             },
5521
5522             "first" : function(c){
5523                 return c[0] || [];
5524             },
5525
5526             "last" : function(c){
5527                 return c[c.length-1] || [];
5528             },
5529
5530             "has" : function(c, ss){
5531                 var s = Roo.DomQuery.select;
5532                 var r = [], ri = -1;
5533                 for(var i = 0, ci; ci = c[i]; i++){
5534                     if(s(ss, ci).length > 0){
5535                         r[++ri] = ci;
5536                     }
5537                 }
5538                 return r;
5539             },
5540
5541             "next" : function(c, ss){
5542                 var is = Roo.DomQuery.is;
5543                 var r = [], ri = -1;
5544                 for(var i = 0, ci; ci = c[i]; i++){
5545                     var n = next(ci);
5546                     if(n && is(n, ss)){
5547                         r[++ri] = ci;
5548                     }
5549                 }
5550                 return r;
5551             },
5552
5553             "prev" : function(c, ss){
5554                 var is = Roo.DomQuery.is;
5555                 var r = [], ri = -1;
5556                 for(var i = 0, ci; ci = c[i]; i++){
5557                     var n = prev(ci);
5558                     if(n && is(n, ss)){
5559                         r[++ri] = ci;
5560                     }
5561                 }
5562                 return r;
5563             }
5564         }
5565     };
5566 }();
5567
5568 /**
5569  * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Roo.DomQuery#select}
5570  * @param {String} path The selector/xpath query
5571  * @param {Node} root (optional) The start of the query (defaults to document).
5572  * @return {Array}
5573  * @member Roo
5574  * @method query
5575  */
5576 Roo.query = Roo.DomQuery.select;
5577 /*
5578  * Based on:
5579  * Ext JS Library 1.1.1
5580  * Copyright(c) 2006-2007, Ext JS, LLC.
5581  *
5582  * Originally Released Under LGPL - original licence link has changed is not relivant.
5583  *
5584  * Fork - LGPL
5585  * <script type="text/javascript">
5586  */
5587
5588 /**
5589  * @class Roo.util.Observable
5590  * Base class that provides a common interface for publishing events. Subclasses are expected to
5591  * to have a property "events" with all the events defined.<br>
5592  * For example:
5593  * <pre><code>
5594  Employee = function(name){
5595     this.name = name;
5596     this.addEvents({
5597         "fired" : true,
5598         "quit" : true
5599     });
5600  }
5601  Roo.extend(Employee, Roo.util.Observable);
5602 </code></pre>
5603  * @param {Object} config properties to use (incuding events / listeners)
5604  */
5605
5606 Roo.util.Observable = function(cfg){
5607     
5608     cfg = cfg|| {};
5609     this.addEvents(cfg.events || {});
5610     if (cfg.events) {
5611         delete cfg.events; // make sure
5612     }
5613      
5614     Roo.apply(this, cfg);
5615     
5616     if(this.listeners){
5617         this.on(this.listeners);
5618         delete this.listeners;
5619     }
5620 };
5621 Roo.util.Observable.prototype = {
5622     /** 
5623  * @cfg {Object} listeners  list of events and functions to call for this object, 
5624  * For example :
5625  * <pre><code>
5626     listeners :  { 
5627        'click' : function(e) {
5628            ..... 
5629         } ,
5630         .... 
5631     } 
5632   </code></pre>
5633  */
5634     
5635     
5636     /**
5637      * Fires the specified event with the passed parameters (minus the event name).
5638      * @param {String} eventName
5639      * @param {Object...} args Variable number of parameters are passed to handlers
5640      * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
5641      */
5642     fireEvent : function(){
5643         var ce = this.events[arguments[0].toLowerCase()];
5644         if(typeof ce == "object"){
5645             return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
5646         }else{
5647             return true;
5648         }
5649     },
5650
5651     // private
5652     filterOptRe : /^(?:scope|delay|buffer|single)$/,
5653
5654     /**
5655      * Appends an event handler to this component
5656      * @param {String}   eventName The type of event to listen for
5657      * @param {Function} handler The method the event invokes
5658      * @param {Object}   scope (optional) The scope in which to execute the handler
5659      * function. The handler function's "this" context.
5660      * @param {Object}   options (optional) An object containing handler configuration
5661      * properties. This may contain any of the following properties:<ul>
5662      * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
5663      * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
5664      * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
5665      * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
5666      * by the specified number of milliseconds. If the event fires again within that time, the original
5667      * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
5668      * </ul><br>
5669      * <p>
5670      * <b>Combining Options</b><br>
5671      * Using the options argument, it is possible to combine different types of listeners:<br>
5672      * <br>
5673      * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
5674                 <pre><code>
5675                 el.on('click', this.onClick, this, {
5676                         single: true,
5677                 delay: 100,
5678                 forumId: 4
5679                 });
5680                 </code></pre>
5681      * <p>
5682      * <b>Attaching multiple handlers in 1 call</b><br>
5683      * The method also allows for a single argument to be passed which is a config object containing properties
5684      * which specify multiple handlers.
5685      * <pre><code>
5686                 el.on({
5687                         'click': {
5688                         fn: this.onClick,
5689                         scope: this,
5690                         delay: 100
5691                 }, 
5692                 'mouseover': {
5693                         fn: this.onMouseOver,
5694                         scope: this
5695                 },
5696                 'mouseout': {
5697                         fn: this.onMouseOut,
5698                         scope: this
5699                 }
5700                 });
5701                 </code></pre>
5702      * <p>
5703      * Or a shorthand syntax which passes the same scope object to all handlers:
5704         <pre><code>
5705                 el.on({
5706                         'click': this.onClick,
5707                 'mouseover': this.onMouseOver,
5708                 'mouseout': this.onMouseOut,
5709                 scope: this
5710                 });
5711                 </code></pre>
5712      */
5713     addListener : function(eventName, fn, scope, o){
5714         if(typeof eventName == "object"){
5715             o = eventName;
5716             for(var e in o){
5717                 if(this.filterOptRe.test(e)){
5718                     continue;
5719                 }
5720                 if(typeof o[e] == "function"){
5721                     // shared options
5722                     this.addListener(e, o[e], o.scope,  o);
5723                 }else{
5724                     // individual options
5725                     this.addListener(e, o[e].fn, o[e].scope, o[e]);
5726                 }
5727             }
5728             return;
5729         }
5730         o = (!o || typeof o == "boolean") ? {} : o;
5731         eventName = eventName.toLowerCase();
5732         var ce = this.events[eventName] || true;
5733         if(typeof ce == "boolean"){
5734             ce = new Roo.util.Event(this, eventName);
5735             this.events[eventName] = ce;
5736         }
5737         ce.addListener(fn, scope, o);
5738     },
5739
5740     /**
5741      * Removes a listener
5742      * @param {String}   eventName     The type of event to listen for
5743      * @param {Function} handler        The handler to remove
5744      * @param {Object}   scope  (optional) The scope (this object) for the handler
5745      */
5746     removeListener : function(eventName, fn, scope){
5747         var ce = this.events[eventName.toLowerCase()];
5748         if(typeof ce == "object"){
5749             ce.removeListener(fn, scope);
5750         }
5751     },
5752
5753     /**
5754      * Removes all listeners for this object
5755      */
5756     purgeListeners : function(){
5757         for(var evt in this.events){
5758             if(typeof this.events[evt] == "object"){
5759                  this.events[evt].clearListeners();
5760             }
5761         }
5762     },
5763
5764     relayEvents : function(o, events){
5765         var createHandler = function(ename){
5766             return function(){
5767                 return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
5768             };
5769         };
5770         for(var i = 0, len = events.length; i < len; i++){
5771             var ename = events[i];
5772             if(!this.events[ename]){ this.events[ename] = true; };
5773             o.on(ename, createHandler(ename), this);
5774         }
5775     },
5776
5777     /**
5778      * Used to define events on this Observable
5779      * @param {Object} object The object with the events defined
5780      */
5781     addEvents : function(o){
5782         if(!this.events){
5783             this.events = {};
5784         }
5785         Roo.applyIf(this.events, o);
5786     },
5787
5788     /**
5789      * Checks to see if this object has any listeners for a specified event
5790      * @param {String} eventName The name of the event to check for
5791      * @return {Boolean} True if the event is being listened for, else false
5792      */
5793     hasListener : function(eventName){
5794         var e = this.events[eventName];
5795         return typeof e == "object" && e.listeners.length > 0;
5796     }
5797 };
5798 /**
5799  * Appends an event handler to this element (shorthand for addListener)
5800  * @param {String}   eventName     The type of event to listen for
5801  * @param {Function} handler        The method the event invokes
5802  * @param {Object}   scope (optional) The scope in which to execute the handler
5803  * function. The handler function's "this" context.
5804  * @param {Object}   options  (optional)
5805  * @method
5806  */
5807 Roo.util.Observable.prototype.on = Roo.util.Observable.prototype.addListener;
5808 /**
5809  * Removes a listener (shorthand for removeListener)
5810  * @param {String}   eventName     The type of event to listen for
5811  * @param {Function} handler        The handler to remove
5812  * @param {Object}   scope  (optional) The scope (this object) for the handler
5813  * @method
5814  */
5815 Roo.util.Observable.prototype.un = Roo.util.Observable.prototype.removeListener;
5816
5817 /**
5818  * Starts capture on the specified Observable. All events will be passed
5819  * to the supplied function with the event name + standard signature of the event
5820  * <b>before</b> the event is fired. If the supplied function returns false,
5821  * the event will not fire.
5822  * @param {Observable} o The Observable to capture
5823  * @param {Function} fn The function to call
5824  * @param {Object} scope (optional) The scope (this object) for the fn
5825  * @static
5826  */
5827 Roo.util.Observable.capture = function(o, fn, scope){
5828     o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
5829 };
5830
5831 /**
5832  * Removes <b>all</b> added captures from the Observable.
5833  * @param {Observable} o The Observable to release
5834  * @static
5835  */
5836 Roo.util.Observable.releaseCapture = function(o){
5837     o.fireEvent = Roo.util.Observable.prototype.fireEvent;
5838 };
5839
5840 (function(){
5841
5842     var createBuffered = function(h, o, scope){
5843         var task = new Roo.util.DelayedTask();
5844         return function(){
5845             task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
5846         };
5847     };
5848
5849     var createSingle = function(h, e, fn, scope){
5850         return function(){
5851             e.removeListener(fn, scope);
5852             return h.apply(scope, arguments);
5853         };
5854     };
5855
5856     var createDelayed = function(h, o, scope){
5857         return function(){
5858             var args = Array.prototype.slice.call(arguments, 0);
5859             setTimeout(function(){
5860                 h.apply(scope, args);
5861             }, o.delay || 10);
5862         };
5863     };
5864
5865     Roo.util.Event = function(obj, name){
5866         this.name = name;
5867         this.obj = obj;
5868         this.listeners = [];
5869     };
5870
5871     Roo.util.Event.prototype = {
5872         addListener : function(fn, scope, options){
5873             var o = options || {};
5874             scope = scope || this.obj;
5875             if(!this.isListening(fn, scope)){
5876                 var l = {fn: fn, scope: scope, options: o};
5877                 var h = fn;
5878                 if(o.delay){
5879                     h = createDelayed(h, o, scope);
5880                 }
5881                 if(o.single){
5882                     h = createSingle(h, this, fn, scope);
5883                 }
5884                 if(o.buffer){
5885                     h = createBuffered(h, o, scope);
5886                 }
5887                 l.fireFn = h;
5888                 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
5889                     this.listeners.push(l);
5890                 }else{
5891                     this.listeners = this.listeners.slice(0);
5892                     this.listeners.push(l);
5893                 }
5894             }
5895         },
5896
5897         findListener : function(fn, scope){
5898             scope = scope || this.obj;
5899             var ls = this.listeners;
5900             for(var i = 0, len = ls.length; i < len; i++){
5901                 var l = ls[i];
5902                 if(l.fn == fn && l.scope == scope){
5903                     return i;
5904                 }
5905             }
5906             return -1;
5907         },
5908
5909         isListening : function(fn, scope){
5910             return this.findListener(fn, scope) != -1;
5911         },
5912
5913         removeListener : function(fn, scope){
5914             var index;
5915             if((index = this.findListener(fn, scope)) != -1){
5916                 if(!this.firing){
5917                     this.listeners.splice(index, 1);
5918                 }else{
5919                     this.listeners = this.listeners.slice(0);
5920                     this.listeners.splice(index, 1);
5921                 }
5922                 return true;
5923             }
5924             return false;
5925         },
5926
5927         clearListeners : function(){
5928             this.listeners = [];
5929         },
5930
5931         fire : function(){
5932             var ls = this.listeners, scope, len = ls.length;
5933             if(len > 0){
5934                 this.firing = true;
5935                 var args = Array.prototype.slice.call(arguments, 0);
5936                 for(var i = 0; i < len; i++){
5937                     var l = ls[i];
5938                     if(l.fireFn.apply(l.scope||this.obj||window, arguments) === false){
5939                         this.firing = false;
5940                         return false;
5941                     }
5942                 }
5943                 this.firing = false;
5944             }
5945             return true;
5946         }
5947     };
5948 })();/*
5949  * Based on:
5950  * Ext JS Library 1.1.1
5951  * Copyright(c) 2006-2007, Ext JS, LLC.
5952  *
5953  * Originally Released Under LGPL - original licence link has changed is not relivant.
5954  *
5955  * Fork - LGPL
5956  * <script type="text/javascript">
5957  */
5958
5959 /**
5960  * @class Roo.EventManager
5961  * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides 
5962  * several useful events directly.
5963  * See {@link Roo.EventObject} for more details on normalized event objects.
5964  * @singleton
5965  */
5966 Roo.EventManager = function(){
5967     var docReadyEvent, docReadyProcId, docReadyState = false;
5968     var resizeEvent, resizeTask, textEvent, textSize;
5969     var E = Roo.lib.Event;
5970     var D = Roo.lib.Dom;
5971
5972
5973     var fireDocReady = function(){
5974         if(!docReadyState){
5975             docReadyState = true;
5976             Roo.isReady = true;
5977             if(docReadyProcId){
5978                 clearInterval(docReadyProcId);
5979             }
5980             if(Roo.isGecko || Roo.isOpera) {
5981                 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
5982             }
5983             if(Roo.isIE){
5984                 var defer = document.getElementById("ie-deferred-loader");
5985                 if(defer){
5986                     defer.onreadystatechange = null;
5987                     defer.parentNode.removeChild(defer);
5988                 }
5989             }
5990             if(docReadyEvent){
5991                 docReadyEvent.fire();
5992                 docReadyEvent.clearListeners();
5993             }
5994         }
5995     };
5996     
5997     var initDocReady = function(){
5998         docReadyEvent = new Roo.util.Event();
5999         if(Roo.isGecko || Roo.isOpera) {
6000             document.addEventListener("DOMContentLoaded", fireDocReady, false);
6001         }else if(Roo.isIE){
6002             document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
6003             var defer = document.getElementById("ie-deferred-loader");
6004             defer.onreadystatechange = function(){
6005                 if(this.readyState == "complete"){
6006                     fireDocReady();
6007                 }
6008             };
6009         }else if(Roo.isSafari){ 
6010             docReadyProcId = setInterval(function(){
6011                 var rs = document.readyState;
6012                 if(rs == "complete") {
6013                     fireDocReady();     
6014                  }
6015             }, 10);
6016         }
6017         // no matter what, make sure it fires on load
6018         E.on(window, "load", fireDocReady);
6019     };
6020
6021     var createBuffered = function(h, o){
6022         var task = new Roo.util.DelayedTask(h);
6023         return function(e){
6024             // create new event object impl so new events don't wipe out properties
6025             e = new Roo.EventObjectImpl(e);
6026             task.delay(o.buffer, h, null, [e]);
6027         };
6028     };
6029
6030     var createSingle = function(h, el, ename, fn){
6031         return function(e){
6032             Roo.EventManager.removeListener(el, ename, fn);
6033             h(e);
6034         };
6035     };
6036
6037     var createDelayed = function(h, o){
6038         return function(e){
6039             // create new event object impl so new events don't wipe out properties
6040             e = new Roo.EventObjectImpl(e);
6041             setTimeout(function(){
6042                 h(e);
6043             }, o.delay || 10);
6044         };
6045     };
6046
6047     var listen = function(element, ename, opt, fn, scope){
6048         var o = (!opt || typeof opt == "boolean") ? {} : opt;
6049         fn = fn || o.fn; scope = scope || o.scope;
6050         var el = Roo.getDom(element);
6051         if(!el){
6052             throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
6053         }
6054         var h = function(e){
6055             e = Roo.EventObject.setEvent(e);
6056             var t;
6057             if(o.delegate){
6058                 t = e.getTarget(o.delegate, el);
6059                 if(!t){
6060                     return;
6061                 }
6062             }else{
6063                 t = e.target;
6064             }
6065             if(o.stopEvent === true){
6066                 e.stopEvent();
6067             }
6068             if(o.preventDefault === true){
6069                e.preventDefault();
6070             }
6071             if(o.stopPropagation === true){
6072                 e.stopPropagation();
6073             }
6074
6075             if(o.normalized === false){
6076                 e = e.browserEvent;
6077             }
6078
6079             fn.call(scope || el, e, t, o);
6080         };
6081         if(o.delay){
6082             h = createDelayed(h, o);
6083         }
6084         if(o.single){
6085             h = createSingle(h, el, ename, fn);
6086         }
6087         if(o.buffer){
6088             h = createBuffered(h, o);
6089         }
6090         fn._handlers = fn._handlers || [];
6091         fn._handlers.push([Roo.id(el), ename, h]);
6092
6093         E.on(el, ename, h);
6094         if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
6095             el.addEventListener("DOMMouseScroll", h, false);
6096             E.on(window, 'unload', function(){
6097                 el.removeEventListener("DOMMouseScroll", h, false);
6098             });
6099         }
6100         if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
6101             Roo.EventManager.stoppedMouseDownEvent.addListener(h);
6102         }
6103         return h;
6104     };
6105
6106     var stopListening = function(el, ename, fn){
6107         var id = Roo.id(el), hds = fn._handlers, hd = fn;
6108         if(hds){
6109             for(var i = 0, len = hds.length; i < len; i++){
6110                 var h = hds[i];
6111                 if(h[0] == id && h[1] == ename){
6112                     hd = h[2];
6113                     hds.splice(i, 1);
6114                     break;
6115                 }
6116             }
6117         }
6118         E.un(el, ename, hd);
6119         el = Roo.getDom(el);
6120         if(ename == "mousewheel" && el.addEventListener){
6121             el.removeEventListener("DOMMouseScroll", hd, false);
6122         }
6123         if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
6124             Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
6125         }
6126     };
6127
6128     var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
6129     
6130     var pub = {
6131         
6132         
6133         /** 
6134          * Fix for doc tools
6135          * @scope Roo.EventManager
6136          */
6137         
6138         
6139         /** 
6140          * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
6141          * object with a Roo.EventObject
6142          * @param {Function} fn        The method the event invokes
6143          * @param {Object}   scope    An object that becomes the scope of the handler
6144          * @param {boolean}  override If true, the obj passed in becomes
6145          *                             the execution scope of the listener
6146          * @return {Function} The wrapped function
6147          * @deprecated
6148          */
6149         wrap : function(fn, scope, override){
6150             return function(e){
6151                 Roo.EventObject.setEvent(e);
6152                 fn.call(override ? scope || window : window, Roo.EventObject, scope);
6153             };
6154         },
6155         
6156         /**
6157      * Appends an event handler to an element (shorthand for addListener)
6158      * @param {String/HTMLElement}   element        The html element or id to assign the
6159      * @param {String}   eventName The type of event to listen for
6160      * @param {Function} handler The method the event invokes
6161      * @param {Object}   scope (optional) The scope in which to execute the handler
6162      * function. The handler function's "this" context.
6163      * @param {Object}   options (optional) An object containing handler configuration
6164      * properties. This may contain any of the following properties:<ul>
6165      * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6166      * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
6167      * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
6168      * <li>preventDefault {Boolean} True to prevent the default action</li>
6169      * <li>stopPropagation {Boolean} True to prevent event propagation</li>
6170      * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
6171      * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6172      * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6173      * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6174      * by the specified number of milliseconds. If the event fires again within that time, the original
6175      * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6176      * </ul><br>
6177      * <p>
6178      * <b>Combining Options</b><br>
6179      * Using the options argument, it is possible to combine different types of listeners:<br>
6180      * <br>
6181      * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
6182      * Code:<pre><code>
6183 el.on('click', this.onClick, this, {
6184     single: true,
6185     delay: 100,
6186     stopEvent : true,
6187     forumId: 4
6188 });</code></pre>
6189      * <p>
6190      * <b>Attaching multiple handlers in 1 call</b><br>
6191       * The method also allows for a single argument to be passed which is a config object containing properties
6192      * which specify multiple handlers.
6193      * <p>
6194      * Code:<pre><code>
6195 el.on({
6196     'click' : {
6197         fn: this.onClick
6198         scope: this,
6199         delay: 100
6200     },
6201     'mouseover' : {
6202         fn: this.onMouseOver
6203         scope: this
6204     },
6205     'mouseout' : {
6206         fn: this.onMouseOut
6207         scope: this
6208     }
6209 });</code></pre>
6210      * <p>
6211      * Or a shorthand syntax:<br>
6212      * Code:<pre><code>
6213 el.on({
6214     'click' : this.onClick,
6215     'mouseover' : this.onMouseOver,
6216     'mouseout' : this.onMouseOut
6217     scope: this
6218 });</code></pre>
6219      */
6220         addListener : function(element, eventName, fn, scope, options){
6221             if(typeof eventName == "object"){
6222                 var o = eventName;
6223                 for(var e in o){
6224                     if(propRe.test(e)){
6225                         continue;
6226                     }
6227                     if(typeof o[e] == "function"){
6228                         // shared options
6229                         listen(element, e, o, o[e], o.scope);
6230                     }else{
6231                         // individual options
6232                         listen(element, e, o[e]);
6233                     }
6234                 }
6235                 return;
6236             }
6237             return listen(element, eventName, options, fn, scope);
6238         },
6239         
6240         /**
6241          * Removes an event handler
6242          *
6243          * @param {String/HTMLElement}   element        The id or html element to remove the 
6244          *                             event from
6245          * @param {String}   eventName     The type of event
6246          * @param {Function} fn
6247          * @return {Boolean} True if a listener was actually removed
6248          */
6249         removeListener : function(element, eventName, fn){
6250             return stopListening(element, eventName, fn);
6251         },
6252         
6253         /**
6254          * Fires when the document is ready (before onload and before images are loaded). Can be 
6255          * accessed shorthanded Roo.onReady().
6256          * @param {Function} fn        The method the event invokes
6257          * @param {Object}   scope    An  object that becomes the scope of the handler
6258          * @param {boolean}  options
6259          */
6260         onDocumentReady : function(fn, scope, options){
6261             if(docReadyState){ // if it already fired
6262                 docReadyEvent.addListener(fn, scope, options);
6263                 docReadyEvent.fire();
6264                 docReadyEvent.clearListeners();
6265                 return;
6266             }
6267             if(!docReadyEvent){
6268                 initDocReady();
6269             }
6270             docReadyEvent.addListener(fn, scope, options);
6271         },
6272         
6273         /**
6274          * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
6275          * @param {Function} fn        The method the event invokes
6276          * @param {Object}   scope    An object that becomes the scope of the handler
6277          * @param {boolean}  options
6278          */
6279         onWindowResize : function(fn, scope, options){
6280             if(!resizeEvent){
6281                 resizeEvent = new Roo.util.Event();
6282                 resizeTask = new Roo.util.DelayedTask(function(){
6283                     resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6284                 });
6285                 E.on(window, "resize", function(){
6286                     if(Roo.isIE){
6287                         resizeTask.delay(50);
6288                     }else{
6289                         resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6290                     }
6291                 });
6292             }
6293             resizeEvent.addListener(fn, scope, options);
6294         },
6295
6296         /**
6297          * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
6298          * @param {Function} fn        The method the event invokes
6299          * @param {Object}   scope    An object that becomes the scope of the handler
6300          * @param {boolean}  options
6301          */
6302         onTextResize : function(fn, scope, options){
6303             if(!textEvent){
6304                 textEvent = new Roo.util.Event();
6305                 var textEl = new Roo.Element(document.createElement('div'));
6306                 textEl.dom.className = 'x-text-resize';
6307                 textEl.dom.innerHTML = 'X';
6308                 textEl.appendTo(document.body);
6309                 textSize = textEl.dom.offsetHeight;
6310                 setInterval(function(){
6311                     if(textEl.dom.offsetHeight != textSize){
6312                         textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
6313                     }
6314                 }, this.textResizeInterval);
6315             }
6316             textEvent.addListener(fn, scope, options);
6317         },
6318
6319         /**
6320          * Removes the passed window resize listener.
6321          * @param {Function} fn        The method the event invokes
6322          * @param {Object}   scope    The scope of handler
6323          */
6324         removeResizeListener : function(fn, scope){
6325             if(resizeEvent){
6326                 resizeEvent.removeListener(fn, scope);
6327             }
6328         },
6329
6330         // private
6331         fireResize : function(){
6332             if(resizeEvent){
6333                 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6334             }   
6335         },
6336         /**
6337          * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
6338          */
6339         ieDeferSrc : false,
6340         /**
6341          * The frequency, in milliseconds, to check for text resize events (defaults to 50)
6342          */
6343         textResizeInterval : 50
6344     };
6345     
6346     /**
6347      * Fix for doc tools
6348      * @scopeAlias pub=Roo.EventManager
6349      */
6350     
6351      /**
6352      * Appends an event handler to an element (shorthand for addListener)
6353      * @param {String/HTMLElement}   element        The html element or id to assign the
6354      * @param {String}   eventName The type of event to listen for
6355      * @param {Function} handler The method the event invokes
6356      * @param {Object}   scope (optional) The scope in which to execute the handler
6357      * function. The handler function's "this" context.
6358      * @param {Object}   options (optional) An object containing handler configuration
6359      * properties. This may contain any of the following properties:<ul>
6360      * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6361      * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
6362      * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
6363      * <li>preventDefault {Boolean} True to prevent the default action</li>
6364      * <li>stopPropagation {Boolean} True to prevent event propagation</li>
6365      * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
6366      * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6367      * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6368      * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6369      * by the specified number of milliseconds. If the event fires again within that time, the original
6370      * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6371      * </ul><br>
6372      * <p>
6373      * <b>Combining Options</b><br>
6374      * Using the options argument, it is possible to combine different types of listeners:<br>
6375      * <br>
6376      * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
6377      * Code:<pre><code>
6378 el.on('click', this.onClick, this, {
6379     single: true,
6380     delay: 100,
6381     stopEvent : true,
6382     forumId: 4
6383 });</code></pre>
6384      * <p>
6385      * <b>Attaching multiple handlers in 1 call</b><br>
6386       * The method also allows for a single argument to be passed which is a config object containing properties
6387      * which specify multiple handlers.
6388      * <p>
6389      * Code:<pre><code>
6390 el.on({
6391     'click' : {
6392         fn: this.onClick
6393         scope: this,
6394         delay: 100
6395     },
6396     'mouseover' : {
6397         fn: this.onMouseOver
6398         scope: this
6399     },
6400     'mouseout' : {
6401         fn: this.onMouseOut
6402         scope: this
6403     }
6404 });</code></pre>
6405      * <p>
6406      * Or a shorthand syntax:<br>
6407      * Code:<pre><code>
6408 el.on({
6409     'click' : this.onClick,
6410     'mouseover' : this.onMouseOver,
6411     'mouseout' : this.onMouseOut
6412     scope: this
6413 });</code></pre>
6414      */
6415     pub.on = pub.addListener;
6416     pub.un = pub.removeListener;
6417
6418     pub.stoppedMouseDownEvent = new Roo.util.Event();
6419     return pub;
6420 }();
6421 /**
6422   * Fires when the document is ready (before onload and before images are loaded).  Shorthand of {@link Roo.EventManager#onDocumentReady}.
6423   * @param {Function} fn        The method the event invokes
6424   * @param {Object}   scope    An  object that becomes the scope of the handler
6425   * @param {boolean}  override If true, the obj passed in becomes
6426   *                             the execution scope of the listener
6427   * @member Roo
6428   * @method onReady
6429  */
6430 Roo.onReady = Roo.EventManager.onDocumentReady;
6431
6432 Roo.onReady(function(){
6433     var bd = Roo.get(document.body);
6434     if(!bd){ return; }
6435
6436     var cls = [
6437             Roo.isIE ? "roo-ie"
6438             : Roo.isGecko ? "roo-gecko"
6439             : Roo.isOpera ? "roo-opera"
6440             : Roo.isSafari ? "roo-safari" : ""];
6441
6442     if(Roo.isMac){
6443         cls.push("roo-mac");
6444     }
6445     if(Roo.isLinux){
6446         cls.push("roo-linux");
6447     }
6448     if(Roo.isBorderBox){
6449         cls.push('roo-border-box');
6450     }
6451     if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
6452         var p = bd.dom.parentNode;
6453         if(p){
6454             p.className += ' roo-strict';
6455         }
6456     }
6457     bd.addClass(cls.join(' '));
6458 });
6459
6460 /**
6461  * @class Roo.EventObject
6462  * EventObject exposes the Yahoo! UI Event functionality directly on the object
6463  * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code 
6464  * Example:
6465  * <pre><code>
6466  function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
6467     e.preventDefault();
6468     var target = e.getTarget();
6469     ...
6470  }
6471  var myDiv = Roo.get("myDiv");
6472  myDiv.on("click", handleClick);
6473  //or
6474  Roo.EventManager.on("myDiv", 'click', handleClick);
6475  Roo.EventManager.addListener("myDiv", 'click', handleClick);
6476  </code></pre>
6477  * @singleton
6478  */
6479 Roo.EventObject = function(){
6480     
6481     var E = Roo.lib.Event;
6482     
6483     // safari keypress events for special keys return bad keycodes
6484     var safariKeys = {
6485         63234 : 37, // left
6486         63235 : 39, // right
6487         63232 : 38, // up
6488         63233 : 40, // down
6489         63276 : 33, // page up
6490         63277 : 34, // page down
6491         63272 : 46, // delete
6492         63273 : 36, // home
6493         63275 : 35  // end
6494     };
6495
6496     // normalize button clicks
6497     var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
6498                 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
6499
6500     Roo.EventObjectImpl = function(e){
6501         if(e){
6502             this.setEvent(e.browserEvent || e);
6503         }
6504     };
6505     Roo.EventObjectImpl.prototype = {
6506         /**
6507          * Used to fix doc tools.
6508          * @scope Roo.EventObject.prototype
6509          */
6510             
6511
6512         
6513         
6514         /** The normal browser event */
6515         browserEvent : null,
6516         /** The button pressed in a mouse event */
6517         button : -1,
6518         /** True if the shift key was down during the event */
6519         shiftKey : false,
6520         /** True if the control key was down during the event */
6521         ctrlKey : false,
6522         /** True if the alt key was down during the event */
6523         altKey : false,
6524
6525         /** Key constant 
6526         * @type Number */
6527         BACKSPACE : 8,
6528         /** Key constant 
6529         * @type Number */
6530         TAB : 9,
6531         /** Key constant 
6532         * @type Number */
6533         RETURN : 13,
6534         /** Key constant 
6535         * @type Number */
6536         ENTER : 13,
6537         /** Key constant 
6538         * @type Number */
6539         SHIFT : 16,
6540         /** Key constant 
6541         * @type Number */
6542         CONTROL : 17,
6543         /** Key constant 
6544         * @type Number */
6545         ESC : 27,
6546         /** Key constant 
6547         * @type Number */
6548         SPACE : 32,
6549         /** Key constant 
6550         * @type Number */
6551         PAGEUP : 33,
6552         /** Key constant 
6553         * @type Number */
6554         PAGEDOWN : 34,
6555         /** Key constant 
6556         * @type Number */
6557         END : 35,
6558         /** Key constant 
6559         * @type Number */
6560         HOME : 36,
6561         /** Key constant 
6562         * @type Number */
6563         LEFT : 37,
6564         /** Key constant 
6565         * @type Number */
6566         UP : 38,
6567         /** Key constant 
6568         * @type Number */
6569         RIGHT : 39,
6570         /** Key constant 
6571         * @type Number */
6572         DOWN : 40,
6573         /** Key constant 
6574         * @type Number */
6575         DELETE : 46,
6576         /** Key constant 
6577         * @type Number */
6578         F5 : 116,
6579
6580            /** @private */
6581         setEvent : function(e){
6582             if(e == this || (e && e.browserEvent)){ // already wrapped
6583                 return e;
6584             }
6585             this.browserEvent = e;
6586             if(e){
6587                 // normalize buttons
6588                 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
6589                 if(e.type == 'click' && this.button == -1){
6590                     this.button = 0;
6591                 }
6592                 this.type = e.type;
6593                 this.shiftKey = e.shiftKey;
6594                 // mac metaKey behaves like ctrlKey
6595                 this.ctrlKey = e.ctrlKey || e.metaKey;
6596                 this.altKey = e.altKey;
6597                 // in getKey these will be normalized for the mac
6598                 this.keyCode = e.keyCode;
6599                 // keyup warnings on firefox.
6600                 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
6601                 // cache the target for the delayed and or buffered events
6602                 this.target = E.getTarget(e);
6603                 // same for XY
6604                 this.xy = E.getXY(e);
6605             }else{
6606                 this.button = -1;
6607                 this.shiftKey = false;
6608                 this.ctrlKey = false;
6609                 this.altKey = false;
6610                 this.keyCode = 0;
6611                 this.charCode =0;
6612                 this.target = null;
6613                 this.xy = [0, 0];
6614             }
6615             return this;
6616         },
6617
6618         /**
6619          * Stop the event (preventDefault and stopPropagation)
6620          */
6621         stopEvent : function(){
6622             if(this.browserEvent){
6623                 if(this.browserEvent.type == 'mousedown'){
6624                     Roo.EventManager.stoppedMouseDownEvent.fire(this);
6625                 }
6626                 E.stopEvent(this.browserEvent);
6627             }
6628         },
6629
6630         /**
6631          * Prevents the browsers default handling of the event.
6632          */
6633         preventDefault : function(){
6634             if(this.browserEvent){
6635                 E.preventDefault(this.browserEvent);
6636             }
6637         },
6638
6639         /** @private */
6640         isNavKeyPress : function(){
6641             var k = this.keyCode;
6642             k = Roo.isSafari ? (safariKeys[k] || k) : k;
6643             return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
6644         },
6645
6646         isSpecialKey : function(){
6647             var k = this.keyCode;
6648             return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13  || k == 40 || k == 27 ||
6649             (k == 16) || (k == 17) ||
6650             (k >= 18 && k <= 20) ||
6651             (k >= 33 && k <= 35) ||
6652             (k >= 36 && k <= 39) ||
6653             (k >= 44 && k <= 45);
6654         },
6655         /**
6656          * Cancels bubbling of the event.
6657          */
6658         stopPropagation : function(){
6659             if(this.browserEvent){
6660                 if(this.type == 'mousedown'){
6661                     Roo.EventManager.stoppedMouseDownEvent.fire(this);
6662                 }
6663                 E.stopPropagation(this.browserEvent);
6664             }
6665         },
6666
6667         /**
6668          * Gets the key code for the event.
6669          * @return {Number}
6670          */
6671         getCharCode : function(){
6672             return this.charCode || this.keyCode;
6673         },
6674
6675         /**
6676          * Returns a normalized keyCode for the event.
6677          * @return {Number} The key code
6678          */
6679         getKey : function(){
6680             var k = this.keyCode || this.charCode;
6681             return Roo.isSafari ? (safariKeys[k] || k) : k;
6682         },
6683
6684         /**
6685          * Gets the x coordinate of the event.
6686          * @return {Number}
6687          */
6688         getPageX : function(){
6689             return this.xy[0];
6690         },
6691
6692         /**
6693          * Gets the y coordinate of the event.
6694          * @return {Number}
6695          */
6696         getPageY : function(){
6697             return this.xy[1];
6698         },
6699
6700         /**
6701          * Gets the time of the event.
6702          * @return {Number}
6703          */
6704         getTime : function(){
6705             if(this.browserEvent){
6706                 return E.getTime(this.browserEvent);
6707             }
6708             return null;
6709         },
6710
6711         /**
6712          * Gets the page coordinates of the event.
6713          * @return {Array} The xy values like [x, y]
6714          */
6715         getXY : function(){
6716             return this.xy;
6717         },
6718
6719         /**
6720          * Gets the target for the event.
6721          * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
6722          * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
6723                 search as a number or element (defaults to 10 || document.body)
6724          * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
6725          * @return {HTMLelement}
6726          */
6727         getTarget : function(selector, maxDepth, returnEl){
6728             return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
6729         },
6730         /**
6731          * Gets the related target.
6732          * @return {HTMLElement}
6733          */
6734         getRelatedTarget : function(){
6735             if(this.browserEvent){
6736                 return E.getRelatedTarget(this.browserEvent);
6737             }
6738             return null;
6739         },
6740
6741         /**
6742          * Normalizes mouse wheel delta across browsers
6743          * @return {Number} The delta
6744          */
6745         getWheelDelta : function(){
6746             var e = this.browserEvent;
6747             var delta = 0;
6748             if(e.wheelDelta){ /* IE/Opera. */
6749                 delta = e.wheelDelta/120;
6750             }else if(e.detail){ /* Mozilla case. */
6751                 delta = -e.detail/3;
6752             }
6753             return delta;
6754         },
6755
6756         /**
6757          * Returns true if the control, meta, shift or alt key was pressed during this event.
6758          * @return {Boolean}
6759          */
6760         hasModifier : function(){
6761             return !!((this.ctrlKey || this.altKey) || this.shiftKey);
6762         },
6763
6764         /**
6765          * Returns true if the target of this event equals el or is a child of el
6766          * @param {String/HTMLElement/Element} el
6767          * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
6768          * @return {Boolean}
6769          */
6770         within : function(el, related){
6771             var t = this[related ? "getRelatedTarget" : "getTarget"]();
6772             return t && Roo.fly(el).contains(t);
6773         },
6774
6775         getPoint : function(){
6776             return new Roo.lib.Point(this.xy[0], this.xy[1]);
6777         }
6778     };
6779
6780     return new Roo.EventObjectImpl();
6781 }();
6782             
6783     /*
6784  * Based on:
6785  * Ext JS Library 1.1.1
6786  * Copyright(c) 2006-2007, Ext JS, LLC.
6787  *
6788  * Originally Released Under LGPL - original licence link has changed is not relivant.
6789  *
6790  * Fork - LGPL
6791  * <script type="text/javascript">
6792  */
6793
6794  
6795 // was in Composite Element!??!?!
6796  
6797 (function(){
6798     var D = Roo.lib.Dom;
6799     var E = Roo.lib.Event;
6800     var A = Roo.lib.Anim;
6801
6802     // local style camelizing for speed
6803     var propCache = {};
6804     var camelRe = /(-[a-z])/gi;
6805     var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
6806     var view = document.defaultView;
6807
6808 /**
6809  * @class Roo.Element
6810  * Represents an Element in the DOM.<br><br>
6811  * Usage:<br>
6812 <pre><code>
6813 var el = Roo.get("my-div");
6814
6815 // or with getEl
6816 var el = getEl("my-div");
6817
6818 // or with a DOM element
6819 var el = Roo.get(myDivElement);
6820 </code></pre>
6821  * Using Roo.get() or getEl() instead of calling the constructor directly ensures you get the same object
6822  * each call instead of constructing a new one.<br><br>
6823  * <b>Animations</b><br />
6824  * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
6825  * should either be a boolean (true) or an object literal with animation options. The animation options are:
6826 <pre>
6827 Option    Default   Description
6828 --------- --------  ---------------------------------------------
6829 duration  .35       The duration of the animation in seconds
6830 easing    easeOut   The YUI easing method
6831 callback  none      A function to execute when the anim completes
6832 scope     this      The scope (this) of the callback function
6833 </pre>
6834 * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
6835 * manipulate the animation. Here's an example:
6836 <pre><code>
6837 var el = Roo.get("my-div");
6838
6839 // no animation
6840 el.setWidth(100);
6841
6842 // default animation
6843 el.setWidth(100, true);
6844
6845 // animation with some options set
6846 el.setWidth(100, {
6847     duration: 1,
6848     callback: this.foo,
6849     scope: this
6850 });
6851
6852 // using the "anim" property to get the Anim object
6853 var opt = {
6854     duration: 1,
6855     callback: this.foo,
6856     scope: this
6857 };
6858 el.setWidth(100, opt);
6859 ...
6860 if(opt.anim.isAnimated()){
6861     opt.anim.stop();
6862 }
6863 </code></pre>
6864 * <b> Composite (Collections of) Elements</b><br />
6865  * For working with collections of Elements, see <a href="Roo.CompositeElement.html">Roo.CompositeElement</a>
6866  * @constructor Create a new Element directly.
6867  * @param {String/HTMLElement} element
6868  * @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).
6869  */
6870     Roo.Element = function(element, forceNew){
6871         var dom = typeof element == "string" ?
6872                 document.getElementById(element) : element;
6873         if(!dom){ // invalid id/element
6874             return null;
6875         }
6876         var id = dom.id;
6877         if(forceNew !== true && id && Roo.Element.cache[id]){ // element object already exists
6878             return Roo.Element.cache[id];
6879         }
6880
6881         /**
6882          * The DOM element
6883          * @type HTMLElement
6884          */
6885         this.dom = dom;
6886
6887         /**
6888          * The DOM element ID
6889          * @type String
6890          */
6891         this.id = id || Roo.id(dom);
6892     };
6893
6894     var El = Roo.Element;
6895
6896     El.prototype = {
6897         /**
6898          * The element's default display mode  (defaults to "")
6899          * @type String
6900          */
6901         originalDisplay : "",
6902
6903         visibilityMode : 1,
6904         /**
6905          * The default unit to append to CSS values where a unit isn't provided (defaults to px).
6906          * @type String
6907          */
6908         defaultUnit : "px",
6909         /**
6910          * Sets the element's visibility mode. When setVisible() is called it
6911          * will use this to determine whether to set the visibility or the display property.
6912          * @param visMode Element.VISIBILITY or Element.DISPLAY
6913          * @return {Roo.Element} this
6914          */
6915         setVisibilityMode : function(visMode){
6916             this.visibilityMode = visMode;
6917             return this;
6918         },
6919         /**
6920          * Convenience method for setVisibilityMode(Element.DISPLAY)
6921          * @param {String} display (optional) What to set display to when visible
6922          * @return {Roo.Element} this
6923          */
6924         enableDisplayMode : function(display){
6925             this.setVisibilityMode(El.DISPLAY);
6926             if(typeof display != "undefined") this.originalDisplay = display;
6927             return this;
6928         },
6929
6930         /**
6931          * 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)
6932          * @param {String} selector The simple selector to test
6933          * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
6934                 search as a number or element (defaults to 10 || document.body)
6935          * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
6936          * @return {HTMLElement} The matching DOM node (or null if no match was found)
6937          */
6938         findParent : function(simpleSelector, maxDepth, returnEl){
6939             var p = this.dom, b = document.body, depth = 0, dq = Roo.DomQuery, stopEl;
6940             maxDepth = maxDepth || 50;
6941             if(typeof maxDepth != "number"){
6942                 stopEl = Roo.getDom(maxDepth);
6943                 maxDepth = 10;
6944             }
6945             while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
6946                 if(dq.is(p, simpleSelector)){
6947                     return returnEl ? Roo.get(p) : p;
6948                 }
6949                 depth++;
6950                 p = p.parentNode;
6951             }
6952             return null;
6953         },
6954
6955
6956         /**
6957          * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
6958          * @param {String} selector The simple selector to test
6959          * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
6960                 search as a number or element (defaults to 10 || document.body)
6961          * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
6962          * @return {HTMLElement} The matching DOM node (or null if no match was found)
6963          */
6964         findParentNode : function(simpleSelector, maxDepth, returnEl){
6965             var p = Roo.fly(this.dom.parentNode, '_internal');
6966             return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
6967         },
6968
6969         /**
6970          * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
6971          * This is a shortcut for findParentNode() that always returns an Roo.Element.
6972          * @param {String} selector The simple selector to test
6973          * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
6974                 search as a number or element (defaults to 10 || document.body)
6975          * @return {Roo.Element} The matching DOM node (or null if no match was found)
6976          */
6977         up : function(simpleSelector, maxDepth){
6978             return this.findParentNode(simpleSelector, maxDepth, true);
6979         },
6980
6981
6982
6983         /**
6984          * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
6985          * @param {String} selector The simple selector to test
6986          * @return {Boolean} True if this element matches the selector, else false
6987          */
6988         is : function(simpleSelector){
6989             return Roo.DomQuery.is(this.dom, simpleSelector);
6990         },
6991
6992         /**
6993          * Perform animation on this element.
6994          * @param {Object} args The YUI animation control args
6995          * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35)
6996          * @param {Function} onComplete (optional) Function to call when animation completes
6997          * @param {String} easing (optional) Easing method to use (defaults to 'easeOut')
6998          * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
6999          * @return {Roo.Element} this
7000          */
7001         animate : function(args, duration, onComplete, easing, animType){
7002             this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
7003             return this;
7004         },
7005
7006         /*
7007          * @private Internal animation call
7008          */
7009         anim : function(args, opt, animType, defaultDur, defaultEase, cb){
7010             animType = animType || 'run';
7011             opt = opt || {};
7012             var anim = Roo.lib.Anim[animType](
7013                 this.dom, args,
7014                 (opt.duration || defaultDur) || .35,
7015                 (opt.easing || defaultEase) || 'easeOut',
7016                 function(){
7017                     Roo.callback(cb, this);
7018                     Roo.callback(opt.callback, opt.scope || this, [this, opt]);
7019                 },
7020                 this
7021             );
7022             opt.anim = anim;
7023             return anim;
7024         },
7025
7026         // private legacy anim prep
7027         preanim : function(a, i){
7028             return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
7029         },
7030
7031         /**
7032          * Removes worthless text nodes
7033          * @param {Boolean} forceReclean (optional) By default the element
7034          * keeps track if it has been cleaned already so
7035          * you can call this over and over. However, if you update the element and
7036          * need to force a reclean, you can pass true.
7037          */
7038         clean : function(forceReclean){
7039             if(this.isCleaned && forceReclean !== true){
7040                 return this;
7041             }
7042             var ns = /\S/;
7043             var d = this.dom, n = d.firstChild, ni = -1;
7044             while(n){
7045                 var nx = n.nextSibling;
7046                 if(n.nodeType == 3 && !ns.test(n.nodeValue)){
7047                     d.removeChild(n);
7048                 }else{
7049                     n.nodeIndex = ++ni;
7050                 }
7051                 n = nx;
7052             }
7053             this.isCleaned = true;
7054             return this;
7055         },
7056
7057         // private
7058         calcOffsetsTo : function(el){
7059             el = Roo.get(el);
7060             var d = el.dom;
7061             var restorePos = false;
7062             if(el.getStyle('position') == 'static'){
7063                 el.position('relative');
7064                 restorePos = true;
7065             }
7066             var x = 0, y =0;
7067             var op = this.dom;
7068             while(op && op != d && op.tagName != 'HTML'){
7069                 x+= op.offsetLeft;
7070                 y+= op.offsetTop;
7071                 op = op.offsetParent;
7072             }
7073             if(restorePos){
7074                 el.position('static');
7075             }
7076             return [x, y];
7077         },
7078
7079         /**
7080          * Scrolls this element into view within the passed container.
7081          * @param {String/HTMLElement/Element} container (optional) The container element to scroll (defaults to document.body)
7082          * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
7083          * @return {Roo.Element} this
7084          */
7085         scrollIntoView : function(container, hscroll){
7086             var c = Roo.getDom(container) || document.body;
7087             var el = this.dom;
7088
7089             var o = this.calcOffsetsTo(c),
7090                 l = o[0],
7091                 t = o[1],
7092                 b = t+el.offsetHeight,
7093                 r = l+el.offsetWidth;
7094
7095             var ch = c.clientHeight;
7096             var ct = parseInt(c.scrollTop, 10);
7097             var cl = parseInt(c.scrollLeft, 10);
7098             var cb = ct + ch;
7099             var cr = cl + c.clientWidth;
7100
7101             if(t < ct){
7102                 c.scrollTop = t;
7103             }else if(b > cb){
7104                 c.scrollTop = b-ch;
7105             }
7106
7107             if(hscroll !== false){
7108                 if(l < cl){
7109                     c.scrollLeft = l;
7110                 }else if(r > cr){
7111                     c.scrollLeft = r-c.clientWidth;
7112                 }
7113             }
7114             return this;
7115         },
7116
7117         // private
7118         scrollChildIntoView : function(child, hscroll){
7119             Roo.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
7120         },
7121
7122         /**
7123          * Measures the element's content height and updates height to match. Note: this function uses setTimeout so
7124          * the new height may not be available immediately.
7125          * @param {Boolean} animate (optional) Animate the transition (defaults to false)
7126          * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
7127          * @param {Function} onComplete (optional) Function to call when animation completes
7128          * @param {String} easing (optional) Easing method to use (defaults to easeOut)
7129          * @return {Roo.Element} this
7130          */
7131         autoHeight : function(animate, duration, onComplete, easing){
7132             var oldHeight = this.getHeight();
7133             this.clip();
7134             this.setHeight(1); // force clipping
7135             setTimeout(function(){
7136                 var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
7137                 if(!animate){
7138                     this.setHeight(height);
7139                     this.unclip();
7140                     if(typeof onComplete == "function"){
7141                         onComplete();
7142                     }
7143                 }else{
7144                     this.setHeight(oldHeight); // restore original height
7145                     this.setHeight(height, animate, duration, function(){
7146                         this.unclip();
7147                         if(typeof onComplete == "function") onComplete();
7148                     }.createDelegate(this), easing);
7149                 }
7150             }.createDelegate(this), 0);
7151             return this;
7152         },
7153
7154         /**
7155          * Returns true if this element is an ancestor of the passed element
7156          * @param {HTMLElement/String} el The element to check
7157          * @return {Boolean} True if this element is an ancestor of el, else false
7158          */
7159         contains : function(el){
7160             if(!el){return false;}
7161             return D.isAncestor(this.dom, el.dom ? el.dom : el);
7162         },
7163
7164         /**
7165          * Checks whether the element is currently visible using both visibility and display properties.
7166          * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
7167          * @return {Boolean} True if the element is currently visible, else false
7168          */
7169         isVisible : function(deep) {
7170             var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
7171             if(deep !== true || !vis){
7172                 return vis;
7173             }
7174             var p = this.dom.parentNode;
7175             while(p && p.tagName.toLowerCase() != "body"){
7176                 if(!Roo.fly(p, '_isVisible').isVisible()){
7177                     return false;
7178                 }
7179                 p = p.parentNode;
7180             }
7181             return true;
7182         },
7183
7184         /**
7185          * Creates a {@link Roo.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
7186          * @param {String} selector The CSS selector
7187          * @param {Boolean} unique (optional) True to create a unique Roo.Element for each child (defaults to false, which creates a single shared flyweight object)
7188          * @return {CompositeElement/CompositeElementLite} The composite element
7189          */
7190         select : function(selector, unique){
7191             return El.select(selector, unique, this.dom);
7192         },
7193
7194         /**
7195          * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
7196          * @param {String} selector The CSS selector
7197          * @return {Array} An array of the matched nodes
7198          */
7199         query : function(selector, unique){
7200             return Roo.DomQuery.select(selector, this.dom);
7201         },
7202
7203         /**
7204          * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
7205          * @param {String} selector The CSS selector
7206          * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
7207          * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
7208          */
7209         child : function(selector, returnDom){
7210             var n = Roo.DomQuery.selectNode(selector, this.dom);
7211             return returnDom ? n : Roo.get(n);
7212         },
7213
7214         /**
7215          * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
7216          * @param {String} selector The CSS selector
7217          * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
7218          * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
7219          */
7220         down : function(selector, returnDom){
7221             var n = Roo.DomQuery.selectNode(" > " + selector, this.dom);
7222             return returnDom ? n : Roo.get(n);
7223         },
7224
7225         /**
7226          * Initializes a {@link Roo.dd.DD} drag drop object for this element.
7227          * @param {String} group The group the DD object is member of
7228          * @param {Object} config The DD config object
7229          * @param {Object} overrides An object containing methods to override/implement on the DD object
7230          * @return {Roo.dd.DD} The DD object
7231          */
7232         initDD : function(group, config, overrides){
7233             var dd = new Roo.dd.DD(Roo.id(this.dom), group, config);
7234             return Roo.apply(dd, overrides);
7235         },
7236
7237         /**
7238          * Initializes a {@link Roo.dd.DDProxy} object for this element.
7239          * @param {String} group The group the DDProxy object is member of
7240          * @param {Object} config The DDProxy config object
7241          * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
7242          * @return {Roo.dd.DDProxy} The DDProxy object
7243          */
7244         initDDProxy : function(group, config, overrides){
7245             var dd = new Roo.dd.DDProxy(Roo.id(this.dom), group, config);
7246             return Roo.apply(dd, overrides);
7247         },
7248
7249         /**
7250          * Initializes a {@link Roo.dd.DDTarget} object for this element.
7251          * @param {String} group The group the DDTarget object is member of
7252          * @param {Object} config The DDTarget config object
7253          * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
7254          * @return {Roo.dd.DDTarget} The DDTarget object
7255          */
7256         initDDTarget : function(group, config, overrides){
7257             var dd = new Roo.dd.DDTarget(Roo.id(this.dom), group, config);
7258             return Roo.apply(dd, overrides);
7259         },
7260
7261         /**
7262          * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
7263          * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
7264          * @param {Boolean} visible Whether the element is visible
7265          * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7266          * @return {Roo.Element} this
7267          */
7268          setVisible : function(visible, animate){
7269             if(!animate || !A){
7270                 if(this.visibilityMode == El.DISPLAY){
7271                     this.setDisplayed(visible);
7272                 }else{
7273                     this.fixDisplay();
7274                     this.dom.style.visibility = visible ? "visible" : "hidden";
7275                 }
7276             }else{
7277                 // closure for composites
7278                 var dom = this.dom;
7279                 var visMode = this.visibilityMode;
7280                 if(visible){
7281                     this.setOpacity(.01);
7282                     this.setVisible(true);
7283                 }
7284                 this.anim({opacity: { to: (visible?1:0) }},
7285                       this.preanim(arguments, 1),
7286                       null, .35, 'easeIn', function(){
7287                          if(!visible){
7288                              if(visMode == El.DISPLAY){
7289                                  dom.style.display = "none";
7290                              }else{
7291                                  dom.style.visibility = "hidden";
7292                              }
7293                              Roo.get(dom).setOpacity(1);
7294                          }
7295                      });
7296             }
7297             return this;
7298         },
7299
7300         /**
7301          * Returns true if display is not "none"
7302          * @return {Boolean}
7303          */
7304         isDisplayed : function() {
7305             return this.getStyle("display") != "none";
7306         },
7307
7308         /**
7309          * Toggles the element's visibility or display, depending on visibility mode.
7310          * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7311          * @return {Roo.Element} this
7312          */
7313         toggle : function(animate){
7314             this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
7315             return this;
7316         },
7317
7318         /**
7319          * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
7320          * @param {Boolean} value Boolean value to display the element using its default display, or a string to set the display directly
7321          * @return {Roo.Element} this
7322          */
7323         setDisplayed : function(value) {
7324             if(typeof value == "boolean"){
7325                value = value ? this.originalDisplay : "none";
7326             }
7327             this.setStyle("display", value);
7328             return this;
7329         },
7330
7331         /**
7332          * Tries to focus the element. Any exceptions are caught and ignored.
7333          * @return {Roo.Element} this
7334          */
7335         focus : function() {
7336             try{
7337                 this.dom.focus();
7338             }catch(e){}
7339             return this;
7340         },
7341
7342         /**
7343          * Tries to blur the element. Any exceptions are caught and ignored.
7344          * @return {Roo.Element} this
7345          */
7346         blur : function() {
7347             try{
7348                 this.dom.blur();
7349             }catch(e){}
7350             return this;
7351         },
7352
7353         /**
7354          * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
7355          * @param {String/Array} className The CSS class to add, or an array of classes
7356          * @return {Roo.Element} this
7357          */
7358         addClass : function(className){
7359             if(className instanceof Array){
7360                 for(var i = 0, len = className.length; i < len; i++) {
7361                     this.addClass(className[i]);
7362                 }
7363             }else{
7364                 if(className && !this.hasClass(className)){
7365                     this.dom.className = this.dom.className + " " + className;
7366                 }
7367             }
7368             return this;
7369         },
7370
7371         /**
7372          * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
7373          * @param {String/Array} className The CSS class to add, or an array of classes
7374          * @return {Roo.Element} this
7375          */
7376         radioClass : function(className){
7377             var siblings = this.dom.parentNode.childNodes;
7378             for(var i = 0; i < siblings.length; i++) {
7379                 var s = siblings[i];
7380                 if(s.nodeType == 1){
7381                     Roo.get(s).removeClass(className);
7382                 }
7383             }
7384             this.addClass(className);
7385             return this;
7386         },
7387
7388         /**
7389          * Removes one or more CSS classes from the element.
7390          * @param {String/Array} className The CSS class to remove, or an array of classes
7391          * @return {Roo.Element} this
7392          */
7393         removeClass : function(className){
7394             if(!className || !this.dom.className){
7395                 return this;
7396             }
7397             if(className instanceof Array){
7398                 for(var i = 0, len = className.length; i < len; i++) {
7399                     this.removeClass(className[i]);
7400                 }
7401             }else{
7402                 if(this.hasClass(className)){
7403                     var re = this.classReCache[className];
7404                     if (!re) {
7405                        re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
7406                        this.classReCache[className] = re;
7407                     }
7408                     this.dom.className =
7409                         this.dom.className.replace(re, " ");
7410                 }
7411             }
7412             return this;
7413         },
7414
7415         // private
7416         classReCache: {},
7417
7418         /**
7419          * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
7420          * @param {String} className The CSS class to toggle
7421          * @return {Roo.Element} this
7422          */
7423         toggleClass : function(className){
7424             if(this.hasClass(className)){
7425                 this.removeClass(className);
7426             }else{
7427                 this.addClass(className);
7428             }
7429             return this;
7430         },
7431
7432         /**
7433          * Checks if the specified CSS class exists on this element's DOM node.
7434          * @param {String} className The CSS class to check for
7435          * @return {Boolean} True if the class exists, else false
7436          */
7437         hasClass : function(className){
7438             return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
7439         },
7440
7441         /**
7442          * Replaces a CSS class on the element with another.  If the old name does not exist, the new name will simply be added.
7443          * @param {String} oldClassName The CSS class to replace
7444          * @param {String} newClassName The replacement CSS class
7445          * @return {Roo.Element} this
7446          */
7447         replaceClass : function(oldClassName, newClassName){
7448             this.removeClass(oldClassName);
7449             this.addClass(newClassName);
7450             return this;
7451         },
7452
7453         /**
7454          * Returns an object with properties matching the styles requested.
7455          * For example, el.getStyles('color', 'font-size', 'width') might return
7456          * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
7457          * @param {String} style1 A style name
7458          * @param {String} style2 A style name
7459          * @param {String} etc.
7460          * @return {Object} The style object
7461          */
7462         getStyles : function(){
7463             var a = arguments, len = a.length, r = {};
7464             for(var i = 0; i < len; i++){
7465                 r[a[i]] = this.getStyle(a[i]);
7466             }
7467             return r;
7468         },
7469
7470         /**
7471          * Normalizes currentStyle and computedStyle. This is not YUI getStyle, it is an optimised version.
7472          * @param {String} property The style property whose value is returned.
7473          * @return {String} The current value of the style property for this element.
7474          */
7475         getStyle : function(){
7476             return view && view.getComputedStyle ?
7477                 function(prop){
7478                     var el = this.dom, v, cs, camel;
7479                     if(prop == 'float'){
7480                         prop = "cssFloat";
7481                     }
7482                     if(el.style && (v = el.style[prop])){
7483                         return v;
7484                     }
7485                     if(cs = view.getComputedStyle(el, "")){
7486                         if(!(camel = propCache[prop])){
7487                             camel = propCache[prop] = prop.replace(camelRe, camelFn);
7488                         }
7489                         return cs[camel];
7490                     }
7491                     return null;
7492                 } :
7493                 function(prop){
7494                     var el = this.dom, v, cs, camel;
7495                     if(prop == 'opacity'){
7496                         if(typeof el.style.filter == 'string'){
7497                             var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
7498                             if(m){
7499                                 var fv = parseFloat(m[1]);
7500                                 if(!isNaN(fv)){
7501                                     return fv ? fv / 100 : 0;
7502                                 }
7503                             }
7504                         }
7505                         return 1;
7506                     }else if(prop == 'float'){
7507                         prop = "styleFloat";
7508                     }
7509                     if(!(camel = propCache[prop])){
7510                         camel = propCache[prop] = prop.replace(camelRe, camelFn);
7511                     }
7512                     if(v = el.style[camel]){
7513                         return v;
7514                     }
7515                     if(cs = el.currentStyle){
7516                         return cs[camel];
7517                     }
7518                     return null;
7519                 };
7520         }(),
7521
7522         /**
7523          * Wrapper for setting style properties, also takes single object parameter of multiple styles.
7524          * @param {String/Object} property The style property to be set, or an object of multiple styles.
7525          * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
7526          * @return {Roo.Element} this
7527          */
7528         setStyle : function(prop, value){
7529             if(typeof prop == "string"){
7530                 
7531                 if (prop == 'float') {
7532                     this.setStyle(Roo.isIE ? 'styleFloat'  : 'cssFloat', value);
7533                     return this;
7534                 }
7535                 
7536                 var camel;
7537                 if(!(camel = propCache[prop])){
7538                     camel = propCache[prop] = prop.replace(camelRe, camelFn);
7539                 }
7540                 
7541                 if(camel == 'opacity') {
7542                     this.setOpacity(value);
7543                 }else{
7544                     this.dom.style[camel] = value;
7545                 }
7546             }else{
7547                 for(var style in prop){
7548                     if(typeof prop[style] != "function"){
7549                        this.setStyle(style, prop[style]);
7550                     }
7551                 }
7552             }
7553             return this;
7554         },
7555
7556         /**
7557          * More flexible version of {@link #setStyle} for setting style properties.
7558          * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
7559          * a function which returns such a specification.
7560          * @return {Roo.Element} this
7561          */
7562         applyStyles : function(style){
7563             Roo.DomHelper.applyStyles(this.dom, style);
7564             return this;
7565         },
7566
7567         /**
7568           * 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).
7569           * @return {Number} The X position of the element
7570           */
7571         getX : function(){
7572             return D.getX(this.dom);
7573         },
7574
7575         /**
7576           * 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).
7577           * @return {Number} The Y position of the element
7578           */
7579         getY : function(){
7580             return D.getY(this.dom);
7581         },
7582
7583         /**
7584           * 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).
7585           * @return {Array} The XY position of the element
7586           */
7587         getXY : function(){
7588             return D.getXY(this.dom);
7589         },
7590
7591         /**
7592          * 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).
7593          * @param {Number} The X position of the element
7594          * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7595          * @return {Roo.Element} this
7596          */
7597         setX : function(x, animate){
7598             if(!animate || !A){
7599                 D.setX(this.dom, x);
7600             }else{
7601                 this.setXY([x, this.getY()], this.preanim(arguments, 1));
7602             }
7603             return this;
7604         },
7605
7606         /**
7607          * 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).
7608          * @param {Number} The Y position of the element
7609          * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7610          * @return {Roo.Element} this
7611          */
7612         setY : function(y, animate){
7613             if(!animate || !A){
7614                 D.setY(this.dom, y);
7615             }else{
7616                 this.setXY([this.getX(), y], this.preanim(arguments, 1));
7617             }
7618             return this;
7619         },
7620
7621         /**
7622          * Sets the element's left position directly using CSS style (instead of {@link #setX}).
7623          * @param {String} left The left CSS property value
7624          * @return {Roo.Element} this
7625          */
7626         setLeft : function(left){
7627             this.setStyle("left", this.addUnits(left));
7628             return this;
7629         },
7630
7631         /**
7632          * Sets the element's top position directly using CSS style (instead of {@link #setY}).
7633          * @param {String} top The top CSS property value
7634          * @return {Roo.Element} this
7635          */
7636         setTop : function(top){
7637             this.setStyle("top", this.addUnits(top));
7638             return this;
7639         },
7640
7641         /**
7642          * Sets the element's CSS right style.
7643          * @param {String} right The right CSS property value
7644          * @return {Roo.Element} this
7645          */
7646         setRight : function(right){
7647             this.setStyle("right", this.addUnits(right));
7648             return this;
7649         },
7650
7651         /**
7652          * Sets the element's CSS bottom style.
7653          * @param {String} bottom The bottom CSS property value
7654          * @return {Roo.Element} this
7655          */
7656         setBottom : function(bottom){
7657             this.setStyle("bottom", this.addUnits(bottom));
7658             return this;
7659         },
7660
7661         /**
7662          * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7663          * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7664          * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
7665          * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7666          * @return {Roo.Element} this
7667          */
7668         setXY : function(pos, animate){
7669             if(!animate || !A){
7670                 D.setXY(this.dom, pos);
7671             }else{
7672                 this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
7673             }
7674             return this;
7675         },
7676
7677         /**
7678          * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7679          * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7680          * @param {Number} x X value for new position (coordinates are page-based)
7681          * @param {Number} y Y value for new position (coordinates are page-based)
7682          * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7683          * @return {Roo.Element} this
7684          */
7685         setLocation : function(x, y, animate){
7686             this.setXY([x, y], this.preanim(arguments, 2));
7687             return this;
7688         },
7689
7690         /**
7691          * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7692          * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7693          * @param {Number} x X value for new position (coordinates are page-based)
7694          * @param {Number} y Y value for new position (coordinates are page-based)
7695          * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7696          * @return {Roo.Element} this
7697          */
7698         moveTo : function(x, y, animate){
7699             this.setXY([x, y], this.preanim(arguments, 2));
7700             return this;
7701         },
7702
7703         /**
7704          * Returns the region of the given element.
7705          * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
7706          * @return {Region} A Roo.lib.Region containing "top, left, bottom, right" member data.
7707          */
7708         getRegion : function(){
7709             return D.getRegion(this.dom);
7710         },
7711
7712         /**
7713          * Returns the offset height of the element
7714          * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
7715          * @return {Number} The element's height
7716          */
7717         getHeight : function(contentHeight){
7718             var h = this.dom.offsetHeight || 0;
7719             return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
7720         },
7721
7722         /**
7723          * Returns the offset width of the element
7724          * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
7725          * @return {Number} The element's width
7726          */
7727         getWidth : function(contentWidth){
7728             var w = this.dom.offsetWidth || 0;
7729             return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
7730         },
7731
7732         /**
7733          * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
7734          * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
7735          * if a height has not been set using CSS.
7736          * @return {Number}
7737          */
7738         getComputedHeight : function(){
7739             var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
7740             if(!h){
7741                 h = parseInt(this.getStyle('height'), 10) || 0;
7742                 if(!this.isBorderBox()){
7743                     h += this.getFrameWidth('tb');
7744                 }
7745             }
7746             return h;
7747         },
7748
7749         /**
7750          * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
7751          * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
7752          * if a width has not been set using CSS.
7753          * @return {Number}
7754          */
7755         getComputedWidth : function(){
7756             var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
7757             if(!w){
7758                 w = parseInt(this.getStyle('width'), 10) || 0;
7759                 if(!this.isBorderBox()){
7760                     w += this.getFrameWidth('lr');
7761                 }
7762             }
7763             return w;
7764         },
7765
7766         /**
7767          * Returns the size of the element.
7768          * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
7769          * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
7770          */
7771         getSize : function(contentSize){
7772             return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
7773         },
7774
7775         /**
7776          * Returns the width and height of the viewport.
7777          * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)}
7778          */
7779         getViewSize : function(){
7780             var d = this.dom, doc = document, aw = 0, ah = 0;
7781             if(d == doc || d == doc.body){
7782                 return {width : D.getViewWidth(), height: D.getViewHeight()};
7783             }else{
7784                 return {
7785                     width : d.clientWidth,
7786                     height: d.clientHeight
7787                 };
7788             }
7789         },
7790
7791         /**
7792          * Returns the value of the "value" attribute
7793          * @param {Boolean} asNumber true to parse the value as a number
7794          * @return {String/Number}
7795          */
7796         getValue : function(asNumber){
7797             return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
7798         },
7799
7800         // private
7801         adjustWidth : function(width){
7802             if(typeof width == "number"){
7803                 if(this.autoBoxAdjust && !this.isBorderBox()){
7804                    width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
7805                 }
7806                 if(width < 0){
7807                     width = 0;
7808                 }
7809             }
7810             return width;
7811         },
7812
7813         // private
7814         adjustHeight : function(height){
7815             if(typeof height == "number"){
7816                if(this.autoBoxAdjust && !this.isBorderBox()){
7817                    height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
7818                }
7819                if(height < 0){
7820                    height = 0;
7821                }
7822             }
7823             return height;
7824         },
7825
7826         /**
7827          * Set the width of the element
7828          * @param {Number} width The new width
7829          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7830          * @return {Roo.Element} this
7831          */
7832         setWidth : function(width, animate){
7833             width = this.adjustWidth(width);
7834             if(!animate || !A){
7835                 this.dom.style.width = this.addUnits(width);
7836             }else{
7837                 this.anim({width: {to: width}}, this.preanim(arguments, 1));
7838             }
7839             return this;
7840         },
7841
7842         /**
7843          * Set the height of the element
7844          * @param {Number} height The new height
7845          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7846          * @return {Roo.Element} this
7847          */
7848          setHeight : function(height, animate){
7849             height = this.adjustHeight(height);
7850             if(!animate || !A){
7851                 this.dom.style.height = this.addUnits(height);
7852             }else{
7853                 this.anim({height: {to: height}}, this.preanim(arguments, 1));
7854             }
7855             return this;
7856         },
7857
7858         /**
7859          * Set the size of the element. If animation is true, both width an height will be animated concurrently.
7860          * @param {Number} width The new width
7861          * @param {Number} height The new height
7862          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7863          * @return {Roo.Element} this
7864          */
7865          setSize : function(width, height, animate){
7866             if(typeof width == "object"){ // in case of object from getSize()
7867                 height = width.height; width = width.width;
7868             }
7869             width = this.adjustWidth(width); height = this.adjustHeight(height);
7870             if(!animate || !A){
7871                 this.dom.style.width = this.addUnits(width);
7872                 this.dom.style.height = this.addUnits(height);
7873             }else{
7874                 this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
7875             }
7876             return this;
7877         },
7878
7879         /**
7880          * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
7881          * @param {Number} x X value for new position (coordinates are page-based)
7882          * @param {Number} y Y value for new position (coordinates are page-based)
7883          * @param {Number} width The new width
7884          * @param {Number} height The new height
7885          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7886          * @return {Roo.Element} this
7887          */
7888         setBounds : function(x, y, width, height, animate){
7889             if(!animate || !A){
7890                 this.setSize(width, height);
7891                 this.setLocation(x, y);
7892             }else{
7893                 width = this.adjustWidth(width); height = this.adjustHeight(height);
7894                 this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
7895                               this.preanim(arguments, 4), 'motion');
7896             }
7897             return this;
7898         },
7899
7900         /**
7901          * 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.
7902          * @param {Roo.lib.Region} region The region to fill
7903          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7904          * @return {Roo.Element} this
7905          */
7906         setRegion : function(region, animate){
7907             this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
7908             return this;
7909         },
7910
7911         /**
7912          * Appends an event handler
7913          *
7914          * @param {String}   eventName     The type of event to append
7915          * @param {Function} fn        The method the event invokes
7916          * @param {Object} scope       (optional) The scope (this object) of the fn
7917          * @param {Object}   options   (optional)An object with standard {@link Roo.EventManager#addListener} options
7918          */
7919         addListener : function(eventName, fn, scope, options){
7920             if (this.dom) {
7921                 Roo.EventManager.on(this.dom,  eventName, fn, scope || this, options);
7922             }
7923         },
7924
7925         /**
7926          * Removes an event handler from this element
7927          * @param {String} eventName the type of event to remove
7928          * @param {Function} fn the method the event invokes
7929          * @return {Roo.Element} this
7930          */
7931         removeListener : function(eventName, fn){
7932             Roo.EventManager.removeListener(this.dom,  eventName, fn);
7933             return this;
7934         },
7935
7936         /**
7937          * Removes all previous added listeners from this element
7938          * @return {Roo.Element} this
7939          */
7940         removeAllListeners : function(){
7941             E.purgeElement(this.dom);
7942             return this;
7943         },
7944
7945         relayEvent : function(eventName, observable){
7946             this.on(eventName, function(e){
7947                 observable.fireEvent(eventName, e);
7948             });
7949         },
7950
7951         /**
7952          * Set the opacity of the element
7953          * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
7954          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7955          * @return {Roo.Element} this
7956          */
7957          setOpacity : function(opacity, animate){
7958             if(!animate || !A){
7959                 var s = this.dom.style;
7960                 if(Roo.isIE){
7961                     s.zoom = 1;
7962                     s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
7963                                (opacity == 1 ? "" : "alpha(opacity=" + opacity * 100 + ")");
7964                 }else{
7965                     s.opacity = opacity;
7966                 }
7967             }else{
7968                 this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
7969             }
7970             return this;
7971         },
7972
7973         /**
7974          * Gets the left X coordinate
7975          * @param {Boolean} local True to get the local css position instead of page coordinate
7976          * @return {Number}
7977          */
7978         getLeft : function(local){
7979             if(!local){
7980                 return this.getX();
7981             }else{
7982                 return parseInt(this.getStyle("left"), 10) || 0;
7983             }
7984         },
7985
7986         /**
7987          * Gets the right X coordinate of the element (element X position + element width)
7988          * @param {Boolean} local True to get the local css position instead of page coordinate
7989          * @return {Number}
7990          */
7991         getRight : function(local){
7992             if(!local){
7993                 return this.getX() + this.getWidth();
7994             }else{
7995                 return (this.getLeft(true) + this.getWidth()) || 0;
7996             }
7997         },
7998
7999         /**
8000          * Gets the top Y coordinate
8001          * @param {Boolean} local True to get the local css position instead of page coordinate
8002          * @return {Number}
8003          */
8004         getTop : function(local) {
8005             if(!local){
8006                 return this.getY();
8007             }else{
8008                 return parseInt(this.getStyle("top"), 10) || 0;
8009             }
8010         },
8011
8012         /**
8013          * Gets the bottom Y coordinate of the element (element Y position + element height)
8014          * @param {Boolean} local True to get the local css position instead of page coordinate
8015          * @return {Number}
8016          */
8017         getBottom : function(local){
8018             if(!local){
8019                 return this.getY() + this.getHeight();
8020             }else{
8021                 return (this.getTop(true) + this.getHeight()) || 0;
8022             }
8023         },
8024
8025         /**
8026         * Initializes positioning on this element. If a desired position is not passed, it will make the
8027         * the element positioned relative IF it is not already positioned.
8028         * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
8029         * @param {Number} zIndex (optional) The zIndex to apply
8030         * @param {Number} x (optional) Set the page X position
8031         * @param {Number} y (optional) Set the page Y position
8032         */
8033         position : function(pos, zIndex, x, y){
8034             if(!pos){
8035                if(this.getStyle('position') == 'static'){
8036                    this.setStyle('position', 'relative');
8037                }
8038             }else{
8039                 this.setStyle("position", pos);
8040             }
8041             if(zIndex){
8042                 this.setStyle("z-index", zIndex);
8043             }
8044             if(x !== undefined && y !== undefined){
8045                 this.setXY([x, y]);
8046             }else if(x !== undefined){
8047                 this.setX(x);
8048             }else if(y !== undefined){
8049                 this.setY(y);
8050             }
8051         },
8052
8053         /**
8054         * Clear positioning back to the default when the document was loaded
8055         * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
8056         * @return {Roo.Element} this
8057          */
8058         clearPositioning : function(value){
8059             value = value ||'';
8060             this.setStyle({
8061                 "left": value,
8062                 "right": value,
8063                 "top": value,
8064                 "bottom": value,
8065                 "z-index": "",
8066                 "position" : "static"
8067             });
8068             return this;
8069         },
8070
8071         /**
8072         * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
8073         * snapshot before performing an update and then restoring the element.
8074         * @return {Object}
8075         */
8076         getPositioning : function(){
8077             var l = this.getStyle("left");
8078             var t = this.getStyle("top");
8079             return {
8080                 "position" : this.getStyle("position"),
8081                 "left" : l,
8082                 "right" : l ? "" : this.getStyle("right"),
8083                 "top" : t,
8084                 "bottom" : t ? "" : this.getStyle("bottom"),
8085                 "z-index" : this.getStyle("z-index")
8086             };
8087         },
8088
8089         /**
8090          * Gets the width of the border(s) for the specified side(s)
8091          * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
8092          * passing lr would get the border (l)eft width + the border (r)ight width.
8093          * @return {Number} The width of the sides passed added together
8094          */
8095         getBorderWidth : function(side){
8096             return this.addStyles(side, El.borders);
8097         },
8098
8099         /**
8100          * Gets the width of the padding(s) for the specified side(s)
8101          * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
8102          * passing lr would get the padding (l)eft + the padding (r)ight.
8103          * @return {Number} The padding of the sides passed added together
8104          */
8105         getPadding : function(side){
8106             return this.addStyles(side, El.paddings);
8107         },
8108
8109         /**
8110         * Set positioning with an object returned by getPositioning().
8111         * @param {Object} posCfg
8112         * @return {Roo.Element} this
8113          */
8114         setPositioning : function(pc){
8115             this.applyStyles(pc);
8116             if(pc.right == "auto"){
8117                 this.dom.style.right = "";
8118             }
8119             if(pc.bottom == "auto"){
8120                 this.dom.style.bottom = "";
8121             }
8122             return this;
8123         },
8124
8125         // private
8126         fixDisplay : function(){
8127             if(this.getStyle("display") == "none"){
8128                 this.setStyle("visibility", "hidden");
8129                 this.setStyle("display", this.originalDisplay); // first try reverting to default
8130                 if(this.getStyle("display") == "none"){ // if that fails, default to block
8131                     this.setStyle("display", "block");
8132                 }
8133             }
8134         },
8135
8136         /**
8137          * Quick set left and top adding default units
8138          * @param {String} left The left CSS property value
8139          * @param {String} top The top CSS property value
8140          * @return {Roo.Element} this
8141          */
8142          setLeftTop : function(left, top){
8143             this.dom.style.left = this.addUnits(left);
8144             this.dom.style.top = this.addUnits(top);
8145             return this;
8146         },
8147
8148         /**
8149          * Move this element relative to its current position.
8150          * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
8151          * @param {Number} distance How far to move the element in pixels
8152          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8153          * @return {Roo.Element} this
8154          */
8155          move : function(direction, distance, animate){
8156             var xy = this.getXY();
8157             direction = direction.toLowerCase();
8158             switch(direction){
8159                 case "l":
8160                 case "left":
8161                     this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
8162                     break;
8163                case "r":
8164                case "right":
8165                     this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
8166                     break;
8167                case "t":
8168                case "top":
8169                case "up":
8170                     this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
8171                     break;
8172                case "b":
8173                case "bottom":
8174                case "down":
8175                     this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
8176                     break;
8177             }
8178             return this;
8179         },
8180
8181         /**
8182          *  Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
8183          * @return {Roo.Element} this
8184          */
8185         clip : function(){
8186             if(!this.isClipped){
8187                this.isClipped = true;
8188                this.originalClip = {
8189                    "o": this.getStyle("overflow"),
8190                    "x": this.getStyle("overflow-x"),
8191                    "y": this.getStyle("overflow-y")
8192                };
8193                this.setStyle("overflow", "hidden");
8194                this.setStyle("overflow-x", "hidden");
8195                this.setStyle("overflow-y", "hidden");
8196             }
8197             return this;
8198         },
8199
8200         /**
8201          *  Return clipping (overflow) to original clipping before clip() was called
8202          * @return {Roo.Element} this
8203          */
8204         unclip : function(){
8205             if(this.isClipped){
8206                 this.isClipped = false;
8207                 var o = this.originalClip;
8208                 if(o.o){this.setStyle("overflow", o.o);}
8209                 if(o.x){this.setStyle("overflow-x", o.x);}
8210                 if(o.y){this.setStyle("overflow-y", o.y);}
8211             }
8212             return this;
8213         },
8214
8215
8216         /**
8217          * Gets the x,y coordinates specified by the anchor position on the element.
8218          * @param {String} anchor (optional) The specified anchor position (defaults to "c").  See {@link #alignTo} for details on supported anchor positions.
8219          * @param {Object} size (optional) An object containing the size to use for calculating anchor position
8220          *                       {width: (target width), height: (target height)} (defaults to the element's current size)
8221          * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead of page coordinates
8222          * @return {Array} [x, y] An array containing the element's x and y coordinates
8223          */
8224         getAnchorXY : function(anchor, local, s){
8225             //Passing a different size is useful for pre-calculating anchors,
8226             //especially for anchored animations that change the el size.
8227
8228             var w, h, vp = false;
8229             if(!s){
8230                 var d = this.dom;
8231                 if(d == document.body || d == document){
8232                     vp = true;
8233                     w = D.getViewWidth(); h = D.getViewHeight();
8234                 }else{
8235                     w = this.getWidth(); h = this.getHeight();
8236                 }
8237             }else{
8238                 w = s.width;  h = s.height;
8239             }
8240             var x = 0, y = 0, r = Math.round;
8241             switch((anchor || "tl").toLowerCase()){
8242                 case "c":
8243                     x = r(w*.5);
8244                     y = r(h*.5);
8245                 break;
8246                 case "t":
8247                     x = r(w*.5);
8248                     y = 0;
8249                 break;
8250                 case "l":
8251                     x = 0;
8252                     y = r(h*.5);
8253                 break;
8254                 case "r":
8255                     x = w;
8256                     y = r(h*.5);
8257                 break;
8258                 case "b":
8259                     x = r(w*.5);
8260                     y = h;
8261                 break;
8262                 case "tl":
8263                     x = 0;
8264                     y = 0;
8265                 break;
8266                 case "bl":
8267                     x = 0;
8268                     y = h;
8269                 break;
8270                 case "br":
8271                     x = w;
8272                     y = h;
8273                 break;
8274                 case "tr":
8275                     x = w;
8276                     y = 0;
8277                 break;
8278             }
8279             if(local === true){
8280                 return [x, y];
8281             }
8282             if(vp){
8283                 var sc = this.getScroll();
8284                 return [x + sc.left, y + sc.top];
8285             }
8286             //Add the element's offset xy
8287             var o = this.getXY();
8288             return [x+o[0], y+o[1]];
8289         },
8290
8291         /**
8292          * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
8293          * supported position values.
8294          * @param {String/HTMLElement/Roo.Element} element The element to align to.
8295          * @param {String} position The position to align to.
8296          * @param {Array} offsets (optional) Offset the positioning by [x, y]
8297          * @return {Array} [x, y]
8298          */
8299         getAlignToXY : function(el, p, o){
8300             el = Roo.get(el);
8301             var d = this.dom;
8302             if(!el.dom){
8303                 throw "Element.alignTo with an element that doesn't exist";
8304             }
8305             var c = false; //constrain to viewport
8306             var p1 = "", p2 = "";
8307             o = o || [0,0];
8308
8309             if(!p){
8310                 p = "tl-bl";
8311             }else if(p == "?"){
8312                 p = "tl-bl?";
8313             }else if(p.indexOf("-") == -1){
8314                 p = "tl-" + p;
8315             }
8316             p = p.toLowerCase();
8317             var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
8318             if(!m){
8319                throw "Element.alignTo with an invalid alignment " + p;
8320             }
8321             p1 = m[1]; p2 = m[2]; c = !!m[3];
8322
8323             //Subtract the aligned el's internal xy from the target's offset xy
8324             //plus custom offset to get the aligned el's new offset xy
8325             var a1 = this.getAnchorXY(p1, true);
8326             var a2 = el.getAnchorXY(p2, false);
8327             var x = a2[0] - a1[0] + o[0];
8328             var y = a2[1] - a1[1] + o[1];
8329             if(c){
8330                 //constrain the aligned el to viewport if necessary
8331                 var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
8332                 // 5px of margin for ie
8333                 var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5;
8334
8335                 //If we are at a viewport boundary and the aligned el is anchored on a target border that is
8336                 //perpendicular to the vp border, allow the aligned el to slide on that border,
8337                 //otherwise swap the aligned el to the opposite border of the target.
8338                 var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
8339                var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
8340                var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t"));
8341                var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
8342
8343                var doc = document;
8344                var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
8345                var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
8346
8347                if((x+w) > dw + scrollX){
8348                     x = swapX ? r.left-w : dw+scrollX-w;
8349                 }
8350                if(x < scrollX){
8351                    x = swapX ? r.right : scrollX;
8352                }
8353                if((y+h) > dh + scrollY){
8354                     y = swapY ? r.top-h : dh+scrollY-h;
8355                 }
8356                if (y < scrollY){
8357                    y = swapY ? r.bottom : scrollY;
8358                }
8359             }
8360             return [x,y];
8361         },
8362
8363         // private
8364         getConstrainToXY : function(){
8365             var os = {top:0, left:0, bottom:0, right: 0};
8366
8367             return function(el, local, offsets, proposedXY){
8368                 el = Roo.get(el);
8369                 offsets = offsets ? Roo.applyIf(offsets, os) : os;
8370
8371                 var vw, vh, vx = 0, vy = 0;
8372                 if(el.dom == document.body || el.dom == document){
8373                     vw = Roo.lib.Dom.getViewWidth();
8374                     vh = Roo.lib.Dom.getViewHeight();
8375                 }else{
8376                     vw = el.dom.clientWidth;
8377                     vh = el.dom.clientHeight;
8378                     if(!local){
8379                         var vxy = el.getXY();
8380                         vx = vxy[0];
8381                         vy = vxy[1];
8382                     }
8383                 }
8384
8385                 var s = el.getScroll();
8386
8387                 vx += offsets.left + s.left;
8388                 vy += offsets.top + s.top;
8389
8390                 vw -= offsets.right;
8391                 vh -= offsets.bottom;
8392
8393                 var vr = vx+vw;
8394                 var vb = vy+vh;
8395
8396                 var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
8397                 var x = xy[0], y = xy[1];
8398                 var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
8399
8400                 // only move it if it needs it
8401                 var moved = false;
8402
8403                 // first validate right/bottom
8404                 if((x + w) > vr){
8405                     x = vr - w;
8406                     moved = true;
8407                 }
8408                 if((y + h) > vb){
8409                     y = vb - h;
8410                     moved = true;
8411                 }
8412                 // then make sure top/left isn't negative
8413                 if(x < vx){
8414                     x = vx;
8415                     moved = true;
8416                 }
8417                 if(y < vy){
8418                     y = vy;
8419                     moved = true;
8420                 }
8421                 return moved ? [x, y] : false;
8422             };
8423         }(),
8424
8425         // private
8426         adjustForConstraints : function(xy, parent, offsets){
8427             return this.getConstrainToXY(parent || document, false, offsets, xy) ||  xy;
8428         },
8429
8430         /**
8431          * Aligns this element with another element relative to the specified anchor points. If the other element is the
8432          * document it aligns it to the viewport.
8433          * The position parameter is optional, and can be specified in any one of the following formats:
8434          * <ul>
8435          *   <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
8436          *   <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
8437          *       The element being aligned will position its top-left corner (tl) to that point.  <i>This method has been
8438          *       deprecated in favor of the newer two anchor syntax below</i>.</li>
8439          *   <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
8440          *       element's anchor point, and the second value is used as the target's anchor point.</li>
8441          * </ul>
8442          * In addition to the anchor points, the position parameter also supports the "?" character.  If "?" is passed at the end of
8443          * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
8444          * the viewport if necessary.  Note that the element being aligned might be swapped to align to a different position than
8445          * that specified in order to enforce the viewport constraints.
8446          * Following are all of the supported anchor positions:
8447     <pre>
8448     Value  Description
8449     -----  -----------------------------
8450     tl     The top left corner (default)
8451     t      The center of the top edge
8452     tr     The top right corner
8453     l      The center of the left edge
8454     c      In the center of the element
8455     r      The center of the right edge
8456     bl     The bottom left corner
8457     b      The center of the bottom edge
8458     br     The bottom right corner
8459     </pre>
8460     Example Usage:
8461     <pre><code>
8462     // align el to other-el using the default positioning ("tl-bl", non-constrained)
8463     el.alignTo("other-el");
8464
8465     // align the top left corner of el with the top right corner of other-el (constrained to viewport)
8466     el.alignTo("other-el", "tr?");
8467
8468     // align the bottom right corner of el with the center left edge of other-el
8469     el.alignTo("other-el", "br-l?");
8470
8471     // align the center of el with the bottom left corner of other-el and
8472     // adjust the x position by -6 pixels (and the y position by 0)
8473     el.alignTo("other-el", "c-bl", [-6, 0]);
8474     </code></pre>
8475          * @param {String/HTMLElement/Roo.Element} element The element to align to.
8476          * @param {String} position The position to align to.
8477          * @param {Array} offsets (optional) Offset the positioning by [x, y]
8478          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8479          * @return {Roo.Element} this
8480          */
8481         alignTo : function(element, position, offsets, animate){
8482             var xy = this.getAlignToXY(element, position, offsets);
8483             this.setXY(xy, this.preanim(arguments, 3));
8484             return this;
8485         },
8486
8487         /**
8488          * Anchors an element to another element and realigns it when the window is resized.
8489          * @param {String/HTMLElement/Roo.Element} element The element to align to.
8490          * @param {String} position The position to align to.
8491          * @param {Array} offsets (optional) Offset the positioning by [x, y]
8492          * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
8493          * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
8494          * is a number, it is used as the buffer delay (defaults to 50ms).
8495          * @param {Function} callback The function to call after the animation finishes
8496          * @return {Roo.Element} this
8497          */
8498         anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
8499             var action = function(){
8500                 this.alignTo(el, alignment, offsets, animate);
8501                 Roo.callback(callback, this);
8502             };
8503             Roo.EventManager.onWindowResize(action, this);
8504             var tm = typeof monitorScroll;
8505             if(tm != 'undefined'){
8506                 Roo.EventManager.on(window, 'scroll', action, this,
8507                     {buffer: tm == 'number' ? monitorScroll : 50});
8508             }
8509             action.call(this); // align immediately
8510             return this;
8511         },
8512         /**
8513          * Clears any opacity settings from this element. Required in some cases for IE.
8514          * @return {Roo.Element} this
8515          */
8516         clearOpacity : function(){
8517             if (window.ActiveXObject) {
8518                 if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
8519                     this.dom.style.filter = "";
8520                 }
8521             } else {
8522                 this.dom.style.opacity = "";
8523                 this.dom.style["-moz-opacity"] = "";
8524                 this.dom.style["-khtml-opacity"] = "";
8525             }
8526             return this;
8527         },
8528
8529         /**
8530          * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
8531          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8532          * @return {Roo.Element} this
8533          */
8534         hide : function(animate){
8535             this.setVisible(false, this.preanim(arguments, 0));
8536             return this;
8537         },
8538
8539         /**
8540         * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
8541         * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8542          * @return {Roo.Element} this
8543          */
8544         show : function(animate){
8545             this.setVisible(true, this.preanim(arguments, 0));
8546             return this;
8547         },
8548
8549         /**
8550          * @private Test if size has a unit, otherwise appends the default
8551          */
8552         addUnits : function(size){
8553             return Roo.Element.addUnits(size, this.defaultUnit);
8554         },
8555
8556         /**
8557          * Temporarily enables offsets (width,height,x,y) for an element with display:none, use endMeasure() when done.
8558          * @return {Roo.Element} this
8559          */
8560         beginMeasure : function(){
8561             var el = this.dom;
8562             if(el.offsetWidth || el.offsetHeight){
8563                 return this; // offsets work already
8564             }
8565             var changed = [];
8566             var p = this.dom, b = document.body; // start with this element
8567             while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){
8568                 var pe = Roo.get(p);
8569                 if(pe.getStyle('display') == 'none'){
8570                     changed.push({el: p, visibility: pe.getStyle("visibility")});
8571                     p.style.visibility = "hidden";
8572                     p.style.display = "block";
8573                 }
8574                 p = p.parentNode;
8575             }
8576             this._measureChanged = changed;
8577             return this;
8578
8579         },
8580
8581         /**
8582          * Restores displays to before beginMeasure was called
8583          * @return {Roo.Element} this
8584          */
8585         endMeasure : function(){
8586             var changed = this._measureChanged;
8587             if(changed){
8588                 for(var i = 0, len = changed.length; i < len; i++) {
8589                     var r = changed[i];
8590                     r.el.style.visibility = r.visibility;
8591                     r.el.style.display = "none";
8592                 }
8593                 this._measureChanged = null;
8594             }
8595             return this;
8596         },
8597
8598         /**
8599         * Update the innerHTML of this element, optionally searching for and processing scripts
8600         * @param {String} html The new HTML
8601         * @param {Boolean} loadScripts (optional) true to look for and process scripts
8602         * @param {Function} callback For async script loading you can be noticed when the update completes
8603         * @return {Roo.Element} this
8604          */
8605         update : function(html, loadScripts, callback){
8606             if(typeof html == "undefined"){
8607                 html = "";
8608             }
8609             if(loadScripts !== true){
8610                 this.dom.innerHTML = html;
8611                 if(typeof callback == "function"){
8612                     callback();
8613                 }
8614                 return this;
8615             }
8616             var id = Roo.id();
8617             var dom = this.dom;
8618
8619             html += '<span id="' + id + '"></span>';
8620
8621             E.onAvailable(id, function(){
8622                 var hd = document.getElementsByTagName("head")[0];
8623                 var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
8624                 var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
8625                 var typeRe = /\stype=([\'\"])(.*?)\1/i;
8626
8627                 var match;
8628                 while(match = re.exec(html)){
8629                     var attrs = match[1];
8630                     var srcMatch = attrs ? attrs.match(srcRe) : false;
8631                     if(srcMatch && srcMatch[2]){
8632                        var s = document.createElement("script");
8633                        s.src = srcMatch[2];
8634                        var typeMatch = attrs.match(typeRe);
8635                        if(typeMatch && typeMatch[2]){
8636                            s.type = typeMatch[2];
8637                        }
8638                        hd.appendChild(s);
8639                     }else if(match[2] && match[2].length > 0){
8640                         if(window.execScript) {
8641                            window.execScript(match[2]);
8642                         } else {
8643                             /**
8644                              * eval:var:id
8645                              * eval:var:dom
8646                              * eval:var:html
8647                              * 
8648                              */
8649                            window.eval(match[2]);
8650                         }
8651                     }
8652                 }
8653                 var el = document.getElementById(id);
8654                 if(el){el.parentNode.removeChild(el);}
8655                 if(typeof callback == "function"){
8656                     callback();
8657                 }
8658             });
8659             dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
8660             return this;
8661         },
8662
8663         /**
8664          * Direct access to the UpdateManager update() method (takes the same parameters).
8665          * @param {String/Function} url The url for this request or a function to call to get the url
8666          * @param {String/Object} params (optional) The parameters to pass as either a url encoded string "param1=1&amp;param2=2" or an object {param1: 1, param2: 2}
8667          * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
8668          * @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.
8669          * @return {Roo.Element} this
8670          */
8671         load : function(){
8672             var um = this.getUpdateManager();
8673             um.update.apply(um, arguments);
8674             return this;
8675         },
8676
8677         /**
8678         * Gets this element's UpdateManager
8679         * @return {Roo.UpdateManager} The UpdateManager
8680         */
8681         getUpdateManager : function(){
8682             if(!this.updateManager){
8683                 this.updateManager = new Roo.UpdateManager(this);
8684             }
8685             return this.updateManager;
8686         },
8687
8688         /**
8689          * Disables text selection for this element (normalized across browsers)
8690          * @return {Roo.Element} this
8691          */
8692         unselectable : function(){
8693             this.dom.unselectable = "on";
8694             this.swallowEvent("selectstart", true);
8695             this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
8696             this.addClass("x-unselectable");
8697             return this;
8698         },
8699
8700         /**
8701         * Calculates the x, y to center this element on the screen
8702         * @return {Array} The x, y values [x, y]
8703         */
8704         getCenterXY : function(){
8705             return this.getAlignToXY(document, 'c-c');
8706         },
8707
8708         /**
8709         * Centers the Element in either the viewport, or another Element.
8710         * @param {String/HTMLElement/Roo.Element} centerIn (optional) The element in which to center the element.
8711         */
8712         center : function(centerIn){
8713             this.alignTo(centerIn || document, 'c-c');
8714             return this;
8715         },
8716
8717         /**
8718          * Tests various css rules/browsers to determine if this element uses a border box
8719          * @return {Boolean}
8720          */
8721         isBorderBox : function(){
8722             return noBoxAdjust[this.dom.tagName.toLowerCase()] || Roo.isBorderBox;
8723         },
8724
8725         /**
8726          * Return a box {x, y, width, height} that can be used to set another elements
8727          * size/location to match this element.
8728          * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
8729          * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
8730          * @return {Object} box An object in the format {x, y, width, height}
8731          */
8732         getBox : function(contentBox, local){
8733             var xy;
8734             if(!local){
8735                 xy = this.getXY();
8736             }else{
8737                 var left = parseInt(this.getStyle("left"), 10) || 0;
8738                 var top = parseInt(this.getStyle("top"), 10) || 0;
8739                 xy = [left, top];
8740             }
8741             var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
8742             if(!contentBox){
8743                 bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
8744             }else{
8745                 var l = this.getBorderWidth("l")+this.getPadding("l");
8746                 var r = this.getBorderWidth("r")+this.getPadding("r");
8747                 var t = this.getBorderWidth("t")+this.getPadding("t");
8748                 var b = this.getBorderWidth("b")+this.getPadding("b");
8749                 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)};
8750             }
8751             bx.right = bx.x + bx.width;
8752             bx.bottom = bx.y + bx.height;
8753             return bx;
8754         },
8755
8756         /**
8757          * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
8758          for more information about the sides.
8759          * @param {String} sides
8760          * @return {Number}
8761          */
8762         getFrameWidth : function(sides, onlyContentBox){
8763             return onlyContentBox && Roo.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
8764         },
8765
8766         /**
8767          * 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.
8768          * @param {Object} box The box to fill {x, y, width, height}
8769          * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
8770          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8771          * @return {Roo.Element} this
8772          */
8773         setBox : function(box, adjust, animate){
8774             var w = box.width, h = box.height;
8775             if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
8776                w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
8777                h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
8778             }
8779             this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
8780             return this;
8781         },
8782
8783         /**
8784          * Forces the browser to repaint this element
8785          * @return {Roo.Element} this
8786          */
8787          repaint : function(){
8788             var dom = this.dom;
8789             this.addClass("x-repaint");
8790             setTimeout(function(){
8791                 Roo.get(dom).removeClass("x-repaint");
8792             }, 1);
8793             return this;
8794         },
8795
8796         /**
8797          * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
8798          * then it returns the calculated width of the sides (see getPadding)
8799          * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
8800          * @return {Object/Number}
8801          */
8802         getMargins : function(side){
8803             if(!side){
8804                 return {
8805                     top: parseInt(this.getStyle("margin-top"), 10) || 0,
8806                     left: parseInt(this.getStyle("margin-left"), 10) || 0,
8807                     bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
8808                     right: parseInt(this.getStyle("margin-right"), 10) || 0
8809                 };
8810             }else{
8811                 return this.addStyles(side, El.margins);
8812              }
8813         },
8814
8815         // private
8816         addStyles : function(sides, styles){
8817             var val = 0, v, w;
8818             for(var i = 0, len = sides.length; i < len; i++){
8819                 v = this.getStyle(styles[sides.charAt(i)]);
8820                 if(v){
8821                      w = parseInt(v, 10);
8822                      if(w){ val += w; }
8823                 }
8824             }
8825             return val;
8826         },
8827
8828         /**
8829          * Creates a proxy element of this element
8830          * @param {String/Object} config The class name of the proxy element or a DomHelper config object
8831          * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
8832          * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
8833          * @return {Roo.Element} The new proxy element
8834          */
8835         createProxy : function(config, renderTo, matchBox){
8836             if(renderTo){
8837                 renderTo = Roo.getDom(renderTo);
8838             }else{
8839                 renderTo = document.body;
8840             }
8841             config = typeof config == "object" ?
8842                 config : {tag : "div", cls: config};
8843             var proxy = Roo.DomHelper.append(renderTo, config, true);
8844             if(matchBox){
8845                proxy.setBox(this.getBox());
8846             }
8847             return proxy;
8848         },
8849
8850         /**
8851          * Puts a mask over this element to disable user interaction. Requires core.css.
8852          * This method can only be applied to elements which accept child nodes.
8853          * @param {String} msg (optional) A message to display in the mask
8854          * @param {String} msgCls (optional) A css class to apply to the msg element
8855          * @return {Element} The mask  element
8856          */
8857         mask : function(msg, msgCls){
8858             if(this.getStyle("position") == "static"){
8859                 this.setStyle("position", "relative");
8860             }
8861             if(!this._mask){
8862                 this._mask = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask"}, true);
8863             }
8864             this.addClass("x-masked");
8865             this._mask.setDisplayed(true);
8866             if(typeof msg == 'string'){
8867                 if(!this._maskMsg){
8868                     this._maskMsg = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask-msg", cn:{tag:'div'}}, true);
8869                 }
8870                 var mm = this._maskMsg;
8871                 mm.dom.className = msgCls ? "roo-el-mask-msg " + msgCls : "roo-el-mask-msg";
8872                 mm.dom.firstChild.innerHTML = msg;
8873                 mm.setDisplayed(true);
8874                 mm.center(this);
8875             }
8876             if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
8877                 this._mask.setHeight(this.getHeight());
8878             }
8879             return this._mask;
8880         },
8881
8882         /**
8883          * Removes a previously applied mask. If removeEl is true the mask overlay is destroyed, otherwise
8884          * it is cached for reuse.
8885          */
8886         unmask : function(removeEl){
8887             if(this._mask){
8888                 if(removeEl === true){
8889                     this._mask.remove();
8890                     delete this._mask;
8891                     if(this._maskMsg){
8892                         this._maskMsg.remove();
8893                         delete this._maskMsg;
8894                     }
8895                 }else{
8896                     this._mask.setDisplayed(false);
8897                     if(this._maskMsg){
8898                         this._maskMsg.setDisplayed(false);
8899                     }
8900                 }
8901             }
8902             this.removeClass("x-masked");
8903         },
8904
8905         /**
8906          * Returns true if this element is masked
8907          * @return {Boolean}
8908          */
8909         isMasked : function(){
8910             return this._mask && this._mask.isVisible();
8911         },
8912
8913         /**
8914          * Creates an iframe shim for this element to keep selects and other windowed objects from
8915          * showing through.
8916          * @return {Roo.Element} The new shim element
8917          */
8918         createShim : function(){
8919             var el = document.createElement('iframe');
8920             el.frameBorder = 'no';
8921             el.className = 'roo-shim';
8922             if(Roo.isIE && Roo.isSecure){
8923                 el.src = Roo.SSL_SECURE_URL;
8924             }
8925             var shim = Roo.get(this.dom.parentNode.insertBefore(el, this.dom));
8926             shim.autoBoxAdjust = false;
8927             return shim;
8928         },
8929
8930         /**
8931          * Removes this element from the DOM and deletes it from the cache
8932          */
8933         remove : function(){
8934             if(this.dom.parentNode){
8935                 this.dom.parentNode.removeChild(this.dom);
8936             }
8937             delete El.cache[this.dom.id];
8938         },
8939
8940         /**
8941          * Sets up event handlers to add and remove a css class when the mouse is over this element
8942          * @param {String} className
8943          * @param {Boolean} preventFlicker (optional) If set to true, it prevents flickering by filtering
8944          * mouseout events for children elements
8945          * @return {Roo.Element} this
8946          */
8947         addClassOnOver : function(className, preventFlicker){
8948             this.on("mouseover", function(){
8949                 Roo.fly(this, '_internal').addClass(className);
8950             }, this.dom);
8951             var removeFn = function(e){
8952                 if(preventFlicker !== true || !e.within(this, true)){
8953                     Roo.fly(this, '_internal').removeClass(className);
8954                 }
8955             };
8956             this.on("mouseout", removeFn, this.dom);
8957             return this;
8958         },
8959
8960         /**
8961          * Sets up event handlers to add and remove a css class when this element has the focus
8962          * @param {String} className
8963          * @return {Roo.Element} this
8964          */
8965         addClassOnFocus : function(className){
8966             this.on("focus", function(){
8967                 Roo.fly(this, '_internal').addClass(className);
8968             }, this.dom);
8969             this.on("blur", function(){
8970                 Roo.fly(this, '_internal').removeClass(className);
8971             }, this.dom);
8972             return this;
8973         },
8974         /**
8975          * 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)
8976          * @param {String} className
8977          * @return {Roo.Element} this
8978          */
8979         addClassOnClick : function(className){
8980             var dom = this.dom;
8981             this.on("mousedown", function(){
8982                 Roo.fly(dom, '_internal').addClass(className);
8983                 var d = Roo.get(document);
8984                 var fn = function(){
8985                     Roo.fly(dom, '_internal').removeClass(className);
8986                     d.removeListener("mouseup", fn);
8987                 };
8988                 d.on("mouseup", fn);
8989             });
8990             return this;
8991         },
8992
8993         /**
8994          * Stops the specified event from bubbling and optionally prevents the default action
8995          * @param {String} eventName
8996          * @param {Boolean} preventDefault (optional) true to prevent the default action too
8997          * @return {Roo.Element} this
8998          */
8999         swallowEvent : function(eventName, preventDefault){
9000             var fn = function(e){
9001                 e.stopPropagation();
9002                 if(preventDefault){
9003                     e.preventDefault();
9004                 }
9005             };
9006             if(eventName instanceof Array){
9007                 for(var i = 0, len = eventName.length; i < len; i++){
9008                      this.on(eventName[i], fn);
9009                 }
9010                 return this;
9011             }
9012             this.on(eventName, fn);
9013             return this;
9014         },
9015
9016         /**
9017          * @private
9018          */
9019       fitToParentDelegate : Roo.emptyFn, // keep a reference to the fitToParent delegate
9020
9021         /**
9022          * Sizes this element to its parent element's dimensions performing
9023          * neccessary box adjustments.
9024          * @param {Boolean} monitorResize (optional) If true maintains the fit when the browser window is resized.
9025          * @param {String/HTMLElment/Element} targetParent (optional) The target parent, default to the parentNode.
9026          * @return {Roo.Element} this
9027          */
9028         fitToParent : function(monitorResize, targetParent) {
9029           Roo.EventManager.removeResizeListener(this.fitToParentDelegate); // always remove previous fitToParent delegate from onWindowResize
9030           this.fitToParentDelegate = Roo.emptyFn; // remove reference to previous delegate
9031           if (monitorResize === true && !this.dom.parentNode) { // check if this Element still exists
9032             return;
9033           }
9034           var p = Roo.get(targetParent || this.dom.parentNode);
9035           this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb'));
9036           if (monitorResize === true) {
9037             this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]);
9038             Roo.EventManager.onWindowResize(this.fitToParentDelegate);
9039           }
9040           return this;
9041         },
9042
9043         /**
9044          * Gets the next sibling, skipping text nodes
9045          * @return {HTMLElement} The next sibling or null
9046          */
9047         getNextSibling : function(){
9048             var n = this.dom.nextSibling;
9049             while(n && n.nodeType != 1){
9050                 n = n.nextSibling;
9051             }
9052             return n;
9053         },
9054
9055         /**
9056          * Gets the previous sibling, skipping text nodes
9057          * @return {HTMLElement} The previous sibling or null
9058          */
9059         getPrevSibling : function(){
9060             var n = this.dom.previousSibling;
9061             while(n && n.nodeType != 1){
9062                 n = n.previousSibling;
9063             }
9064             return n;
9065         },
9066
9067
9068         /**
9069          * Appends the passed element(s) to this element
9070          * @param {String/HTMLElement/Array/Element/CompositeElement} el
9071          * @return {Roo.Element} this
9072          */
9073         appendChild: function(el){
9074             el = Roo.get(el);
9075             el.appendTo(this);
9076             return this;
9077         },
9078
9079         /**
9080          * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
9081          * @param {Object} config DomHelper element config object.  If no tag is specified (e.g., {tag:'input'}) then a div will be
9082          * automatically generated with the specified attributes.
9083          * @param {HTMLElement} insertBefore (optional) a child element of this element
9084          * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
9085          * @return {Roo.Element} The new child element
9086          */
9087         createChild: function(config, insertBefore, returnDom){
9088             config = config || {tag:'div'};
9089             if(insertBefore){
9090                 return Roo.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
9091             }
9092             return Roo.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config,  returnDom !== true);
9093         },
9094
9095         /**
9096          * Appends this element to the passed element
9097          * @param {String/HTMLElement/Element} el The new parent element
9098          * @return {Roo.Element} this
9099          */
9100         appendTo: function(el){
9101             el = Roo.getDom(el);
9102             el.appendChild(this.dom);
9103             return this;
9104         },
9105
9106         /**
9107          * Inserts this element before the passed element in the DOM
9108          * @param {String/HTMLElement/Element} el The element to insert before
9109          * @return {Roo.Element} this
9110          */
9111         insertBefore: function(el){
9112             el = Roo.getDom(el);
9113             el.parentNode.insertBefore(this.dom, el);
9114             return this;
9115         },
9116
9117         /**
9118          * Inserts this element after the passed element in the DOM
9119          * @param {String/HTMLElement/Element} el The element to insert after
9120          * @return {Roo.Element} this
9121          */
9122         insertAfter: function(el){
9123             el = Roo.getDom(el);
9124             el.parentNode.insertBefore(this.dom, el.nextSibling);
9125             return this;
9126         },
9127
9128         /**
9129          * Inserts (or creates) an element (or DomHelper config) as the first child of the this element
9130          * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
9131          * @return {Roo.Element} The new child
9132          */
9133         insertFirst: function(el, returnDom){
9134             el = el || {};
9135             if(typeof el == 'object' && !el.nodeType){ // dh config
9136                 return this.createChild(el, this.dom.firstChild, returnDom);
9137             }else{
9138                 el = Roo.getDom(el);
9139                 this.dom.insertBefore(el, this.dom.firstChild);
9140                 return !returnDom ? Roo.get(el) : el;
9141             }
9142         },
9143
9144         /**
9145          * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
9146          * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
9147          * @param {String} where (optional) 'before' or 'after' defaults to before
9148          * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
9149          * @return {Roo.Element} the inserted Element
9150          */
9151         insertSibling: function(el, where, returnDom){
9152             where = where ? where.toLowerCase() : 'before';
9153             el = el || {};
9154             var rt, refNode = where == 'before' ? this.dom : this.dom.nextSibling;
9155
9156             if(typeof el == 'object' && !el.nodeType){ // dh config
9157                 if(where == 'after' && !this.dom.nextSibling){
9158                     rt = Roo.DomHelper.append(this.dom.parentNode, el, !returnDom);
9159                 }else{
9160                     rt = Roo.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
9161                 }
9162
9163             }else{
9164                 rt = this.dom.parentNode.insertBefore(Roo.getDom(el),
9165                             where == 'before' ? this.dom : this.dom.nextSibling);
9166                 if(!returnDom){
9167                     rt = Roo.get(rt);
9168                 }
9169             }
9170             return rt;
9171         },
9172
9173         /**
9174          * Creates and wraps this element with another element
9175          * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
9176          * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
9177          * @return {HTMLElement/Element} The newly created wrapper element
9178          */
9179         wrap: function(config, returnDom){
9180             if(!config){
9181                 config = {tag: "div"};
9182             }
9183             var newEl = Roo.DomHelper.insertBefore(this.dom, config, !returnDom);
9184             newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
9185             return newEl;
9186         },
9187
9188         /**
9189          * Replaces the passed element with this element
9190          * @param {String/HTMLElement/Element} el The element to replace
9191          * @return {Roo.Element} this
9192          */
9193         replace: function(el){
9194             el = Roo.get(el);
9195             this.insertBefore(el);
9196             el.remove();
9197             return this;
9198         },
9199
9200         /**
9201          * Inserts an html fragment into this element
9202          * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
9203          * @param {String} html The HTML fragment
9204          * @param {Boolean} returnEl True to return an Roo.Element
9205          * @return {HTMLElement/Roo.Element} The inserted node (or nearest related if more than 1 inserted)
9206          */
9207         insertHtml : function(where, html, returnEl){
9208             var el = Roo.DomHelper.insertHtml(where, this.dom, html);
9209             return returnEl ? Roo.get(el) : el;
9210         },
9211
9212         /**
9213          * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
9214          * @param {Object} o The object with the attributes
9215          * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
9216          * @return {Roo.Element} this
9217          */
9218         set : function(o, useSet){
9219             var el = this.dom;
9220             useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
9221             for(var attr in o){
9222                 if(attr == "style" || typeof o[attr] == "function") continue;
9223                 if(attr=="cls"){
9224                     el.className = o["cls"];
9225                 }else{
9226                     if(useSet) el.setAttribute(attr, o[attr]);
9227                     else el[attr] = o[attr];
9228                 }
9229             }
9230             if(o.style){
9231                 Roo.DomHelper.applyStyles(el, o.style);
9232             }
9233             return this;
9234         },
9235
9236         /**
9237          * Convenience method for constructing a KeyMap
9238          * @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:
9239          *                                  {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
9240          * @param {Function} fn The function to call
9241          * @param {Object} scope (optional) The scope of the function
9242          * @return {Roo.KeyMap} The KeyMap created
9243          */
9244         addKeyListener : function(key, fn, scope){
9245             var config;
9246             if(typeof key != "object" || key instanceof Array){
9247                 config = {
9248                     key: key,
9249                     fn: fn,
9250                     scope: scope
9251                 };
9252             }else{
9253                 config = {
9254                     key : key.key,
9255                     shift : key.shift,
9256                     ctrl : key.ctrl,
9257                     alt : key.alt,
9258                     fn: fn,
9259                     scope: scope
9260                 };
9261             }
9262             return new Roo.KeyMap(this, config);
9263         },
9264
9265         /**
9266          * Creates a KeyMap for this element
9267          * @param {Object} config The KeyMap config. See {@link Roo.KeyMap} for more details
9268          * @return {Roo.KeyMap} The KeyMap created
9269          */
9270         addKeyMap : function(config){
9271             return new Roo.KeyMap(this, config);
9272         },
9273
9274         /**
9275          * Returns true if this element is scrollable.
9276          * @return {Boolean}
9277          */
9278          isScrollable : function(){
9279             var dom = this.dom;
9280             return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
9281         },
9282
9283         /**
9284          * 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().
9285          * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
9286          * @param {Number} value The new scroll value
9287          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9288          * @return {Element} this
9289          */
9290
9291         scrollTo : function(side, value, animate){
9292             var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
9293             if(!animate || !A){
9294                 this.dom[prop] = value;
9295             }else{
9296                 var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
9297                 this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
9298             }
9299             return this;
9300         },
9301
9302         /**
9303          * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
9304          * within this element's scrollable range.
9305          * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
9306          * @param {Number} distance How far to scroll the element in pixels
9307          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9308          * @return {Boolean} Returns true if a scroll was triggered or false if the element
9309          * was scrolled as far as it could go.
9310          */
9311          scroll : function(direction, distance, animate){
9312              if(!this.isScrollable()){
9313                  return;
9314              }
9315              var el = this.dom;
9316              var l = el.scrollLeft, t = el.scrollTop;
9317              var w = el.scrollWidth, h = el.scrollHeight;
9318              var cw = el.clientWidth, ch = el.clientHeight;
9319              direction = direction.toLowerCase();
9320              var scrolled = false;
9321              var a = this.preanim(arguments, 2);
9322              switch(direction){
9323                  case "l":
9324                  case "left":
9325                      if(w - l > cw){
9326                          var v = Math.min(l + distance, w-cw);
9327                          this.scrollTo("left", v, a);
9328                          scrolled = true;
9329                      }
9330                      break;
9331                 case "r":
9332                 case "right":
9333                      if(l > 0){
9334                          var v = Math.max(l - distance, 0);
9335                          this.scrollTo("left", v, a);
9336                          scrolled = true;
9337                      }
9338                      break;
9339                 case "t":
9340                 case "top":
9341                 case "up":
9342                      if(t > 0){
9343                          var v = Math.max(t - distance, 0);
9344                          this.scrollTo("top", v, a);
9345                          scrolled = true;
9346                      }
9347                      break;
9348                 case "b":
9349                 case "bottom":
9350                 case "down":
9351                      if(h - t > ch){
9352                          var v = Math.min(t + distance, h-ch);
9353                          this.scrollTo("top", v, a);
9354                          scrolled = true;
9355                      }
9356                      break;
9357              }
9358              return scrolled;
9359         },
9360
9361         /**
9362          * Translates the passed page coordinates into left/top css values for this element
9363          * @param {Number/Array} x The page x or an array containing [x, y]
9364          * @param {Number} y The page y
9365          * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
9366          */
9367         translatePoints : function(x, y){
9368             if(typeof x == 'object' || x instanceof Array){
9369                 y = x[1]; x = x[0];
9370             }
9371             var p = this.getStyle('position');
9372             var o = this.getXY();
9373
9374             var l = parseInt(this.getStyle('left'), 10);
9375             var t = parseInt(this.getStyle('top'), 10);
9376
9377             if(isNaN(l)){
9378                 l = (p == "relative") ? 0 : this.dom.offsetLeft;
9379             }
9380             if(isNaN(t)){
9381                 t = (p == "relative") ? 0 : this.dom.offsetTop;
9382             }
9383
9384             return {left: (x - o[0] + l), top: (y - o[1] + t)};
9385         },
9386
9387         /**
9388          * Returns the current scroll position of the element.
9389          * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
9390          */
9391         getScroll : function(){
9392             var d = this.dom, doc = document;
9393             if(d == doc || d == doc.body){
9394                 var l = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
9395                 var t = window.pageYOffset || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
9396                 return {left: l, top: t};
9397             }else{
9398                 return {left: d.scrollLeft, top: d.scrollTop};
9399             }
9400         },
9401
9402         /**
9403          * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
9404          * are convert to standard 6 digit hex color.
9405          * @param {String} attr The css attribute
9406          * @param {String} defaultValue The default value to use when a valid color isn't found
9407          * @param {String} prefix (optional) defaults to #. Use an empty string when working with
9408          * YUI color anims.
9409          */
9410         getColor : function(attr, defaultValue, prefix){
9411             var v = this.getStyle(attr);
9412             if(!v || v == "transparent" || v == "inherit") {
9413                 return defaultValue;
9414             }
9415             var color = typeof prefix == "undefined" ? "#" : prefix;
9416             if(v.substr(0, 4) == "rgb("){
9417                 var rvs = v.slice(4, v.length -1).split(",");
9418                 for(var i = 0; i < 3; i++){
9419                     var h = parseInt(rvs[i]).toString(16);
9420                     if(h < 16){
9421                         h = "0" + h;
9422                     }
9423                     color += h;
9424                 }
9425             } else {
9426                 if(v.substr(0, 1) == "#"){
9427                     if(v.length == 4) {
9428                         for(var i = 1; i < 4; i++){
9429                             var c = v.charAt(i);
9430                             color +=  c + c;
9431                         }
9432                     }else if(v.length == 7){
9433                         color += v.substr(1);
9434                     }
9435                 }
9436             }
9437             return(color.length > 5 ? color.toLowerCase() : defaultValue);
9438         },
9439
9440         /**
9441          * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
9442          * gradient background, rounded corners and a 4-way shadow.
9443          * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
9444          * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
9445          * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
9446          * @return {Roo.Element} this
9447          */
9448         boxWrap : function(cls){
9449             cls = cls || 'x-box';
9450             var el = Roo.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
9451             el.child('.'+cls+'-mc').dom.appendChild(this.dom);
9452             return el;
9453         },
9454
9455         /**
9456          * Returns the value of a namespaced attribute from the element's underlying DOM node.
9457          * @param {String} namespace The namespace in which to look for the attribute
9458          * @param {String} name The attribute name
9459          * @return {String} The attribute value
9460          */
9461         getAttributeNS : Roo.isIE ? function(ns, name){
9462             var d = this.dom;
9463             var type = typeof d[ns+":"+name];
9464             if(type != 'undefined' && type != 'unknown'){
9465                 return d[ns+":"+name];
9466             }
9467             return d[name];
9468         } : function(ns, name){
9469             var d = this.dom;
9470             return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
9471         }
9472     };
9473
9474     var ep = El.prototype;
9475
9476     /**
9477      * Appends an event handler (Shorthand for addListener)
9478      * @param {String}   eventName     The type of event to append
9479      * @param {Function} fn        The method the event invokes
9480      * @param {Object} scope       (optional) The scope (this object) of the fn
9481      * @param {Object}   options   (optional)An object with standard {@link Roo.EventManager#addListener} options
9482      * @method
9483      */
9484     ep.on = ep.addListener;
9485         // backwards compat
9486     ep.mon = ep.addListener;
9487
9488     /**
9489      * Removes an event handler from this element (shorthand for removeListener)
9490      * @param {String} eventName the type of event to remove
9491      * @param {Function} fn the method the event invokes
9492      * @return {Roo.Element} this
9493      * @method
9494      */
9495     ep.un = ep.removeListener;
9496
9497     /**
9498      * true to automatically adjust width and height settings for box-model issues (default to true)
9499      */
9500     ep.autoBoxAdjust = true;
9501
9502     // private
9503     El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
9504
9505     // private
9506     El.addUnits = function(v, defaultUnit){
9507         if(v === "" || v == "auto"){
9508             return v;
9509         }
9510         if(v === undefined){
9511             return '';
9512         }
9513         if(typeof v == "number" || !El.unitPattern.test(v)){
9514             return v + (defaultUnit || 'px');
9515         }
9516         return v;
9517     };
9518
9519     // special markup used throughout Roo when box wrapping elements
9520     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>';
9521     /**
9522      * Visibility mode constant - Use visibility to hide element
9523      * @static
9524      * @type Number
9525      */
9526     El.VISIBILITY = 1;
9527     /**
9528      * Visibility mode constant - Use display to hide element
9529      * @static
9530      * @type Number
9531      */
9532     El.DISPLAY = 2;
9533
9534     El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
9535     El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
9536     El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
9537
9538
9539
9540     /**
9541      * @private
9542      */
9543     El.cache = {};
9544
9545     var docEl;
9546
9547     /**
9548      * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
9549      * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
9550      * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
9551      * @return {Element} The Element object
9552      * @static
9553      */
9554     El.get = function(el){
9555         var ex, elm, id;
9556         if(!el){ return null; }
9557         if(typeof el == "string"){ // element id
9558             if(!(elm = document.getElementById(el))){
9559                 return null;
9560             }
9561             if(ex = El.cache[el]){
9562                 ex.dom = elm;
9563             }else{
9564                 ex = El.cache[el] = new El(elm);
9565             }
9566             return ex;
9567         }else if(el.tagName){ // dom element
9568             if(!(id = el.id)){
9569                 id = Roo.id(el);
9570             }
9571             if(ex = El.cache[id]){
9572                 ex.dom = el;
9573             }else{
9574                 ex = El.cache[id] = new El(el);
9575             }
9576             return ex;
9577         }else if(el instanceof El){
9578             if(el != docEl){
9579                 el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
9580                                                               // catch case where it hasn't been appended
9581                 El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
9582             }
9583             return el;
9584         }else if(el.isComposite){
9585             return el;
9586         }else if(el instanceof Array){
9587             return El.select(el);
9588         }else if(el == document){
9589             // create a bogus element object representing the document object
9590             if(!docEl){
9591                 var f = function(){};
9592                 f.prototype = El.prototype;
9593                 docEl = new f();
9594                 docEl.dom = document;
9595             }
9596             return docEl;
9597         }
9598         return null;
9599     };
9600
9601     // private
9602     El.uncache = function(el){
9603         for(var i = 0, a = arguments, len = a.length; i < len; i++) {
9604             if(a[i]){
9605                 delete El.cache[a[i].id || a[i]];
9606             }
9607         }
9608     };
9609
9610     // private
9611     // Garbage collection - uncache elements/purge listeners on orphaned elements
9612     // so we don't hold a reference and cause the browser to retain them
9613     El.garbageCollect = function(){
9614         if(!Roo.enableGarbageCollector){
9615             clearInterval(El.collectorThread);
9616             return;
9617         }
9618         for(var eid in El.cache){
9619             var el = El.cache[eid], d = el.dom;
9620             // -------------------------------------------------------
9621             // Determining what is garbage:
9622             // -------------------------------------------------------
9623             // !d
9624             // dom node is null, definitely garbage
9625             // -------------------------------------------------------
9626             // !d.parentNode
9627             // no parentNode == direct orphan, definitely garbage
9628             // -------------------------------------------------------
9629             // !d.offsetParent && !document.getElementById(eid)
9630             // display none elements have no offsetParent so we will
9631             // also try to look it up by it's id. However, check
9632             // offsetParent first so we don't do unneeded lookups.
9633             // This enables collection of elements that are not orphans
9634             // directly, but somewhere up the line they have an orphan
9635             // parent.
9636             // -------------------------------------------------------
9637             if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
9638                 delete El.cache[eid];
9639                 if(d && Roo.enableListenerCollection){
9640                     E.purgeElement(d);
9641                 }
9642             }
9643         }
9644     }
9645     El.collectorThreadId = setInterval(El.garbageCollect, 30000);
9646
9647
9648     // dom is optional
9649     El.Flyweight = function(dom){
9650         this.dom = dom;
9651     };
9652     El.Flyweight.prototype = El.prototype;
9653
9654     El._flyweights = {};
9655     /**
9656      * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
9657      * the dom node can be overwritten by other code.
9658      * @param {String/HTMLElement} el The dom node or id
9659      * @param {String} named (optional) Allows for creation of named reusable flyweights to
9660      *                                  prevent conflicts (e.g. internally Roo uses "_internal")
9661      * @static
9662      * @return {Element} The shared Element object
9663      */
9664     El.fly = function(el, named){
9665         named = named || '_global';
9666         el = Roo.getDom(el);
9667         if(!el){
9668             return null;
9669         }
9670         if(!El._flyweights[named]){
9671             El._flyweights[named] = new El.Flyweight();
9672         }
9673         El._flyweights[named].dom = el;
9674         return El._flyweights[named];
9675     };
9676
9677     /**
9678      * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
9679      * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
9680      * Shorthand of {@link Roo.Element#get}
9681      * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
9682      * @return {Element} The Element object
9683      * @member Roo
9684      * @method get
9685      */
9686     Roo.get = El.get;
9687     /**
9688      * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
9689      * the dom node can be overwritten by other code.
9690      * Shorthand of {@link Roo.Element#fly}
9691      * @param {String/HTMLElement} el The dom node or id
9692      * @param {String} named (optional) Allows for creation of named reusable flyweights to
9693      *                                  prevent conflicts (e.g. internally Roo uses "_internal")
9694      * @static
9695      * @return {Element} The shared Element object
9696      * @member Roo
9697      * @method fly
9698      */
9699     Roo.fly = El.fly;
9700
9701     // speedy lookup for elements never to box adjust
9702     var noBoxAdjust = Roo.isStrict ? {
9703         select:1
9704     } : {
9705         input:1, select:1, textarea:1
9706     };
9707     if(Roo.isIE || Roo.isGecko){
9708         noBoxAdjust['button'] = 1;
9709     }
9710
9711
9712     Roo.EventManager.on(window, 'unload', function(){
9713         delete El.cache;
9714         delete El._flyweights;
9715     });
9716 })();
9717
9718
9719
9720
9721 if(Roo.DomQuery){
9722     Roo.Element.selectorFunction = Roo.DomQuery.select;
9723 }
9724
9725 Roo.Element.select = function(selector, unique, root){
9726     var els;
9727     if(typeof selector == "string"){
9728         els = Roo.Element.selectorFunction(selector, root);
9729     }else if(selector.length !== undefined){
9730         els = selector;
9731     }else{
9732         throw "Invalid selector";
9733     }
9734     if(unique === true){
9735         return new Roo.CompositeElement(els);
9736     }else{
9737         return new Roo.CompositeElementLite(els);
9738     }
9739 };
9740 /**
9741  * Selects elements based on the passed CSS selector to enable working on them as 1.
9742  * @param {String/Array} selector The CSS selector or an array of elements
9743  * @param {Boolean} unique (optional) true to create a unique Roo.Element for each element (defaults to a shared flyweight object)
9744  * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
9745  * @return {CompositeElementLite/CompositeElement}
9746  * @member Roo
9747  * @method select
9748  */
9749 Roo.select = Roo.Element.select;
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764 /*
9765  * Based on:
9766  * Ext JS Library 1.1.1
9767  * Copyright(c) 2006-2007, Ext JS, LLC.
9768  *
9769  * Originally Released Under LGPL - original licence link has changed is not relivant.
9770  *
9771  * Fork - LGPL
9772  * <script type="text/javascript">
9773  */
9774
9775
9776
9777 //Notifies Element that fx methods are available
9778 Roo.enableFx = true;
9779
9780 /**
9781  * @class Roo.Fx
9782  * <p>A class to provide basic animation and visual effects support.  <b>Note:</b> This class is automatically applied
9783  * to the {@link Roo.Element} interface when included, so all effects calls should be performed via Element.
9784  * Conversely, since the effects are not actually defined in Element, Roo.Fx <b>must</b> be included in order for the 
9785  * Element effects to work.</p><br/>
9786  *
9787  * <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
9788  * they return the Element object itself as the method return value, it is not always possible to mix the two in a single
9789  * method chain.  The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
9790  * Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately.  For this reason,
9791  * while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
9792  * expected results and should be done with care.</p><br/>
9793  *
9794  * <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
9795  * that will serve as either the start or end point of the animation.  Following are all of the supported anchor positions:</p>
9796 <pre>
9797 Value  Description
9798 -----  -----------------------------
9799 tl     The top left corner
9800 t      The center of the top edge
9801 tr     The top right corner
9802 l      The center of the left edge
9803 r      The center of the right edge
9804 bl     The bottom left corner
9805 b      The center of the bottom edge
9806 br     The bottom right corner
9807 </pre>
9808  * <b>Although some Fx methods accept specific custom config parameters, the ones shown in the Config Options section
9809  * below are common options that can be passed to any Fx method.</b>
9810  * @cfg {Function} callback A function called when the effect is finished
9811  * @cfg {Object} scope The scope of the effect function
9812  * @cfg {String} easing A valid Easing value for the effect
9813  * @cfg {String} afterCls A css class to apply after the effect
9814  * @cfg {Number} duration The length of time (in seconds) that the effect should last
9815  * @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
9816  * @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to 
9817  * effects that end with the element being visually hidden, ignored otherwise)
9818  * @cfg {String/Object/Function} afterStyle A style specification string, e.g. "width:100px", or an object in the form {width:"100px"}, or
9819  * a function which returns such a specification that will be applied to the Element after the effect finishes
9820  * @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
9821  * @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
9822  * @cfg {Boolean} stopFx Whether subsequent effects should be stopped and removed after the current effect finishes
9823  */
9824 Roo.Fx = {
9825         /**
9826          * Slides the element into view.  An anchor point can be optionally passed to set the point of
9827          * origin for the slide effect.  This function automatically handles wrapping the element with
9828          * a fixed-size container if needed.  See the Fx class overview for valid anchor point options.
9829          * Usage:
9830          *<pre><code>
9831 // default: slide the element in from the top
9832 el.slideIn();
9833
9834 // custom: slide the element in from the right with a 2-second duration
9835 el.slideIn('r', { duration: 2 });
9836
9837 // common config options shown with default values
9838 el.slideIn('t', {
9839     easing: 'easeOut',
9840     duration: .5
9841 });
9842 </code></pre>
9843          * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
9844          * @param {Object} options (optional) Object literal with any of the Fx config options
9845          * @return {Roo.Element} The Element
9846          */
9847     slideIn : function(anchor, o){
9848         var el = this.getFxEl();
9849         o = o || {};
9850
9851         el.queueFx(o, function(){
9852
9853             anchor = anchor || "t";
9854
9855             // fix display to visibility
9856             this.fixDisplay();
9857
9858             // restore values after effect
9859             var r = this.getFxRestore();
9860             var b = this.getBox();
9861             // fixed size for slide
9862             this.setSize(b);
9863
9864             // wrap if needed
9865             var wrap = this.fxWrap(r.pos, o, "hidden");
9866
9867             var st = this.dom.style;
9868             st.visibility = "visible";
9869             st.position = "absolute";
9870
9871             // clear out temp styles after slide and unwrap
9872             var after = function(){
9873                 el.fxUnwrap(wrap, r.pos, o);
9874                 st.width = r.width;
9875                 st.height = r.height;
9876                 el.afterFx(o);
9877             };
9878             // time to calc the positions
9879             var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
9880
9881             switch(anchor.toLowerCase()){
9882                 case "t":
9883                     wrap.setSize(b.width, 0);
9884                     st.left = st.bottom = "0";
9885                     a = {height: bh};
9886                 break;
9887                 case "l":
9888                     wrap.setSize(0, b.height);
9889                     st.right = st.top = "0";
9890                     a = {width: bw};
9891                 break;
9892                 case "r":
9893                     wrap.setSize(0, b.height);
9894                     wrap.setX(b.right);
9895                     st.left = st.top = "0";
9896                     a = {width: bw, points: pt};
9897                 break;
9898                 case "b":
9899                     wrap.setSize(b.width, 0);
9900                     wrap.setY(b.bottom);
9901                     st.left = st.top = "0";
9902                     a = {height: bh, points: pt};
9903                 break;
9904                 case "tl":
9905                     wrap.setSize(0, 0);
9906                     st.right = st.bottom = "0";
9907                     a = {width: bw, height: bh};
9908                 break;
9909                 case "bl":
9910                     wrap.setSize(0, 0);
9911                     wrap.setY(b.y+b.height);
9912                     st.right = st.top = "0";
9913                     a = {width: bw, height: bh, points: pt};
9914                 break;
9915                 case "br":
9916                     wrap.setSize(0, 0);
9917                     wrap.setXY([b.right, b.bottom]);
9918                     st.left = st.top = "0";
9919                     a = {width: bw, height: bh, points: pt};
9920                 break;
9921                 case "tr":
9922                     wrap.setSize(0, 0);
9923                     wrap.setX(b.x+b.width);
9924                     st.left = st.bottom = "0";
9925                     a = {width: bw, height: bh, points: pt};
9926                 break;
9927             }
9928             this.dom.style.visibility = "visible";
9929             wrap.show();
9930
9931             arguments.callee.anim = wrap.fxanim(a,
9932                 o,
9933                 'motion',
9934                 .5,
9935                 'easeOut', after);
9936         });
9937         return this;
9938     },
9939     
9940         /**
9941          * Slides the element out of view.  An anchor point can be optionally passed to set the end point
9942          * for the slide effect.  When the effect is completed, the element will be hidden (visibility = 
9943          * 'hidden') but block elements will still take up space in the document.  The element must be removed
9944          * from the DOM using the 'remove' config option if desired.  This function automatically handles 
9945          * wrapping the element with a fixed-size container if needed.  See the Fx class overview for valid anchor point options.
9946          * Usage:
9947          *<pre><code>
9948 // default: slide the element out to the top
9949 el.slideOut();
9950
9951 // custom: slide the element out to the right with a 2-second duration
9952 el.slideOut('r', { duration: 2 });
9953
9954 // common config options shown with default values
9955 el.slideOut('t', {
9956     easing: 'easeOut',
9957     duration: .5,
9958     remove: false,
9959     useDisplay: false
9960 });
9961 </code></pre>
9962          * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
9963          * @param {Object} options (optional) Object literal with any of the Fx config options
9964          * @return {Roo.Element} The Element
9965          */
9966     slideOut : function(anchor, o){
9967         var el = this.getFxEl();
9968         o = o || {};
9969
9970         el.queueFx(o, function(){
9971
9972             anchor = anchor || "t";
9973
9974             // restore values after effect
9975             var r = this.getFxRestore();
9976             
9977             var b = this.getBox();
9978             // fixed size for slide
9979             this.setSize(b);
9980
9981             // wrap if needed
9982             var wrap = this.fxWrap(r.pos, o, "visible");
9983
9984             var st = this.dom.style;
9985             st.visibility = "visible";
9986             st.position = "absolute";
9987
9988             wrap.setSize(b);
9989
9990             var after = function(){
9991                 if(o.useDisplay){
9992                     el.setDisplayed(false);
9993                 }else{
9994                     el.hide();
9995                 }
9996
9997                 el.fxUnwrap(wrap, r.pos, o);
9998
9999                 st.width = r.width;
10000                 st.height = r.height;
10001
10002                 el.afterFx(o);
10003             };
10004
10005             var a, zero = {to: 0};
10006             switch(anchor.toLowerCase()){
10007                 case "t":
10008                     st.left = st.bottom = "0";
10009                     a = {height: zero};
10010                 break;
10011                 case "l":
10012                     st.right = st.top = "0";
10013                     a = {width: zero};
10014                 break;
10015                 case "r":
10016                     st.left = st.top = "0";
10017                     a = {width: zero, points: {to:[b.right, b.y]}};
10018                 break;
10019                 case "b":
10020                     st.left = st.top = "0";
10021                     a = {height: zero, points: {to:[b.x, b.bottom]}};
10022                 break;
10023                 case "tl":
10024                     st.right = st.bottom = "0";
10025                     a = {width: zero, height: zero};
10026                 break;
10027                 case "bl":
10028                     st.right = st.top = "0";
10029                     a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
10030                 break;
10031                 case "br":
10032                     st.left = st.top = "0";
10033                     a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
10034                 break;
10035                 case "tr":
10036                     st.left = st.bottom = "0";
10037                     a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
10038                 break;
10039             }
10040
10041             arguments.callee.anim = wrap.fxanim(a,
10042                 o,
10043                 'motion',
10044                 .5,
10045                 "easeOut", after);
10046         });
10047         return this;
10048     },
10049
10050         /**
10051          * Fades the element out while slowly expanding it in all directions.  When the effect is completed, the 
10052          * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document. 
10053          * The element must be removed from the DOM using the 'remove' config option if desired.
10054          * Usage:
10055          *<pre><code>
10056 // default
10057 el.puff();
10058
10059 // common config options shown with default values
10060 el.puff({
10061     easing: 'easeOut',
10062     duration: .5,
10063     remove: false,
10064     useDisplay: false
10065 });
10066 </code></pre>
10067          * @param {Object} options (optional) Object literal with any of the Fx config options
10068          * @return {Roo.Element} The Element
10069          */
10070     puff : function(o){
10071         var el = this.getFxEl();
10072         o = o || {};
10073
10074         el.queueFx(o, function(){
10075             this.clearOpacity();
10076             this.show();
10077
10078             // restore values after effect
10079             var r = this.getFxRestore();
10080             var st = this.dom.style;
10081
10082             var after = function(){
10083                 if(o.useDisplay){
10084                     el.setDisplayed(false);
10085                 }else{
10086                     el.hide();
10087                 }
10088
10089                 el.clearOpacity();
10090
10091                 el.setPositioning(r.pos);
10092                 st.width = r.width;
10093                 st.height = r.height;
10094                 st.fontSize = '';
10095                 el.afterFx(o);
10096             };
10097
10098             var width = this.getWidth();
10099             var height = this.getHeight();
10100
10101             arguments.callee.anim = this.fxanim({
10102                     width : {to: this.adjustWidth(width * 2)},
10103                     height : {to: this.adjustHeight(height * 2)},
10104                     points : {by: [-(width * .5), -(height * .5)]},
10105                     opacity : {to: 0},
10106                     fontSize: {to:200, unit: "%"}
10107                 },
10108                 o,
10109                 'motion',
10110                 .5,
10111                 "easeOut", after);
10112         });
10113         return this;
10114     },
10115
10116         /**
10117          * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
10118          * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still 
10119          * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
10120          * Usage:
10121          *<pre><code>
10122 // default
10123 el.switchOff();
10124
10125 // all config options shown with default values
10126 el.switchOff({
10127     easing: 'easeIn',
10128     duration: .3,
10129     remove: false,
10130     useDisplay: false
10131 });
10132 </code></pre>
10133          * @param {Object} options (optional) Object literal with any of the Fx config options
10134          * @return {Roo.Element} The Element
10135          */
10136     switchOff : function(o){
10137         var el = this.getFxEl();
10138         o = o || {};
10139
10140         el.queueFx(o, function(){
10141             this.clearOpacity();
10142             this.clip();
10143
10144             // restore values after effect
10145             var r = this.getFxRestore();
10146             var st = this.dom.style;
10147
10148             var after = function(){
10149                 if(o.useDisplay){
10150                     el.setDisplayed(false);
10151                 }else{
10152                     el.hide();
10153                 }
10154
10155                 el.clearOpacity();
10156                 el.setPositioning(r.pos);
10157                 st.width = r.width;
10158                 st.height = r.height;
10159
10160                 el.afterFx(o);
10161             };
10162
10163             this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
10164                 this.clearOpacity();
10165                 (function(){
10166                     this.fxanim({
10167                         height:{to:1},
10168                         points:{by:[0, this.getHeight() * .5]}
10169                     }, o, 'motion', 0.3, 'easeIn', after);
10170                 }).defer(100, this);
10171             });
10172         });
10173         return this;
10174     },
10175
10176     /**
10177      * Highlights the Element by setting a color (applies to the background-color by default, but can be
10178      * changed using the "attr" config option) and then fading back to the original color. If no original
10179      * color is available, you should provide the "endColor" config option which will be cleared after the animation.
10180      * Usage:
10181 <pre><code>
10182 // default: highlight background to yellow
10183 el.highlight();
10184
10185 // custom: highlight foreground text to blue for 2 seconds
10186 el.highlight("0000ff", { attr: 'color', duration: 2 });
10187
10188 // common config options shown with default values
10189 el.highlight("ffff9c", {
10190     attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
10191     endColor: (current color) or "ffffff",
10192     easing: 'easeIn',
10193     duration: 1
10194 });
10195 </code></pre>
10196      * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
10197      * @param {Object} options (optional) Object literal with any of the Fx config options
10198      * @return {Roo.Element} The Element
10199      */ 
10200     highlight : function(color, o){
10201         var el = this.getFxEl();
10202         o = o || {};
10203
10204         el.queueFx(o, function(){
10205             color = color || "ffff9c";
10206             attr = o.attr || "backgroundColor";
10207
10208             this.clearOpacity();
10209             this.show();
10210
10211             var origColor = this.getColor(attr);
10212             var restoreColor = this.dom.style[attr];
10213             endColor = (o.endColor || origColor) || "ffffff";
10214
10215             var after = function(){
10216                 el.dom.style[attr] = restoreColor;
10217                 el.afterFx(o);
10218             };
10219
10220             var a = {};
10221             a[attr] = {from: color, to: endColor};
10222             arguments.callee.anim = this.fxanim(a,
10223                 o,
10224                 'color',
10225                 1,
10226                 'easeIn', after);
10227         });
10228         return this;
10229     },
10230
10231    /**
10232     * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
10233     * Usage:
10234 <pre><code>
10235 // default: a single light blue ripple
10236 el.frame();
10237
10238 // custom: 3 red ripples lasting 3 seconds total
10239 el.frame("ff0000", 3, { duration: 3 });
10240
10241 // common config options shown with default values
10242 el.frame("C3DAF9", 1, {
10243     duration: 1 //duration of entire animation (not each individual ripple)
10244     // Note: Easing is not configurable and will be ignored if included
10245 });
10246 </code></pre>
10247     * @param {String} color (optional) The color of the border.  Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
10248     * @param {Number} count (optional) The number of ripples to display (defaults to 1)
10249     * @param {Object} options (optional) Object literal with any of the Fx config options
10250     * @return {Roo.Element} The Element
10251     */
10252     frame : function(color, count, o){
10253         var el = this.getFxEl();
10254         o = o || {};
10255
10256         el.queueFx(o, function(){
10257             color = color || "#C3DAF9";
10258             if(color.length == 6){
10259                 color = "#" + color;
10260             }
10261             count = count || 1;
10262             duration = o.duration || 1;
10263             this.show();
10264
10265             var b = this.getBox();
10266             var animFn = function(){
10267                 var proxy = this.createProxy({
10268
10269                      style:{
10270                         visbility:"hidden",
10271                         position:"absolute",
10272                         "z-index":"35000", // yee haw
10273                         border:"0px solid " + color
10274                      }
10275                   });
10276                 var scale = Roo.isBorderBox ? 2 : 1;
10277                 proxy.animate({
10278                     top:{from:b.y, to:b.y - 20},
10279                     left:{from:b.x, to:b.x - 20},
10280                     borderWidth:{from:0, to:10},
10281                     opacity:{from:1, to:0},
10282                     height:{from:b.height, to:(b.height + (20*scale))},
10283                     width:{from:b.width, to:(b.width + (20*scale))}
10284                 }, duration, function(){
10285                     proxy.remove();
10286                 });
10287                 if(--count > 0){
10288                      animFn.defer((duration/2)*1000, this);
10289                 }else{
10290                     el.afterFx(o);
10291                 }
10292             };
10293             animFn.call(this);
10294         });
10295         return this;
10296     },
10297
10298    /**
10299     * Creates a pause before any subsequent queued effects begin.  If there are
10300     * no effects queued after the pause it will have no effect.
10301     * Usage:
10302 <pre><code>
10303 el.pause(1);
10304 </code></pre>
10305     * @param {Number} seconds The length of time to pause (in seconds)
10306     * @return {Roo.Element} The Element
10307     */
10308     pause : function(seconds){
10309         var el = this.getFxEl();
10310         var o = {};
10311
10312         el.queueFx(o, function(){
10313             setTimeout(function(){
10314                 el.afterFx(o);
10315             }, seconds * 1000);
10316         });
10317         return this;
10318     },
10319
10320    /**
10321     * Fade an element in (from transparent to opaque).  The ending opacity can be specified
10322     * using the "endOpacity" config option.
10323     * Usage:
10324 <pre><code>
10325 // default: fade in from opacity 0 to 100%
10326 el.fadeIn();
10327
10328 // custom: fade in from opacity 0 to 75% over 2 seconds
10329 el.fadeIn({ endOpacity: .75, duration: 2});
10330
10331 // common config options shown with default values
10332 el.fadeIn({
10333     endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
10334     easing: 'easeOut',
10335     duration: .5
10336 });
10337 </code></pre>
10338     * @param {Object} options (optional) Object literal with any of the Fx config options
10339     * @return {Roo.Element} The Element
10340     */
10341     fadeIn : function(o){
10342         var el = this.getFxEl();
10343         o = o || {};
10344         el.queueFx(o, function(){
10345             this.setOpacity(0);
10346             this.fixDisplay();
10347             this.dom.style.visibility = 'visible';
10348             var to = o.endOpacity || 1;
10349             arguments.callee.anim = this.fxanim({opacity:{to:to}},
10350                 o, null, .5, "easeOut", function(){
10351                 if(to == 1){
10352                     this.clearOpacity();
10353                 }
10354                 el.afterFx(o);
10355             });
10356         });
10357         return this;
10358     },
10359
10360    /**
10361     * Fade an element out (from opaque to transparent).  The ending opacity can be specified
10362     * using the "endOpacity" config option.
10363     * Usage:
10364 <pre><code>
10365 // default: fade out from the element's current opacity to 0
10366 el.fadeOut();
10367
10368 // custom: fade out from the element's current opacity to 25% over 2 seconds
10369 el.fadeOut({ endOpacity: .25, duration: 2});
10370
10371 // common config options shown with default values
10372 el.fadeOut({
10373     endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
10374     easing: 'easeOut',
10375     duration: .5
10376     remove: false,
10377     useDisplay: false
10378 });
10379 </code></pre>
10380     * @param {Object} options (optional) Object literal with any of the Fx config options
10381     * @return {Roo.Element} The Element
10382     */
10383     fadeOut : function(o){
10384         var el = this.getFxEl();
10385         o = o || {};
10386         el.queueFx(o, function(){
10387             arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}},
10388                 o, null, .5, "easeOut", function(){
10389                 if(this.visibilityMode == Roo.Element.DISPLAY || o.useDisplay){
10390                      this.dom.style.display = "none";
10391                 }else{
10392                      this.dom.style.visibility = "hidden";
10393                 }
10394                 this.clearOpacity();
10395                 el.afterFx(o);
10396             });
10397         });
10398         return this;
10399     },
10400
10401    /**
10402     * Animates the transition of an element's dimensions from a starting height/width
10403     * to an ending height/width.
10404     * Usage:
10405 <pre><code>
10406 // change height and width to 100x100 pixels
10407 el.scale(100, 100);
10408
10409 // common config options shown with default values.  The height and width will default to
10410 // the element's existing values if passed as null.
10411 el.scale(
10412     [element's width],
10413     [element's height], {
10414     easing: 'easeOut',
10415     duration: .35
10416 });
10417 </code></pre>
10418     * @param {Number} width  The new width (pass undefined to keep the original width)
10419     * @param {Number} height  The new height (pass undefined to keep the original height)
10420     * @param {Object} options (optional) Object literal with any of the Fx config options
10421     * @return {Roo.Element} The Element
10422     */
10423     scale : function(w, h, o){
10424         this.shift(Roo.apply({}, o, {
10425             width: w,
10426             height: h
10427         }));
10428         return this;
10429     },
10430
10431    /**
10432     * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
10433     * Any of these properties not specified in the config object will not be changed.  This effect 
10434     * requires that at least one new dimension, position or opacity setting must be passed in on
10435     * the config object in order for the function to have any effect.
10436     * Usage:
10437 <pre><code>
10438 // slide the element horizontally to x position 200 while changing the height and opacity
10439 el.shift({ x: 200, height: 50, opacity: .8 });
10440
10441 // common config options shown with default values.
10442 el.shift({
10443     width: [element's width],
10444     height: [element's height],
10445     x: [element's x position],
10446     y: [element's y position],
10447     opacity: [element's opacity],
10448     easing: 'easeOut',
10449     duration: .35
10450 });
10451 </code></pre>
10452     * @param {Object} options  Object literal with any of the Fx config options
10453     * @return {Roo.Element} The Element
10454     */
10455     shift : function(o){
10456         var el = this.getFxEl();
10457         o = o || {};
10458         el.queueFx(o, function(){
10459             var a = {}, w = o.width, h = o.height, x = o.x, y = o.y,  op = o.opacity;
10460             if(w !== undefined){
10461                 a.width = {to: this.adjustWidth(w)};
10462             }
10463             if(h !== undefined){
10464                 a.height = {to: this.adjustHeight(h)};
10465             }
10466             if(x !== undefined || y !== undefined){
10467                 a.points = {to: [
10468                     x !== undefined ? x : this.getX(),
10469                     y !== undefined ? y : this.getY()
10470                 ]};
10471             }
10472             if(op !== undefined){
10473                 a.opacity = {to: op};
10474             }
10475             if(o.xy !== undefined){
10476                 a.points = {to: o.xy};
10477             }
10478             arguments.callee.anim = this.fxanim(a,
10479                 o, 'motion', .35, "easeOut", function(){
10480                 el.afterFx(o);
10481             });
10482         });
10483         return this;
10484     },
10485
10486         /**
10487          * Slides the element while fading it out of view.  An anchor point can be optionally passed to set the 
10488          * ending point of the effect.
10489          * Usage:
10490          *<pre><code>
10491 // default: slide the element downward while fading out
10492 el.ghost();
10493
10494 // custom: slide the element out to the right with a 2-second duration
10495 el.ghost('r', { duration: 2 });
10496
10497 // common config options shown with default values
10498 el.ghost('b', {
10499     easing: 'easeOut',
10500     duration: .5
10501     remove: false,
10502     useDisplay: false
10503 });
10504 </code></pre>
10505          * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
10506          * @param {Object} options (optional) Object literal with any of the Fx config options
10507          * @return {Roo.Element} The Element
10508          */
10509     ghost : function(anchor, o){
10510         var el = this.getFxEl();
10511         o = o || {};
10512
10513         el.queueFx(o, function(){
10514             anchor = anchor || "b";
10515
10516             // restore values after effect
10517             var r = this.getFxRestore();
10518             var w = this.getWidth(),
10519                 h = this.getHeight();
10520
10521             var st = this.dom.style;
10522
10523             var after = function(){
10524                 if(o.useDisplay){
10525                     el.setDisplayed(false);
10526                 }else{
10527                     el.hide();
10528                 }
10529
10530                 el.clearOpacity();
10531                 el.setPositioning(r.pos);
10532                 st.width = r.width;
10533                 st.height = r.height;
10534
10535                 el.afterFx(o);
10536             };
10537
10538             var a = {opacity: {to: 0}, points: {}}, pt = a.points;
10539             switch(anchor.toLowerCase()){
10540                 case "t":
10541                     pt.by = [0, -h];
10542                 break;
10543                 case "l":
10544                     pt.by = [-w, 0];
10545                 break;
10546                 case "r":
10547                     pt.by = [w, 0];
10548                 break;
10549                 case "b":
10550                     pt.by = [0, h];
10551                 break;
10552                 case "tl":
10553                     pt.by = [-w, -h];
10554                 break;
10555                 case "bl":
10556                     pt.by = [-w, h];
10557                 break;
10558                 case "br":
10559                     pt.by = [w, h];
10560                 break;
10561                 case "tr":
10562                     pt.by = [w, -h];
10563                 break;
10564             }
10565
10566             arguments.callee.anim = this.fxanim(a,
10567                 o,
10568                 'motion',
10569                 .5,
10570                 "easeOut", after);
10571         });
10572         return this;
10573     },
10574
10575         /**
10576          * Ensures that all effects queued after syncFx is called on the element are
10577          * run concurrently.  This is the opposite of {@link #sequenceFx}.
10578          * @return {Roo.Element} The Element
10579          */
10580     syncFx : function(){
10581         this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
10582             block : false,
10583             concurrent : true,
10584             stopFx : false
10585         });
10586         return this;
10587     },
10588
10589         /**
10590          * Ensures that all effects queued after sequenceFx is called on the element are
10591          * run in sequence.  This is the opposite of {@link #syncFx}.
10592          * @return {Roo.Element} The Element
10593          */
10594     sequenceFx : function(){
10595         this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
10596             block : false,
10597             concurrent : false,
10598             stopFx : false
10599         });
10600         return this;
10601     },
10602
10603         /* @private */
10604     nextFx : function(){
10605         var ef = this.fxQueue[0];
10606         if(ef){
10607             ef.call(this);
10608         }
10609     },
10610
10611         /**
10612          * Returns true if the element has any effects actively running or queued, else returns false.
10613          * @return {Boolean} True if element has active effects, else false
10614          */
10615     hasActiveFx : function(){
10616         return this.fxQueue && this.fxQueue[0];
10617     },
10618
10619         /**
10620          * Stops any running effects and clears the element's internal effects queue if it contains
10621          * any additional effects that haven't started yet.
10622          * @return {Roo.Element} The Element
10623          */
10624     stopFx : function(){
10625         if(this.hasActiveFx()){
10626             var cur = this.fxQueue[0];
10627             if(cur && cur.anim && cur.anim.isAnimated()){
10628                 this.fxQueue = [cur]; // clear out others
10629                 cur.anim.stop(true);
10630             }
10631         }
10632         return this;
10633     },
10634
10635         /* @private */
10636     beforeFx : function(o){
10637         if(this.hasActiveFx() && !o.concurrent){
10638            if(o.stopFx){
10639                this.stopFx();
10640                return true;
10641            }
10642            return false;
10643         }
10644         return true;
10645     },
10646
10647         /**
10648          * Returns true if the element is currently blocking so that no other effect can be queued
10649          * until this effect is finished, else returns false if blocking is not set.  This is commonly
10650          * used to ensure that an effect initiated by a user action runs to completion prior to the
10651          * same effect being restarted (e.g., firing only one effect even if the user clicks several times).
10652          * @return {Boolean} True if blocking, else false
10653          */
10654     hasFxBlock : function(){
10655         var q = this.fxQueue;
10656         return q && q[0] && q[0].block;
10657     },
10658
10659         /* @private */
10660     queueFx : function(o, fn){
10661         if(!this.fxQueue){
10662             this.fxQueue = [];
10663         }
10664         if(!this.hasFxBlock()){
10665             Roo.applyIf(o, this.fxDefaults);
10666             if(!o.concurrent){
10667                 var run = this.beforeFx(o);
10668                 fn.block = o.block;
10669                 this.fxQueue.push(fn);
10670                 if(run){
10671                     this.nextFx();
10672                 }
10673             }else{
10674                 fn.call(this);
10675             }
10676         }
10677         return this;
10678     },
10679
10680         /* @private */
10681     fxWrap : function(pos, o, vis){
10682         var wrap;
10683         if(!o.wrap || !(wrap = Roo.get(o.wrap))){
10684             var wrapXY;
10685             if(o.fixPosition){
10686                 wrapXY = this.getXY();
10687             }
10688             var div = document.createElement("div");
10689             div.style.visibility = vis;
10690             wrap = Roo.get(this.dom.parentNode.insertBefore(div, this.dom));
10691             wrap.setPositioning(pos);
10692             if(wrap.getStyle("position") == "static"){
10693                 wrap.position("relative");
10694             }
10695             this.clearPositioning('auto');
10696             wrap.clip();
10697             wrap.dom.appendChild(this.dom);
10698             if(wrapXY){
10699                 wrap.setXY(wrapXY);
10700             }
10701         }
10702         return wrap;
10703     },
10704
10705         /* @private */
10706     fxUnwrap : function(wrap, pos, o){
10707         this.clearPositioning();
10708         this.setPositioning(pos);
10709         if(!o.wrap){
10710             wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
10711             wrap.remove();
10712         }
10713     },
10714
10715         /* @private */
10716     getFxRestore : function(){
10717         var st = this.dom.style;
10718         return {pos: this.getPositioning(), width: st.width, height : st.height};
10719     },
10720
10721         /* @private */
10722     afterFx : function(o){
10723         if(o.afterStyle){
10724             this.applyStyles(o.afterStyle);
10725         }
10726         if(o.afterCls){
10727             this.addClass(o.afterCls);
10728         }
10729         if(o.remove === true){
10730             this.remove();
10731         }
10732         Roo.callback(o.callback, o.scope, [this]);
10733         if(!o.concurrent){
10734             this.fxQueue.shift();
10735             this.nextFx();
10736         }
10737     },
10738
10739         /* @private */
10740     getFxEl : function(){ // support for composite element fx
10741         return Roo.get(this.dom);
10742     },
10743
10744         /* @private */
10745     fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
10746         animType = animType || 'run';
10747         opt = opt || {};
10748         var anim = Roo.lib.Anim[animType](
10749             this.dom, args,
10750             (opt.duration || defaultDur) || .35,
10751             (opt.easing || defaultEase) || 'easeOut',
10752             function(){
10753                 Roo.callback(cb, this);
10754             },
10755             this
10756         );
10757         opt.anim = anim;
10758         return anim;
10759     }
10760 };
10761
10762 // backwords compat
10763 Roo.Fx.resize = Roo.Fx.scale;
10764
10765 //When included, Roo.Fx is automatically applied to Element so that all basic
10766 //effects are available directly via the Element API
10767 Roo.apply(Roo.Element.prototype, Roo.Fx);/*
10768  * Based on:
10769  * Ext JS Library 1.1.1
10770  * Copyright(c) 2006-2007, Ext JS, LLC.
10771  *
10772  * Originally Released Under LGPL - original licence link has changed is not relivant.
10773  *
10774  * Fork - LGPL
10775  * <script type="text/javascript">
10776  */
10777
10778
10779 /**
10780  * @class Roo.CompositeElement
10781  * Standard composite class. Creates a Roo.Element for every element in the collection.
10782  * <br><br>
10783  * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
10784  * actions will be performed on all the elements in this collection.</b>
10785  * <br><br>
10786  * All methods return <i>this</i> and can be chained.
10787  <pre><code>
10788  var els = Roo.select("#some-el div.some-class", true);
10789  // or select directly from an existing element
10790  var el = Roo.get('some-el');
10791  el.select('div.some-class', true);
10792
10793  els.setWidth(100); // all elements become 100 width
10794  els.hide(true); // all elements fade out and hide
10795  // or
10796  els.setWidth(100).hide(true);
10797  </code></pre>
10798  */
10799 Roo.CompositeElement = function(els){
10800     this.elements = [];
10801     this.addElements(els);
10802 };
10803 Roo.CompositeElement.prototype = {
10804     isComposite: true,
10805     addElements : function(els){
10806         if(!els) return this;
10807         if(typeof els == "string"){
10808             els = Roo.Element.selectorFunction(els);
10809         }
10810         var yels = this.elements;
10811         var index = yels.length-1;
10812         for(var i = 0, len = els.length; i < len; i++) {
10813                 yels[++index] = Roo.get(els[i]);
10814         }
10815         return this;
10816     },
10817
10818     /**
10819     * Clears this composite and adds the elements returned by the passed selector.
10820     * @param {String/Array} els A string CSS selector, an array of elements or an element
10821     * @return {CompositeElement} this
10822     */
10823     fill : function(els){
10824         this.elements = [];
10825         this.add(els);
10826         return this;
10827     },
10828
10829     /**
10830     * Filters this composite to only elements that match the passed selector.
10831     * @param {String} selector A string CSS selector
10832     * @return {CompositeElement} this
10833     */
10834     filter : function(selector){
10835         var els = [];
10836         this.each(function(el){
10837             if(el.is(selector)){
10838                 els[els.length] = el.dom;
10839             }
10840         });
10841         this.fill(els);
10842         return this;
10843     },
10844
10845     invoke : function(fn, args){
10846         var els = this.elements;
10847         for(var i = 0, len = els.length; i < len; i++) {
10848                 Roo.Element.prototype[fn].apply(els[i], args);
10849         }
10850         return this;
10851     },
10852     /**
10853     * Adds elements to this composite.
10854     * @param {String/Array} els A string CSS selector, an array of elements or an element
10855     * @return {CompositeElement} this
10856     */
10857     add : function(els){
10858         if(typeof els == "string"){
10859             this.addElements(Roo.Element.selectorFunction(els));
10860         }else if(els.length !== undefined){
10861             this.addElements(els);
10862         }else{
10863             this.addElements([els]);
10864         }
10865         return this;
10866     },
10867     /**
10868     * Calls the passed function passing (el, this, index) for each element in this composite.
10869     * @param {Function} fn The function to call
10870     * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
10871     * @return {CompositeElement} this
10872     */
10873     each : function(fn, scope){
10874         var els = this.elements;
10875         for(var i = 0, len = els.length; i < len; i++){
10876             if(fn.call(scope || els[i], els[i], this, i) === false) {
10877                 break;
10878             }
10879         }
10880         return this;
10881     },
10882
10883     /**
10884      * Returns the Element object at the specified index
10885      * @param {Number} index
10886      * @return {Roo.Element}
10887      */
10888     item : function(index){
10889         return this.elements[index] || null;
10890     },
10891
10892     /**
10893      * Returns the first Element
10894      * @return {Roo.Element}
10895      */
10896     first : function(){
10897         return this.item(0);
10898     },
10899
10900     /**
10901      * Returns the last Element
10902      * @return {Roo.Element}
10903      */
10904     last : function(){
10905         return this.item(this.elements.length-1);
10906     },
10907
10908     /**
10909      * Returns the number of elements in this composite
10910      * @return Number
10911      */
10912     getCount : function(){
10913         return this.elements.length;
10914     },
10915
10916     /**
10917      * Returns true if this composite contains the passed element
10918      * @return Boolean
10919      */
10920     contains : function(el){
10921         return this.indexOf(el) !== -1;
10922     },
10923
10924     /**
10925      * Returns true if this composite contains the passed element
10926      * @return Boolean
10927      */
10928     indexOf : function(el){
10929         return this.elements.indexOf(Roo.get(el));
10930     },
10931
10932
10933     /**
10934     * Removes the specified element(s).
10935     * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
10936     * or an array of any of those.
10937     * @param {Boolean} removeDom (optional) True to also remove the element from the document
10938     * @return {CompositeElement} this
10939     */
10940     removeElement : function(el, removeDom){
10941         if(el instanceof Array){
10942             for(var i = 0, len = el.length; i < len; i++){
10943                 this.removeElement(el[i]);
10944             }
10945             return this;
10946         }
10947         var index = typeof el == 'number' ? el : this.indexOf(el);
10948         if(index !== -1){
10949             if(removeDom){
10950                 var d = this.elements[index];
10951                 if(d.dom){
10952                     d.remove();
10953                 }else{
10954                     d.parentNode.removeChild(d);
10955                 }
10956             }
10957             this.elements.splice(index, 1);
10958         }
10959         return this;
10960     },
10961
10962     /**
10963     * Replaces the specified element with the passed element.
10964     * @param {String/HTMLElement/Element/Number} el The id of an element, the Element itself, the index of the element in this composite
10965     * to replace.
10966     * @param {String/HTMLElement/Element} replacement The id of an element or the Element itself.
10967     * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
10968     * @return {CompositeElement} this
10969     */
10970     replaceElement : function(el, replacement, domReplace){
10971         var index = typeof el == 'number' ? el : this.indexOf(el);
10972         if(index !== -1){
10973             if(domReplace){
10974                 this.elements[index].replaceWith(replacement);
10975             }else{
10976                 this.elements.splice(index, 1, Roo.get(replacement))
10977             }
10978         }
10979         return this;
10980     },
10981
10982     /**
10983      * Removes all elements.
10984      */
10985     clear : function(){
10986         this.elements = [];
10987     }
10988 };
10989 (function(){
10990     Roo.CompositeElement.createCall = function(proto, fnName){
10991         if(!proto[fnName]){
10992             proto[fnName] = function(){
10993                 return this.invoke(fnName, arguments);
10994             };
10995         }
10996     };
10997     for(var fnName in Roo.Element.prototype){
10998         if(typeof Roo.Element.prototype[fnName] == "function"){
10999             Roo.CompositeElement.createCall(Roo.CompositeElement.prototype, fnName);
11000         }
11001     };
11002 })();
11003 /*
11004  * Based on:
11005  * Ext JS Library 1.1.1
11006  * Copyright(c) 2006-2007, Ext JS, LLC.
11007  *
11008  * Originally Released Under LGPL - original licence link has changed is not relivant.
11009  *
11010  * Fork - LGPL
11011  * <script type="text/javascript">
11012  */
11013
11014 /**
11015  * @class Roo.CompositeElementLite
11016  * @extends Roo.CompositeElement
11017  * Flyweight composite class. Reuses the same Roo.Element for element operations.
11018  <pre><code>
11019  var els = Roo.select("#some-el div.some-class");
11020  // or select directly from an existing element
11021  var el = Roo.get('some-el');
11022  el.select('div.some-class');
11023
11024  els.setWidth(100); // all elements become 100 width
11025  els.hide(true); // all elements fade out and hide
11026  // or
11027  els.setWidth(100).hide(true);
11028  </code></pre><br><br>
11029  * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
11030  * actions will be performed on all the elements in this collection.</b>
11031  */
11032 Roo.CompositeElementLite = function(els){
11033     Roo.CompositeElementLite.superclass.constructor.call(this, els);
11034     this.el = new Roo.Element.Flyweight();
11035 };
11036 Roo.extend(Roo.CompositeElementLite, Roo.CompositeElement, {
11037     addElements : function(els){
11038         if(els){
11039             if(els instanceof Array){
11040                 this.elements = this.elements.concat(els);
11041             }else{
11042                 var yels = this.elements;
11043                 var index = yels.length-1;
11044                 for(var i = 0, len = els.length; i < len; i++) {
11045                     yels[++index] = els[i];
11046                 }
11047             }
11048         }
11049         return this;
11050     },
11051     invoke : function(fn, args){
11052         var els = this.elements;
11053         var el = this.el;
11054         for(var i = 0, len = els.length; i < len; i++) {
11055             el.dom = els[i];
11056                 Roo.Element.prototype[fn].apply(el, args);
11057         }
11058         return this;
11059     },
11060     /**
11061      * Returns a flyweight Element of the dom element object at the specified index
11062      * @param {Number} index
11063      * @return {Roo.Element}
11064      */
11065     item : function(index){
11066         if(!this.elements[index]){
11067             return null;
11068         }
11069         this.el.dom = this.elements[index];
11070         return this.el;
11071     },
11072
11073     // fixes scope with flyweight
11074     addListener : function(eventName, handler, scope, opt){
11075         var els = this.elements;
11076         for(var i = 0, len = els.length; i < len; i++) {
11077             Roo.EventManager.on(els[i], eventName, handler, scope || els[i], opt);
11078         }
11079         return this;
11080     },
11081
11082     /**
11083     * Calls the passed function passing (el, this, index) for each element in this composite. <b>The element
11084     * passed is the flyweight (shared) Roo.Element instance, so if you require a
11085     * a reference to the dom node, use el.dom.</b>
11086     * @param {Function} fn The function to call
11087     * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
11088     * @return {CompositeElement} this
11089     */
11090     each : function(fn, scope){
11091         var els = this.elements;
11092         var el = this.el;
11093         for(var i = 0, len = els.length; i < len; i++){
11094             el.dom = els[i];
11095                 if(fn.call(scope || el, el, this, i) === false){
11096                 break;
11097             }
11098         }
11099         return this;
11100     },
11101
11102     indexOf : function(el){
11103         return this.elements.indexOf(Roo.getDom(el));
11104     },
11105
11106     replaceElement : function(el, replacement, domReplace){
11107         var index = typeof el == 'number' ? el : this.indexOf(el);
11108         if(index !== -1){
11109             replacement = Roo.getDom(replacement);
11110             if(domReplace){
11111                 var d = this.elements[index];
11112                 d.parentNode.insertBefore(replacement, d);
11113                 d.parentNode.removeChild(d);
11114             }
11115             this.elements.splice(index, 1, replacement);
11116         }
11117         return this;
11118     }
11119 });
11120 Roo.CompositeElementLite.prototype.on = Roo.CompositeElementLite.prototype.addListener;
11121
11122 /*
11123  * Based on:
11124  * Ext JS Library 1.1.1
11125  * Copyright(c) 2006-2007, Ext JS, LLC.
11126  *
11127  * Originally Released Under LGPL - original licence link has changed is not relivant.
11128  *
11129  * Fork - LGPL
11130  * <script type="text/javascript">
11131  */
11132
11133  
11134
11135 /**
11136  * @class Roo.data.Connection
11137  * @extends Roo.util.Observable
11138  * The class encapsulates a connection to the page's originating domain, allowing requests to be made
11139  * either to a configured URL, or to a URL specified at request time.<br><br>
11140  * <p>
11141  * Requests made by this class are asynchronous, and will return immediately. No data from
11142  * the server will be available to the statement immediately following the {@link #request} call.
11143  * To process returned data, use a callback in the request options object, or an event listener.</p><br>
11144  * <p>
11145  * Note: If you are doing a file upload, you will not get a normal response object sent back to
11146  * your callback or event handler.  Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
11147  * The response object is created using the innerHTML of the IFRAME's document as the responseText
11148  * property and, if present, the IFRAME's XML document as the responseXML property.</p><br>
11149  * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
11150  * that it be placed either inside a &lt;textarea> in an HTML document and retrieved from the responseText
11151  * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
11152  * standard DOM methods.
11153  * @constructor
11154  * @param {Object} config a configuration object.
11155  */
11156 Roo.data.Connection = function(config){
11157     Roo.apply(this, config);
11158     this.addEvents({
11159         /**
11160          * @event beforerequest
11161          * Fires before a network request is made to retrieve a data object.
11162          * @param {Connection} conn This Connection object.
11163          * @param {Object} options The options config object passed to the {@link #request} method.
11164          */
11165         "beforerequest" : true,
11166         /**
11167          * @event requestcomplete
11168          * Fires if the request was successfully completed.
11169          * @param {Connection} conn This Connection object.
11170          * @param {Object} response The XHR object containing the response data.
11171          * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
11172          * @param {Object} options The options config object passed to the {@link #request} method.
11173          */
11174         "requestcomplete" : true,
11175         /**
11176          * @event requestexception
11177          * Fires if an error HTTP status was returned from the server.
11178          * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
11179          * @param {Connection} conn This Connection object.
11180          * @param {Object} response The XHR object containing the response data.
11181          * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
11182          * @param {Object} options The options config object passed to the {@link #request} method.
11183          */
11184         "requestexception" : true
11185     });
11186     Roo.data.Connection.superclass.constructor.call(this);
11187 };
11188
11189 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
11190     /**
11191      * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
11192      */
11193     /**
11194      * @cfg {Object} extraParams (Optional) An object containing properties which are used as
11195      * extra parameters to each request made by this object. (defaults to undefined)
11196      */
11197     /**
11198      * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
11199      *  to each request made by this object. (defaults to undefined)
11200      */
11201     /**
11202      * @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)
11203      */
11204     /**
11205      * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
11206      */
11207     timeout : 30000,
11208     /**
11209      * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
11210      * @type Boolean
11211      */
11212     autoAbort:false,
11213
11214     /**
11215      * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
11216      * @type Boolean
11217      */
11218     disableCaching: true,
11219
11220     /**
11221      * Sends an HTTP request to a remote server.
11222      * @param {Object} options An object which may contain the following properties:<ul>
11223      * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
11224      * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
11225      * request, a url encoded string or a function to call to get either.</li>
11226      * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
11227      * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
11228      * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
11229      * The callback is called regardless of success or failure and is passed the following parameters:<ul>
11230      * <li>options {Object} The parameter to the request call.</li>
11231      * <li>success {Boolean} True if the request succeeded.</li>
11232      * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11233      * </ul></li>
11234      * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
11235      * The callback is passed the following parameters:<ul>
11236      * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11237      * <li>options {Object} The parameter to the request call.</li>
11238      * </ul></li>
11239      * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
11240      * The callback is passed the following parameters:<ul>
11241      * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11242      * <li>options {Object} The parameter to the request call.</li>
11243      * </ul></li>
11244      * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
11245      * for the callback function. Defaults to the browser window.</li>
11246      * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
11247      * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
11248      * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
11249      * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
11250      * params for the post data. Any params will be appended to the URL.</li>
11251      * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
11252      * </ul>
11253      * @return {Number} transactionId
11254      */
11255     request : function(o){
11256         if(this.fireEvent("beforerequest", this, o) !== false){
11257             var p = o.params;
11258
11259             if(typeof p == "function"){
11260                 p = p.call(o.scope||window, o);
11261             }
11262             if(typeof p == "object"){
11263                 p = Roo.urlEncode(o.params);
11264             }
11265             if(this.extraParams){
11266                 var extras = Roo.urlEncode(this.extraParams);
11267                 p = p ? (p + '&' + extras) : extras;
11268             }
11269
11270             var url = o.url || this.url;
11271             if(typeof url == 'function'){
11272                 url = url.call(o.scope||window, o);
11273             }
11274
11275             if(o.form){
11276                 var form = Roo.getDom(o.form);
11277                 url = url || form.action;
11278
11279                 var enctype = form.getAttribute("enctype");
11280                 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
11281                     return this.doFormUpload(o, p, url);
11282                 }
11283                 var f = Roo.lib.Ajax.serializeForm(form);
11284                 p = p ? (p + '&' + f) : f;
11285             }
11286
11287             var hs = o.headers;
11288             if(this.defaultHeaders){
11289                 hs = Roo.apply(hs || {}, this.defaultHeaders);
11290                 if(!o.headers){
11291                     o.headers = hs;
11292                 }
11293             }
11294
11295             var cb = {
11296                 success: this.handleResponse,
11297                 failure: this.handleFailure,
11298                 scope: this,
11299                 argument: {options: o},
11300                 timeout : this.timeout
11301             };
11302
11303             var method = o.method||this.method||(p ? "POST" : "GET");
11304
11305             if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
11306                 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
11307             }
11308
11309             if(typeof o.autoAbort == 'boolean'){ // options gets top priority
11310                 if(o.autoAbort){
11311                     this.abort();
11312                 }
11313             }else if(this.autoAbort !== false){
11314                 this.abort();
11315             }
11316
11317             if((method == 'GET' && p) || o.xmlData){
11318                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
11319                 p = '';
11320             }
11321             this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
11322             return this.transId;
11323         }else{
11324             Roo.callback(o.callback, o.scope, [o, null, null]);
11325             return null;
11326         }
11327     },
11328
11329     /**
11330      * Determine whether this object has a request outstanding.
11331      * @param {Number} transactionId (Optional) defaults to the last transaction
11332      * @return {Boolean} True if there is an outstanding request.
11333      */
11334     isLoading : function(transId){
11335         if(transId){
11336             return Roo.lib.Ajax.isCallInProgress(transId);
11337         }else{
11338             return this.transId ? true : false;
11339         }
11340     },
11341
11342     /**
11343      * Aborts any outstanding request.
11344      * @param {Number} transactionId (Optional) defaults to the last transaction
11345      */
11346     abort : function(transId){
11347         if(transId || this.isLoading()){
11348             Roo.lib.Ajax.abort(transId || this.transId);
11349         }
11350     },
11351
11352     // private
11353     handleResponse : function(response){
11354         this.transId = false;
11355         var options = response.argument.options;
11356         response.argument = options ? options.argument : null;
11357         this.fireEvent("requestcomplete", this, response, options);
11358         Roo.callback(options.success, options.scope, [response, options]);
11359         Roo.callback(options.callback, options.scope, [options, true, response]);
11360     },
11361
11362     // private
11363     handleFailure : function(response, e){
11364         this.transId = false;
11365         var options = response.argument.options;
11366         response.argument = options ? options.argument : null;
11367         this.fireEvent("requestexception", this, response, options, e);
11368         Roo.callback(options.failure, options.scope, [response, options]);
11369         Roo.callback(options.callback, options.scope, [options, false, response]);
11370     },
11371
11372     // private
11373     doFormUpload : function(o, ps, url){
11374         var id = Roo.id();
11375         var frame = document.createElement('iframe');
11376         frame.id = id;
11377         frame.name = id;
11378         frame.className = 'x-hidden';
11379         if(Roo.isIE){
11380             frame.src = Roo.SSL_SECURE_URL;
11381         }
11382         document.body.appendChild(frame);
11383
11384         if(Roo.isIE){
11385            document.frames[id].name = id;
11386         }
11387
11388         var form = Roo.getDom(o.form);
11389         form.target = id;
11390         form.method = 'POST';
11391         form.enctype = form.encoding = 'multipart/form-data';
11392         if(url){
11393             form.action = url;
11394         }
11395
11396         var hiddens, hd;
11397         if(ps){ // add dynamic params
11398             hiddens = [];
11399             ps = Roo.urlDecode(ps, false);
11400             for(var k in ps){
11401                 if(ps.hasOwnProperty(k)){
11402                     hd = document.createElement('input');
11403                     hd.type = 'hidden';
11404                     hd.name = k;
11405                     hd.value = ps[k];
11406                     form.appendChild(hd);
11407                     hiddens.push(hd);
11408                 }
11409             }
11410         }
11411
11412         function cb(){
11413             var r = {  // bogus response object
11414                 responseText : '',
11415                 responseXML : null
11416             };
11417
11418             r.argument = o ? o.argument : null;
11419
11420             try { //
11421                 var doc;
11422                 if(Roo.isIE){
11423                     doc = frame.contentWindow.document;
11424                 }else {
11425                     doc = (frame.contentDocument || window.frames[id].document);
11426                 }
11427                 if(doc && doc.body){
11428                     r.responseText = doc.body.innerHTML;
11429                 }
11430                 if(doc && doc.XMLDocument){
11431                     r.responseXML = doc.XMLDocument;
11432                 }else {
11433                     r.responseXML = doc;
11434                 }
11435             }
11436             catch(e) {
11437                 // ignore
11438             }
11439
11440             Roo.EventManager.removeListener(frame, 'load', cb, this);
11441
11442             this.fireEvent("requestcomplete", this, r, o);
11443             Roo.callback(o.success, o.scope, [r, o]);
11444             Roo.callback(o.callback, o.scope, [o, true, r]);
11445
11446             setTimeout(function(){document.body.removeChild(frame);}, 100);
11447         }
11448
11449         Roo.EventManager.on(frame, 'load', cb, this);
11450         form.submit();
11451
11452         if(hiddens){ // remove dynamic params
11453             for(var i = 0, len = hiddens.length; i < len; i++){
11454                 form.removeChild(hiddens[i]);
11455             }
11456         }
11457     }
11458 });
11459
11460 /**
11461  * @class Roo.Ajax
11462  * @extends Roo.data.Connection
11463  * Global Ajax request class.
11464  *
11465  * @singleton
11466  */
11467 Roo.Ajax = new Roo.data.Connection({
11468     // fix up the docs
11469    /**
11470      * @cfg {String} url @hide
11471      */
11472     /**
11473      * @cfg {Object} extraParams @hide
11474      */
11475     /**
11476      * @cfg {Object} defaultHeaders @hide
11477      */
11478     /**
11479      * @cfg {String} method (Optional) @hide
11480      */
11481     /**
11482      * @cfg {Number} timeout (Optional) @hide
11483      */
11484     /**
11485      * @cfg {Boolean} autoAbort (Optional) @hide
11486      */
11487
11488     /**
11489      * @cfg {Boolean} disableCaching (Optional) @hide
11490      */
11491
11492     /**
11493      * @property  disableCaching
11494      * True to add a unique cache-buster param to GET requests. (defaults to true)
11495      * @type Boolean
11496      */
11497     /**
11498      * @property  url
11499      * The default URL to be used for requests to the server. (defaults to undefined)
11500      * @type String
11501      */
11502     /**
11503      * @property  extraParams
11504      * An object containing properties which are used as
11505      * extra parameters to each request made by this object. (defaults to undefined)
11506      * @type Object
11507      */
11508     /**
11509      * @property  defaultHeaders
11510      * An object containing request headers which are added to each request made by this object. (defaults to undefined)
11511      * @type Object
11512      */
11513     /**
11514      * @property  method
11515      * The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
11516      * @type String
11517      */
11518     /**
11519      * @property  timeout
11520      * The timeout in milliseconds to be used for requests. (defaults to 30000)
11521      * @type Number
11522      */
11523
11524     /**
11525      * @property  autoAbort
11526      * Whether a new request should abort any pending requests. (defaults to false)
11527      * @type Boolean
11528      */
11529     autoAbort : false,
11530
11531     /**
11532      * Serialize the passed form into a url encoded string
11533      * @param {String/HTMLElement} form
11534      * @return {String}
11535      */
11536     serializeForm : function(form){
11537         return Roo.lib.Ajax.serializeForm(form);
11538     }
11539 });/*
11540  * Based on:
11541  * Ext JS Library 1.1.1
11542  * Copyright(c) 2006-2007, Ext JS, LLC.
11543  *
11544  * Originally Released Under LGPL - original licence link has changed is not relivant.
11545  *
11546  * Fork - LGPL
11547  * <script type="text/javascript">
11548  */
11549  
11550 /**
11551  * @class Roo.Ajax
11552  * @extends Roo.data.Connection
11553  * Global Ajax request class.
11554  *
11555  * @instanceOf  Roo.data.Connection
11556  */
11557 Roo.Ajax = new Roo.data.Connection({
11558     // fix up the docs
11559     
11560     /**
11561      * fix up scoping
11562      * @scope Roo.Ajax
11563      */
11564     
11565    /**
11566      * @cfg {String} url @hide
11567      */
11568     /**
11569      * @cfg {Object} extraParams @hide
11570      */
11571     /**
11572      * @cfg {Object} defaultHeaders @hide
11573      */
11574     /**
11575      * @cfg {String} method (Optional) @hide
11576      */
11577     /**
11578      * @cfg {Number} timeout (Optional) @hide
11579      */
11580     /**
11581      * @cfg {Boolean} autoAbort (Optional) @hide
11582      */
11583
11584     /**
11585      * @cfg {Boolean} disableCaching (Optional) @hide
11586      */
11587
11588     /**
11589      * @property  disableCaching
11590      * True to add a unique cache-buster param to GET requests. (defaults to true)
11591      * @type Boolean
11592      */
11593     /**
11594      * @property  url
11595      * The default URL to be used for requests to the server. (defaults to undefined)
11596      * @type String
11597      */
11598     /**
11599      * @property  extraParams
11600      * An object containing properties which are used as
11601      * extra parameters to each request made by this object. (defaults to undefined)
11602      * @type Object
11603      */
11604     /**
11605      * @property  defaultHeaders
11606      * An object containing request headers which are added to each request made by this object. (defaults to undefined)
11607      * @type Object
11608      */
11609     /**
11610      * @property  method
11611      * The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
11612      * @type String
11613      */
11614     /**
11615      * @property  timeout
11616      * The timeout in milliseconds to be used for requests. (defaults to 30000)
11617      * @type Number
11618      */
11619
11620     /**
11621      * @property  autoAbort
11622      * Whether a new request should abort any pending requests. (defaults to false)
11623      * @type Boolean
11624      */
11625     autoAbort : false,
11626
11627     /**
11628      * Serialize the passed form into a url encoded string
11629      * @param {String/HTMLElement} form
11630      * @return {String}
11631      */
11632     serializeForm : function(form){
11633         return Roo.lib.Ajax.serializeForm(form);
11634     }
11635 });/*
11636  * Based on:
11637  * Ext JS Library 1.1.1
11638  * Copyright(c) 2006-2007, Ext JS, LLC.
11639  *
11640  * Originally Released Under LGPL - original licence link has changed is not relivant.
11641  *
11642  * Fork - LGPL
11643  * <script type="text/javascript">
11644  */
11645
11646  
11647 /**
11648  * @class Roo.UpdateManager
11649  * @extends Roo.util.Observable
11650  * Provides AJAX-style update for Element object.<br><br>
11651  * Usage:<br>
11652  * <pre><code>
11653  * // Get it from a Roo.Element object
11654  * var el = Roo.get("foo");
11655  * var mgr = el.getUpdateManager();
11656  * mgr.update("http://myserver.com/index.php", "param1=1&amp;param2=2");
11657  * ...
11658  * mgr.formUpdate("myFormId", "http://myserver.com/index.php");
11659  * <br>
11660  * // or directly (returns the same UpdateManager instance)
11661  * var mgr = new Roo.UpdateManager("myElementId");
11662  * mgr.startAutoRefresh(60, "http://myserver.com/index.php");
11663  * mgr.on("update", myFcnNeedsToKnow);
11664  * <br>
11665    // short handed call directly from the element object
11666    Roo.get("foo").load({
11667         url: "bar.php",
11668         scripts:true,
11669         params: "for=bar",
11670         text: "Loading Foo..."
11671    });
11672  * </code></pre>
11673  * @constructor
11674  * Create new UpdateManager directly.
11675  * @param {String/HTMLElement/Roo.Element} el The element to update
11676  * @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).
11677  */
11678 Roo.UpdateManager = function(el, forceNew){
11679     el = Roo.get(el);
11680     if(!forceNew && el.updateManager){
11681         return el.updateManager;
11682     }
11683     /**
11684      * The Element object
11685      * @type Roo.Element
11686      */
11687     this.el = el;
11688     /**
11689      * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
11690      * @type String
11691      */
11692     this.defaultUrl = null;
11693
11694     this.addEvents({
11695         /**
11696          * @event beforeupdate
11697          * Fired before an update is made, return false from your handler and the update is cancelled.
11698          * @param {Roo.Element} el
11699          * @param {String/Object/Function} url
11700          * @param {String/Object} params
11701          */
11702         "beforeupdate": true,
11703         /**
11704          * @event update
11705          * Fired after successful update is made.
11706          * @param {Roo.Element} el
11707          * @param {Object} oResponseObject The response Object
11708          */
11709         "update": true,
11710         /**
11711          * @event failure
11712          * Fired on update failure.
11713          * @param {Roo.Element} el
11714          * @param {Object} oResponseObject The response Object
11715          */
11716         "failure": true
11717     });
11718     var d = Roo.UpdateManager.defaults;
11719     /**
11720      * Blank page URL to use with SSL file uploads (Defaults to Roo.UpdateManager.defaults.sslBlankUrl or "about:blank").
11721      * @type String
11722      */
11723     this.sslBlankUrl = d.sslBlankUrl;
11724     /**
11725      * Whether to append unique parameter on get request to disable caching (Defaults to Roo.UpdateManager.defaults.disableCaching or false).
11726      * @type Boolean
11727      */
11728     this.disableCaching = d.disableCaching;
11729     /**
11730      * Text for loading indicator (Defaults to Roo.UpdateManager.defaults.indicatorText or '&lt;div class="loading-indicator"&gt;Loading...&lt;/div&gt;').
11731      * @type String
11732      */
11733     this.indicatorText = d.indicatorText;
11734     /**
11735      * Whether to show indicatorText when loading (Defaults to Roo.UpdateManager.defaults.showLoadIndicator or true).
11736      * @type String
11737      */
11738     this.showLoadIndicator = d.showLoadIndicator;
11739     /**
11740      * Timeout for requests or form posts in seconds (Defaults to Roo.UpdateManager.defaults.timeout or 30 seconds).
11741      * @type Number
11742      */
11743     this.timeout = d.timeout;
11744
11745     /**
11746      * True to process scripts in the output (Defaults to Roo.UpdateManager.defaults.loadScripts (false)).
11747      * @type Boolean
11748      */
11749     this.loadScripts = d.loadScripts;
11750
11751     /**
11752      * Transaction object of current executing transaction
11753      */
11754     this.transaction = null;
11755
11756     /**
11757      * @private
11758      */
11759     this.autoRefreshProcId = null;
11760     /**
11761      * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
11762      * @type Function
11763      */
11764     this.refreshDelegate = this.refresh.createDelegate(this);
11765     /**
11766      * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
11767      * @type Function
11768      */
11769     this.updateDelegate = this.update.createDelegate(this);
11770     /**
11771      * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
11772      * @type Function
11773      */
11774     this.formUpdateDelegate = this.formUpdate.createDelegate(this);
11775     /**
11776      * @private
11777      */
11778     this.successDelegate = this.processSuccess.createDelegate(this);
11779     /**
11780      * @private
11781      */
11782     this.failureDelegate = this.processFailure.createDelegate(this);
11783
11784     if(!this.renderer){
11785      /**
11786       * The renderer for this UpdateManager. Defaults to {@link Roo.UpdateManager.BasicRenderer}.
11787       */
11788     this.renderer = new Roo.UpdateManager.BasicRenderer();
11789     }
11790     
11791     Roo.UpdateManager.superclass.constructor.call(this);
11792 };
11793
11794 Roo.extend(Roo.UpdateManager, Roo.util.Observable, {
11795     /**
11796      * Get the Element this UpdateManager is bound to
11797      * @return {Roo.Element} The element
11798      */
11799     getEl : function(){
11800         return this.el;
11801     },
11802     /**
11803      * Performs an async request, updating this element with the response. If params are specified it uses POST, otherwise it uses GET.
11804      * @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:
11805 <pre><code>
11806 um.update({<br/>
11807     url: "your-url.php",<br/>
11808     params: {param1: "foo", param2: "bar"}, // or a URL encoded string<br/>
11809     callback: yourFunction,<br/>
11810     scope: yourObject, //(optional scope)  <br/>
11811     discardUrl: false, <br/>
11812     nocache: false,<br/>
11813     text: "Loading...",<br/>
11814     timeout: 30,<br/>
11815     scripts: false<br/>
11816 });
11817 </code></pre>
11818      * The only required property is url. The optional properties nocache, text and scripts
11819      * are shorthand for disableCaching, indicatorText and loadScripts and are used to set their associated property on this UpdateManager instance.
11820      * @param {String/Object} params (optional) The parameters to pass as either a url encoded string "param1=1&amp;param2=2" or an object {param1: 1, param2: 2}
11821      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
11822      * @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.
11823      */
11824     update : function(url, params, callback, discardUrl){
11825         if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
11826             var method = this.method, cfg;
11827             if(typeof url == "object"){ // must be config object
11828                 cfg = url;
11829                 url = cfg.url;
11830                 params = params || cfg.params;
11831                 callback = callback || cfg.callback;
11832                 discardUrl = discardUrl || cfg.discardUrl;
11833                 if(callback && cfg.scope){
11834                     callback = callback.createDelegate(cfg.scope);
11835                 }
11836                 if(typeof cfg.method != "undefined"){method = cfg.method;};
11837                 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
11838                 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
11839                 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
11840                 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
11841             }
11842             this.showLoading();
11843             if(!discardUrl){
11844                 this.defaultUrl = url;
11845             }
11846             if(typeof url == "function"){
11847                 url = url.call(this);
11848             }
11849
11850             method = method || (params ? "POST" : "GET");
11851             if(method == "GET"){
11852                 url = this.prepareUrl(url);
11853             }
11854
11855             var o = Roo.apply(cfg ||{}, {
11856                 url : url,
11857                 params: params,
11858                 success: this.successDelegate,
11859                 failure: this.failureDelegate,
11860                 callback: undefined,
11861                 timeout: (this.timeout*1000),
11862                 argument: {"url": url, "form": null, "callback": callback, "params": params}
11863             });
11864
11865             this.transaction = Roo.Ajax.request(o);
11866         }
11867     },
11868
11869     /**
11870      * 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.
11871      * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.
11872      * @param {String/HTMLElement} form The form Id or form element
11873      * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
11874      * @param {Boolean} reset (optional) Whether to try to reset the form after the update
11875      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
11876      */
11877     formUpdate : function(form, url, reset, callback){
11878         if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
11879             if(typeof url == "function"){
11880                 url = url.call(this);
11881             }
11882             form = Roo.getDom(form);
11883             this.transaction = Roo.Ajax.request({
11884                 form: form,
11885                 url:url,
11886                 success: this.successDelegate,
11887                 failure: this.failureDelegate,
11888                 timeout: (this.timeout*1000),
11889                 argument: {"url": url, "form": form, "callback": callback, "reset": reset}
11890             });
11891             this.showLoading.defer(1, this);
11892         }
11893     },
11894
11895     /**
11896      * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
11897      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
11898      */
11899     refresh : function(callback){
11900         if(this.defaultUrl == null){
11901             return;
11902         }
11903         this.update(this.defaultUrl, null, callback, true);
11904     },
11905
11906     /**
11907      * Set this element to auto refresh.
11908      * @param {Number} interval How often to update (in seconds).
11909      * @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)
11910      * @param {String/Object} params (optional) The parameters to pass as either a url encoded string "&param1=1&param2=2" or as an object {param1: 1, param2: 2}
11911      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
11912      * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
11913      */
11914     startAutoRefresh : function(interval, url, params, callback, refreshNow){
11915         if(refreshNow){
11916             this.update(url || this.defaultUrl, params, callback, true);
11917         }
11918         if(this.autoRefreshProcId){
11919             clearInterval(this.autoRefreshProcId);
11920         }
11921         this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
11922     },
11923
11924     /**
11925      * Stop auto refresh on this element.
11926      */
11927      stopAutoRefresh : function(){
11928         if(this.autoRefreshProcId){
11929             clearInterval(this.autoRefreshProcId);
11930             delete this.autoRefreshProcId;
11931         }
11932     },
11933
11934     isAutoRefreshing : function(){
11935        return this.autoRefreshProcId ? true : false;
11936     },
11937     /**
11938      * Called to update the element to "Loading" state. Override to perform custom action.
11939      */
11940     showLoading : function(){
11941         if(this.showLoadIndicator){
11942             this.el.update(this.indicatorText);
11943         }
11944     },
11945
11946     /**
11947      * Adds unique parameter to query string if disableCaching = true
11948      * @private
11949      */
11950     prepareUrl : function(url){
11951         if(this.disableCaching){
11952             var append = "_dc=" + (new Date().getTime());
11953             if(url.indexOf("?") !== -1){
11954                 url += "&" + append;
11955             }else{
11956                 url += "?" + append;
11957             }
11958         }
11959         return url;
11960     },
11961
11962     /**
11963      * @private
11964      */
11965     processSuccess : function(response){
11966         this.transaction = null;
11967         if(response.argument.form && response.argument.reset){
11968             try{ // put in try/catch since some older FF releases had problems with this
11969                 response.argument.form.reset();
11970             }catch(e){}
11971         }
11972         if(this.loadScripts){
11973             this.renderer.render(this.el, response, this,
11974                 this.updateComplete.createDelegate(this, [response]));
11975         }else{
11976             this.renderer.render(this.el, response, this);
11977             this.updateComplete(response);
11978         }
11979     },
11980
11981     updateComplete : function(response){
11982         this.fireEvent("update", this.el, response);
11983         if(typeof response.argument.callback == "function"){
11984             response.argument.callback(this.el, true, response);
11985         }
11986     },
11987
11988     /**
11989      * @private
11990      */
11991     processFailure : function(response){
11992         this.transaction = null;
11993         this.fireEvent("failure", this.el, response);
11994         if(typeof response.argument.callback == "function"){
11995             response.argument.callback(this.el, false, response);
11996         }
11997     },
11998
11999     /**
12000      * Set the content renderer for this UpdateManager. See {@link Roo.UpdateManager.BasicRenderer#render} for more details.
12001      * @param {Object} renderer The object implementing the render() method
12002      */
12003     setRenderer : function(renderer){
12004         this.renderer = renderer;
12005     },
12006
12007     getRenderer : function(){
12008        return this.renderer;
12009     },
12010
12011     /**
12012      * Set the defaultUrl used for updates
12013      * @param {String/Function} defaultUrl The url or a function to call to get the url
12014      */
12015     setDefaultUrl : function(defaultUrl){
12016         this.defaultUrl = defaultUrl;
12017     },
12018
12019     /**
12020      * Aborts the executing transaction
12021      */
12022     abort : function(){
12023         if(this.transaction){
12024             Roo.Ajax.abort(this.transaction);
12025         }
12026     },
12027
12028     /**
12029      * Returns true if an update is in progress
12030      * @return {Boolean}
12031      */
12032     isUpdating : function(){
12033         if(this.transaction){
12034             return Roo.Ajax.isLoading(this.transaction);
12035         }
12036         return false;
12037     }
12038 });
12039
12040 /**
12041  * @class Roo.UpdateManager.defaults
12042  * @static (not really - but it helps the doc tool)
12043  * The defaults collection enables customizing the default properties of UpdateManager
12044  */
12045    Roo.UpdateManager.defaults = {
12046        /**
12047          * Timeout for requests or form posts in seconds (Defaults 30 seconds).
12048          * @type Number
12049          */
12050          timeout : 30,
12051
12052          /**
12053          * True to process scripts by default (Defaults to false).
12054          * @type Boolean
12055          */
12056         loadScripts : false,
12057
12058         /**
12059         * Blank page URL to use with SSL file uploads (Defaults to "javascript:false").
12060         * @type String
12061         */
12062         sslBlankUrl : (Roo.SSL_SECURE_URL || "javascript:false"),
12063         /**
12064          * Whether to append unique parameter on get request to disable caching (Defaults to false).
12065          * @type Boolean
12066          */
12067         disableCaching : false,
12068         /**
12069          * Whether to show indicatorText when loading (Defaults to true).
12070          * @type Boolean
12071          */
12072         showLoadIndicator : true,
12073         /**
12074          * Text for loading indicator (Defaults to '&lt;div class="loading-indicator"&gt;Loading...&lt;/div&gt;').
12075          * @type String
12076          */
12077         indicatorText : '<div class="loading-indicator">Loading...</div>'
12078    };
12079
12080 /**
12081  * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}).
12082  *Usage:
12083  * <pre><code>Roo.UpdateManager.updateElement("my-div", "stuff.php");</code></pre>
12084  * @param {String/HTMLElement/Roo.Element} el The element to update
12085  * @param {String} url The url
12086  * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
12087  * @param {Object} options (optional) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
12088  * @static
12089  * @deprecated
12090  * @member Roo.UpdateManager
12091  */
12092 Roo.UpdateManager.updateElement = function(el, url, params, options){
12093     var um = Roo.get(el, true).getUpdateManager();
12094     Roo.apply(um, options);
12095     um.update(url, params, options ? options.callback : null);
12096 };
12097 // alias for backwards compat
12098 Roo.UpdateManager.update = Roo.UpdateManager.updateElement;
12099 /**
12100  * @class Roo.UpdateManager.BasicRenderer
12101  * Default Content renderer. Updates the elements innerHTML with the responseText.
12102  */
12103 Roo.UpdateManager.BasicRenderer = function(){};
12104
12105 Roo.UpdateManager.BasicRenderer.prototype = {
12106     /**
12107      * This is called when the transaction is completed and it's time to update the element - The BasicRenderer
12108      * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),
12109      * create an object with a "render(el, response)" method and pass it to setRenderer on the UpdateManager.
12110      * @param {Roo.Element} el The element being rendered
12111      * @param {Object} response The YUI Connect response object
12112      * @param {UpdateManager} updateManager The calling update manager
12113      * @param {Function} callback A callback that will need to be called if loadScripts is true on the UpdateManager
12114      */
12115      render : function(el, response, updateManager, callback){
12116         el.update(response.responseText, updateManager.loadScripts, callback);
12117     }
12118 };
12119 /*
12120  * Based on:
12121  * Ext JS Library 1.1.1
12122  * Copyright(c) 2006-2007, Ext JS, LLC.
12123  *
12124  * Originally Released Under LGPL - original licence link has changed is not relivant.
12125  *
12126  * Fork - LGPL
12127  * <script type="text/javascript">
12128  */
12129
12130 /**
12131  * @class Roo.util.DelayedTask
12132  * Provides a convenient method of performing setTimeout where a new
12133  * timeout cancels the old timeout. An example would be performing validation on a keypress.
12134  * You can use this class to buffer
12135  * the keypress events for a certain number of milliseconds, and perform only if they stop
12136  * for that amount of time.
12137  * @constructor The parameters to this constructor serve as defaults and are not required.
12138  * @param {Function} fn (optional) The default function to timeout
12139  * @param {Object} scope (optional) The default scope of that timeout
12140  * @param {Array} args (optional) The default Array of arguments
12141  */
12142 Roo.util.DelayedTask = function(fn, scope, args){
12143     var id = null, d, t;
12144
12145     var call = function(){
12146         var now = new Date().getTime();
12147         if(now - t >= d){
12148             clearInterval(id);
12149             id = null;
12150             fn.apply(scope, args || []);
12151         }
12152     };
12153     /**
12154      * Cancels any pending timeout and queues a new one
12155      * @param {Number} delay The milliseconds to delay
12156      * @param {Function} newFn (optional) Overrides function passed to constructor
12157      * @param {Object} newScope (optional) Overrides scope passed to constructor
12158      * @param {Array} newArgs (optional) Overrides args passed to constructor
12159      */
12160     this.delay = function(delay, newFn, newScope, newArgs){
12161         if(id && delay != d){
12162             this.cancel();
12163         }
12164         d = delay;
12165         t = new Date().getTime();
12166         fn = newFn || fn;
12167         scope = newScope || scope;
12168         args = newArgs || args;
12169         if(!id){
12170             id = setInterval(call, d);
12171         }
12172     };
12173
12174     /**
12175      * Cancel the last queued timeout
12176      */
12177     this.cancel = function(){
12178         if(id){
12179             clearInterval(id);
12180             id = null;
12181         }
12182     };
12183 };/*
12184  * Based on:
12185  * Ext JS Library 1.1.1
12186  * Copyright(c) 2006-2007, Ext JS, LLC.
12187  *
12188  * Originally Released Under LGPL - original licence link has changed is not relivant.
12189  *
12190  * Fork - LGPL
12191  * <script type="text/javascript">
12192  */
12193  
12194  
12195 Roo.util.TaskRunner = function(interval){
12196     interval = interval || 10;
12197     var tasks = [], removeQueue = [];
12198     var id = 0;
12199     var running = false;
12200
12201     var stopThread = function(){
12202         running = false;
12203         clearInterval(id);
12204         id = 0;
12205     };
12206
12207     var startThread = function(){
12208         if(!running){
12209             running = true;
12210             id = setInterval(runTasks, interval);
12211         }
12212     };
12213
12214     var removeTask = function(task){
12215         removeQueue.push(task);
12216         if(task.onStop){
12217             task.onStop();
12218         }
12219     };
12220
12221     var runTasks = function(){
12222         if(removeQueue.length > 0){
12223             for(var i = 0, len = removeQueue.length; i < len; i++){
12224                 tasks.remove(removeQueue[i]);
12225             }
12226             removeQueue = [];
12227             if(tasks.length < 1){
12228                 stopThread();
12229                 return;
12230             }
12231         }
12232         var now = new Date().getTime();
12233         for(var i = 0, len = tasks.length; i < len; ++i){
12234             var t = tasks[i];
12235             var itime = now - t.taskRunTime;
12236             if(t.interval <= itime){
12237                 var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
12238                 t.taskRunTime = now;
12239                 if(rt === false || t.taskRunCount === t.repeat){
12240                     removeTask(t);
12241                     return;
12242                 }
12243             }
12244             if(t.duration && t.duration <= (now - t.taskStartTime)){
12245                 removeTask(t);
12246             }
12247         }
12248     };
12249
12250     /**
12251      * Queues a new task.
12252      * @param {Object} task
12253      */
12254     this.start = function(task){
12255         tasks.push(task);
12256         task.taskStartTime = new Date().getTime();
12257         task.taskRunTime = 0;
12258         task.taskRunCount = 0;
12259         startThread();
12260         return task;
12261     };
12262
12263     this.stop = function(task){
12264         removeTask(task);
12265         return task;
12266     };
12267
12268     this.stopAll = function(){
12269         stopThread();
12270         for(var i = 0, len = tasks.length; i < len; i++){
12271             if(tasks[i].onStop){
12272                 tasks[i].onStop();
12273             }
12274         }
12275         tasks = [];
12276         removeQueue = [];
12277     };
12278 };
12279
12280 Roo.TaskMgr = new Roo.util.TaskRunner();/*
12281  * Based on:
12282  * Ext JS Library 1.1.1
12283  * Copyright(c) 2006-2007, Ext JS, LLC.
12284  *
12285  * Originally Released Under LGPL - original licence link has changed is not relivant.
12286  *
12287  * Fork - LGPL
12288  * <script type="text/javascript">
12289  */
12290
12291  
12292 /**
12293  * @class Roo.util.MixedCollection
12294  * @extends Roo.util.Observable
12295  * A Collection class that maintains both numeric indexes and keys and exposes events.
12296  * @constructor
12297  * @param {Boolean} allowFunctions True if the addAll function should add function references to the
12298  * collection (defaults to false)
12299  * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
12300  * and return the key value for that item.  This is used when available to look up the key on items that
12301  * were passed without an explicit key parameter to a MixedCollection method.  Passing this parameter is
12302  * equivalent to providing an implementation for the {@link #getKey} method.
12303  */
12304 Roo.util.MixedCollection = function(allowFunctions, keyFn){
12305     this.items = [];
12306     this.map = {};
12307     this.keys = [];
12308     this.length = 0;
12309     this.addEvents({
12310         /**
12311          * @event clear
12312          * Fires when the collection is cleared.
12313          */
12314         "clear" : true,
12315         /**
12316          * @event add
12317          * Fires when an item is added to the collection.
12318          * @param {Number} index The index at which the item was added.
12319          * @param {Object} o The item added.
12320          * @param {String} key The key associated with the added item.
12321          */
12322         "add" : true,
12323         /**
12324          * @event replace
12325          * Fires when an item is replaced in the collection.
12326          * @param {String} key he key associated with the new added.
12327          * @param {Object} old The item being replaced.
12328          * @param {Object} new The new item.
12329          */
12330         "replace" : true,
12331         /**
12332          * @event remove
12333          * Fires when an item is removed from the collection.
12334          * @param {Object} o The item being removed.
12335          * @param {String} key (optional) The key associated with the removed item.
12336          */
12337         "remove" : true,
12338         "sort" : true
12339     });
12340     this.allowFunctions = allowFunctions === true;
12341     if(keyFn){
12342         this.getKey = keyFn;
12343     }
12344     Roo.util.MixedCollection.superclass.constructor.call(this);
12345 };
12346
12347 Roo.extend(Roo.util.MixedCollection, Roo.util.Observable, {
12348     allowFunctions : false,
12349     
12350 /**
12351  * Adds an item to the collection.
12352  * @param {String} key The key to associate with the item
12353  * @param {Object} o The item to add.
12354  * @return {Object} The item added.
12355  */
12356     add : function(key, o){
12357         if(arguments.length == 1){
12358             o = arguments[0];
12359             key = this.getKey(o);
12360         }
12361         if(typeof key == "undefined" || key === null){
12362             this.length++;
12363             this.items.push(o);
12364             this.keys.push(null);
12365         }else{
12366             var old = this.map[key];
12367             if(old){
12368                 return this.replace(key, o);
12369             }
12370             this.length++;
12371             this.items.push(o);
12372             this.map[key] = o;
12373             this.keys.push(key);
12374         }
12375         this.fireEvent("add", this.length-1, o, key);
12376         return o;
12377     },
12378        
12379 /**
12380   * MixedCollection has a generic way to fetch keys if you implement getKey.
12381 <pre><code>
12382 // normal way
12383 var mc = new Roo.util.MixedCollection();
12384 mc.add(someEl.dom.id, someEl);
12385 mc.add(otherEl.dom.id, otherEl);
12386 //and so on
12387
12388 // using getKey
12389 var mc = new Roo.util.MixedCollection();
12390 mc.getKey = function(el){
12391    return el.dom.id;
12392 };
12393 mc.add(someEl);
12394 mc.add(otherEl);
12395
12396 // or via the constructor
12397 var mc = new Roo.util.MixedCollection(false, function(el){
12398    return el.dom.id;
12399 });
12400 mc.add(someEl);
12401 mc.add(otherEl);
12402 </code></pre>
12403  * @param o {Object} The item for which to find the key.
12404  * @return {Object} The key for the passed item.
12405  */
12406     getKey : function(o){
12407          return o.id; 
12408     },
12409    
12410 /**
12411  * Replaces an item in the collection.
12412  * @param {String} key The key associated with the item to replace, or the item to replace.
12413  * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate with that key.
12414  * @return {Object}  The new item.
12415  */
12416     replace : function(key, o){
12417         if(arguments.length == 1){
12418             o = arguments[0];
12419             key = this.getKey(o);
12420         }
12421         var old = this.item(key);
12422         if(typeof key == "undefined" || key === null || typeof old == "undefined"){
12423              return this.add(key, o);
12424         }
12425         var index = this.indexOfKey(key);
12426         this.items[index] = o;
12427         this.map[key] = o;
12428         this.fireEvent("replace", key, old, o);
12429         return o;
12430     },
12431    
12432 /**
12433  * Adds all elements of an Array or an Object to the collection.
12434  * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
12435  * an Array of values, each of which are added to the collection.
12436  */
12437     addAll : function(objs){
12438         if(arguments.length > 1 || objs instanceof Array){
12439             var args = arguments.length > 1 ? arguments : objs;
12440             for(var i = 0, len = args.length; i < len; i++){
12441                 this.add(args[i]);
12442             }
12443         }else{
12444             for(var key in objs){
12445                 if(this.allowFunctions || typeof objs[key] != "function"){
12446                     this.add(key, objs[key]);
12447                 }
12448             }
12449         }
12450     },
12451    
12452 /**
12453  * Executes the specified function once for every item in the collection, passing each
12454  * item as the first and only parameter. returning false from the function will stop the iteration.
12455  * @param {Function} fn The function to execute for each item.
12456  * @param {Object} scope (optional) The scope in which to execute the function.
12457  */
12458     each : function(fn, scope){
12459         var items = [].concat(this.items); // each safe for removal
12460         for(var i = 0, len = items.length; i < len; i++){
12461             if(fn.call(scope || items[i], items[i], i, len) === false){
12462                 break;
12463             }
12464         }
12465     },
12466    
12467 /**
12468  * Executes the specified function once for every key in the collection, passing each
12469  * key, and its associated item as the first two parameters.
12470  * @param {Function} fn The function to execute for each item.
12471  * @param {Object} scope (optional) The scope in which to execute the function.
12472  */
12473     eachKey : function(fn, scope){
12474         for(var i = 0, len = this.keys.length; i < len; i++){
12475             fn.call(scope || window, this.keys[i], this.items[i], i, len);
12476         }
12477     },
12478    
12479 /**
12480  * Returns the first item in the collection which elicits a true return value from the
12481  * passed selection function.
12482  * @param {Function} fn The selection function to execute for each item.
12483  * @param {Object} scope (optional) The scope in which to execute the function.
12484  * @return {Object} The first item in the collection which returned true from the selection function.
12485  */
12486     find : function(fn, scope){
12487         for(var i = 0, len = this.items.length; i < len; i++){
12488             if(fn.call(scope || window, this.items[i], this.keys[i])){
12489                 return this.items[i];
12490             }
12491         }
12492         return null;
12493     },
12494    
12495 /**
12496  * Inserts an item at the specified index in the collection.
12497  * @param {Number} index The index to insert the item at.
12498  * @param {String} key The key to associate with the new item, or the item itself.
12499  * @param {Object} o  (optional) If the second parameter was a key, the new item.
12500  * @return {Object} The item inserted.
12501  */
12502     insert : function(index, key, o){
12503         if(arguments.length == 2){
12504             o = arguments[1];
12505             key = this.getKey(o);
12506         }
12507         if(index >= this.length){
12508             return this.add(key, o);
12509         }
12510         this.length++;
12511         this.items.splice(index, 0, o);
12512         if(typeof key != "undefined" && key != null){
12513             this.map[key] = o;
12514         }
12515         this.keys.splice(index, 0, key);
12516         this.fireEvent("add", index, o, key);
12517         return o;
12518     },
12519    
12520 /**
12521  * Removed an item from the collection.
12522  * @param {Object} o The item to remove.
12523  * @return {Object} The item removed.
12524  */
12525     remove : function(o){
12526         return this.removeAt(this.indexOf(o));
12527     },
12528    
12529 /**
12530  * Remove an item from a specified index in the collection.
12531  * @param {Number} index The index within the collection of the item to remove.
12532  */
12533     removeAt : function(index){
12534         if(index < this.length && index >= 0){
12535             this.length--;
12536             var o = this.items[index];
12537             this.items.splice(index, 1);
12538             var key = this.keys[index];
12539             if(typeof key != "undefined"){
12540                 delete this.map[key];
12541             }
12542             this.keys.splice(index, 1);
12543             this.fireEvent("remove", o, key);
12544         }
12545     },
12546    
12547 /**
12548  * Removed an item associated with the passed key fom the collection.
12549  * @param {String} key The key of the item to remove.
12550  */
12551     removeKey : function(key){
12552         return this.removeAt(this.indexOfKey(key));
12553     },
12554    
12555 /**
12556  * Returns the number of items in the collection.
12557  * @return {Number} the number of items in the collection.
12558  */
12559     getCount : function(){
12560         return this.length; 
12561     },
12562    
12563 /**
12564  * Returns index within the collection of the passed Object.
12565  * @param {Object} o The item to find the index of.
12566  * @return {Number} index of the item.
12567  */
12568     indexOf : function(o){
12569         if(!this.items.indexOf){
12570             for(var i = 0, len = this.items.length; i < len; i++){
12571                 if(this.items[i] == o) return i;
12572             }
12573             return -1;
12574         }else{
12575             return this.items.indexOf(o);
12576         }
12577     },
12578    
12579 /**
12580  * Returns index within the collection of the passed key.
12581  * @param {String} key The key to find the index of.
12582  * @return {Number} index of the key.
12583  */
12584     indexOfKey : function(key){
12585         if(!this.keys.indexOf){
12586             for(var i = 0, len = this.keys.length; i < len; i++){
12587                 if(this.keys[i] == key) return i;
12588             }
12589             return -1;
12590         }else{
12591             return this.keys.indexOf(key);
12592         }
12593     },
12594    
12595 /**
12596  * Returns the item associated with the passed key OR index. Key has priority over index.
12597  * @param {String/Number} key The key or index of the item.
12598  * @return {Object} The item associated with the passed key.
12599  */
12600     item : function(key){
12601         var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
12602         return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
12603     },
12604     
12605 /**
12606  * Returns the item at the specified index.
12607  * @param {Number} index The index of the item.
12608  * @return {Object}
12609  */
12610     itemAt : function(index){
12611         return this.items[index];
12612     },
12613     
12614 /**
12615  * Returns the item associated with the passed key.
12616  * @param {String/Number} key The key of the item.
12617  * @return {Object} The item associated with the passed key.
12618  */
12619     key : function(key){
12620         return this.map[key];
12621     },
12622    
12623 /**
12624  * Returns true if the collection contains the passed Object as an item.
12625  * @param {Object} o  The Object to look for in the collection.
12626  * @return {Boolean} True if the collection contains the Object as an item.
12627  */
12628     contains : function(o){
12629         return this.indexOf(o) != -1;
12630     },
12631    
12632 /**
12633  * Returns true if the collection contains the passed Object as a key.
12634  * @param {String} key The key to look for in the collection.
12635  * @return {Boolean} True if the collection contains the Object as a key.
12636  */
12637     containsKey : function(key){
12638         return typeof this.map[key] != "undefined";
12639     },
12640    
12641 /**
12642  * Removes all items from the collection.
12643  */
12644     clear : function(){
12645         this.length = 0;
12646         this.items = [];
12647         this.keys = [];
12648         this.map = {};
12649         this.fireEvent("clear");
12650     },
12651    
12652 /**
12653  * Returns the first item in the collection.
12654  * @return {Object} the first item in the collection..
12655  */
12656     first : function(){
12657         return this.items[0]; 
12658     },
12659    
12660 /**
12661  * Returns the last item in the collection.
12662  * @return {Object} the last item in the collection..
12663  */
12664     last : function(){
12665         return this.items[this.length-1];   
12666     },
12667     
12668     _sort : function(property, dir, fn){
12669         var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
12670         fn = fn || function(a, b){
12671             return a-b;
12672         };
12673         var c = [], k = this.keys, items = this.items;
12674         for(var i = 0, len = items.length; i < len; i++){
12675             c[c.length] = {key: k[i], value: items[i], index: i};
12676         }
12677         c.sort(function(a, b){
12678             var v = fn(a[property], b[property]) * dsc;
12679             if(v == 0){
12680                 v = (a.index < b.index ? -1 : 1);
12681             }
12682             return v;
12683         });
12684         for(var i = 0, len = c.length; i < len; i++){
12685             items[i] = c[i].value;
12686             k[i] = c[i].key;
12687         }
12688         this.fireEvent("sort", this);
12689     },
12690     
12691     /**
12692      * Sorts this collection with the passed comparison function
12693      * @param {String} direction (optional) "ASC" or "DESC"
12694      * @param {Function} fn (optional) comparison function
12695      */
12696     sort : function(dir, fn){
12697         this._sort("value", dir, fn);
12698     },
12699     
12700     /**
12701      * Sorts this collection by keys
12702      * @param {String} direction (optional) "ASC" or "DESC"
12703      * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
12704      */
12705     keySort : function(dir, fn){
12706         this._sort("key", dir, fn || function(a, b){
12707             return String(a).toUpperCase()-String(b).toUpperCase();
12708         });
12709     },
12710     
12711     /**
12712      * Returns a range of items in this collection
12713      * @param {Number} startIndex (optional) defaults to 0
12714      * @param {Number} endIndex (optional) default to the last item
12715      * @return {Array} An array of items
12716      */
12717     getRange : function(start, end){
12718         var items = this.items;
12719         if(items.length < 1){
12720             return [];
12721         }
12722         start = start || 0;
12723         end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
12724         var r = [];
12725         if(start <= end){
12726             for(var i = start; i <= end; i++) {
12727                     r[r.length] = items[i];
12728             }
12729         }else{
12730             for(var i = start; i >= end; i--) {
12731                     r[r.length] = items[i];
12732             }
12733         }
12734         return r;
12735     },
12736         
12737     /**
12738      * Filter the <i>objects</i> in this collection by a specific property. 
12739      * Returns a new collection that has been filtered.
12740      * @param {String} property A property on your objects
12741      * @param {String/RegExp} value Either string that the property values 
12742      * should start with or a RegExp to test against the property
12743      * @return {MixedCollection} The new filtered collection
12744      */
12745     filter : function(property, value){
12746         if(!value.exec){ // not a regex
12747             value = String(value);
12748             if(value.length == 0){
12749                 return this.clone();
12750             }
12751             value = new RegExp("^" + Roo.escapeRe(value), "i");
12752         }
12753         return this.filterBy(function(o){
12754             return o && value.test(o[property]);
12755         });
12756         },
12757     
12758     /**
12759      * Filter by a function. * Returns a new collection that has been filtered.
12760      * The passed function will be called with each 
12761      * object in the collection. If the function returns true, the value is included 
12762      * otherwise it is filtered.
12763      * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
12764      * @param {Object} scope (optional) The scope of the function (defaults to this) 
12765      * @return {MixedCollection} The new filtered collection
12766      */
12767     filterBy : function(fn, scope){
12768         var r = new Roo.util.MixedCollection();
12769         r.getKey = this.getKey;
12770         var k = this.keys, it = this.items;
12771         for(var i = 0, len = it.length; i < len; i++){
12772             if(fn.call(scope||this, it[i], k[i])){
12773                                 r.add(k[i], it[i]);
12774                         }
12775         }
12776         return r;
12777     },
12778     
12779     /**
12780      * Creates a duplicate of this collection
12781      * @return {MixedCollection}
12782      */
12783     clone : function(){
12784         var r = new Roo.util.MixedCollection();
12785         var k = this.keys, it = this.items;
12786         for(var i = 0, len = it.length; i < len; i++){
12787             r.add(k[i], it[i]);
12788         }
12789         r.getKey = this.getKey;
12790         return r;
12791     }
12792 });
12793 /**
12794  * Returns the item associated with the passed key or index.
12795  * @method
12796  * @param {String/Number} key The key or index of the item.
12797  * @return {Object} The item associated with the passed key.
12798  */
12799 Roo.util.MixedCollection.prototype.get = Roo.util.MixedCollection.prototype.item;/*
12800  * Based on:
12801  * Ext JS Library 1.1.1
12802  * Copyright(c) 2006-2007, Ext JS, LLC.
12803  *
12804  * Originally Released Under LGPL - original licence link has changed is not relivant.
12805  *
12806  * Fork - LGPL
12807  * <script type="text/javascript">
12808  */
12809 /**
12810  * @class Roo.util.JSON
12811  * Modified version of Douglas Crockford"s json.js that doesn"t
12812  * mess with the Object prototype 
12813  * http://www.json.org/js.html
12814  * @singleton
12815  */
12816 Roo.util.JSON = new (function(){
12817     var useHasOwn = {}.hasOwnProperty ? true : false;
12818     
12819     // crashes Safari in some instances
12820     //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
12821     
12822     var pad = function(n) {
12823         return n < 10 ? "0" + n : n;
12824     };
12825     
12826     var m = {
12827         "\b": '\\b',
12828         "\t": '\\t',
12829         "\n": '\\n',
12830         "\f": '\\f',
12831         "\r": '\\r',
12832         '"' : '\\"',
12833         "\\": '\\\\'
12834     };
12835
12836     var encodeString = function(s){
12837         if (/["\\\x00-\x1f]/.test(s)) {
12838             return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
12839                 var c = m[b];
12840                 if(c){
12841                     return c;
12842                 }
12843                 c = b.charCodeAt();
12844                 return "\\u00" +
12845                     Math.floor(c / 16).toString(16) +
12846                     (c % 16).toString(16);
12847             }) + '"';
12848         }
12849         return '"' + s + '"';
12850     };
12851     
12852     var encodeArray = function(o){
12853         var a = ["["], b, i, l = o.length, v;
12854             for (i = 0; i < l; i += 1) {
12855                 v = o[i];
12856                 switch (typeof v) {
12857                     case "undefined":
12858                     case "function":
12859                     case "unknown":
12860                         break;
12861                     default:
12862                         if (b) {
12863                             a.push(',');
12864                         }
12865                         a.push(v === null ? "null" : Roo.util.JSON.encode(v));
12866                         b = true;
12867                 }
12868             }
12869             a.push("]");
12870             return a.join("");
12871     };
12872     
12873     var encodeDate = function(o){
12874         return '"' + o.getFullYear() + "-" +
12875                 pad(o.getMonth() + 1) + "-" +
12876                 pad(o.getDate()) + "T" +
12877                 pad(o.getHours()) + ":" +
12878                 pad(o.getMinutes()) + ":" +
12879                 pad(o.getSeconds()) + '"';
12880     };
12881     
12882     /**
12883      * Encodes an Object, Array or other value
12884      * @param {Mixed} o The variable to encode
12885      * @return {String} The JSON string
12886      */
12887     this.encode = function(o)
12888     {
12889         // should this be extended to fully wrap stringify..
12890         
12891         if(typeof o == "undefined" || o === null){
12892             return "null";
12893         }else if(o instanceof Array){
12894             return encodeArray(o);
12895         }else if(o instanceof Date){
12896             return encodeDate(o);
12897         }else if(typeof o == "string"){
12898             return encodeString(o);
12899         }else if(typeof o == "number"){
12900             return isFinite(o) ? String(o) : "null";
12901         }else if(typeof o == "boolean"){
12902             return String(o);
12903         }else {
12904             var a = ["{"], b, i, v;
12905             for (i in o) {
12906                 if(!useHasOwn || o.hasOwnProperty(i)) {
12907                     v = o[i];
12908                     switch (typeof v) {
12909                     case "undefined":
12910                     case "function":
12911                     case "unknown":
12912                         break;
12913                     default:
12914                         if(b){
12915                             a.push(',');
12916                         }
12917                         a.push(this.encode(i), ":",
12918                                 v === null ? "null" : this.encode(v));
12919                         b = true;
12920                     }
12921                 }
12922             }
12923             a.push("}");
12924             return a.join("");
12925         }
12926     };
12927     
12928     /**
12929      * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
12930      * @param {String} json The JSON string
12931      * @return {Object} The resulting object
12932      */
12933     this.decode = function(json){
12934         
12935         return  /** eval:var:json */ eval("(" + json + ')');
12936     };
12937 })();
12938 /** 
12939  * Shorthand for {@link Roo.util.JSON#encode}
12940  * @member Roo encode 
12941  * @method */
12942 Roo.encode = typeof(JSON) != 'undefined' && JSON.stringify ? JSON.stringify : Roo.util.JSON.encode;
12943 /** 
12944  * Shorthand for {@link Roo.util.JSON#decode}
12945  * @member Roo decode 
12946  * @method */
12947 Roo.decode = typeof(JSON) != 'undefined' && JSON.parse ? JSON.parse : Roo.util.JSON.decode;
12948 /*
12949  * Based on:
12950  * Ext JS Library 1.1.1
12951  * Copyright(c) 2006-2007, Ext JS, LLC.
12952  *
12953  * Originally Released Under LGPL - original licence link has changed is not relivant.
12954  *
12955  * Fork - LGPL
12956  * <script type="text/javascript">
12957  */
12958  
12959 /**
12960  * @class Roo.util.Format
12961  * Reusable data formatting functions
12962  * @singleton
12963  */
12964 Roo.util.Format = function(){
12965     var trimRe = /^\s+|\s+$/g;
12966     return {
12967         /**
12968          * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
12969          * @param {String} value The string to truncate
12970          * @param {Number} length The maximum length to allow before truncating
12971          * @return {String} The converted text
12972          */
12973         ellipsis : function(value, len){
12974             if(value && value.length > len){
12975                 return value.substr(0, len-3)+"...";
12976             }
12977             return value;
12978         },
12979
12980         /**
12981          * Checks a reference and converts it to empty string if it is undefined
12982          * @param {Mixed} value Reference to check
12983          * @return {Mixed} Empty string if converted, otherwise the original value
12984          */
12985         undef : function(value){
12986             return typeof value != "undefined" ? value : "";
12987         },
12988
12989         /**
12990          * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
12991          * @param {String} value The string to encode
12992          * @return {String} The encoded text
12993          */
12994         htmlEncode : function(value){
12995             return !value ? value : String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
12996         },
12997
12998         /**
12999          * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
13000          * @param {String} value The string to decode
13001          * @return {String} The decoded text
13002          */
13003         htmlDecode : function(value){
13004             return !value ? value : String(value).replace(/&amp;/g, "&").replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"');
13005         },
13006
13007         /**
13008          * Trims any whitespace from either side of a string
13009          * @param {String} value The text to trim
13010          * @return {String} The trimmed text
13011          */
13012         trim : function(value){
13013             return String(value).replace(trimRe, "");
13014         },
13015
13016         /**
13017          * Returns a substring from within an original string
13018          * @param {String} value The original text
13019          * @param {Number} start The start index of the substring
13020          * @param {Number} length The length of the substring
13021          * @return {String} The substring
13022          */
13023         substr : function(value, start, length){
13024             return String(value).substr(start, length);
13025         },
13026
13027         /**
13028          * Converts a string to all lower case letters
13029          * @param {String} value The text to convert
13030          * @return {String} The converted text
13031          */
13032         lowercase : function(value){
13033             return String(value).toLowerCase();
13034         },
13035
13036         /**
13037          * Converts a string to all upper case letters
13038          * @param {String} value The text to convert
13039          * @return {String} The converted text
13040          */
13041         uppercase : function(value){
13042             return String(value).toUpperCase();
13043         },
13044
13045         /**
13046          * Converts the first character only of a string to upper case
13047          * @param {String} value The text to convert
13048          * @return {String} The converted text
13049          */
13050         capitalize : function(value){
13051             return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
13052         },
13053
13054         // private
13055         call : function(value, fn){
13056             if(arguments.length > 2){
13057                 var args = Array.prototype.slice.call(arguments, 2);
13058                 args.unshift(value);
13059                  
13060                 return /** eval:var:value */  eval(fn).apply(window, args);
13061             }else{
13062                 /** eval:var:value */
13063                 return /** eval:var:value */ eval(fn).call(window, value);
13064             }
13065         },
13066
13067        
13068         /**
13069          * safer version of Math.toFixed..??/
13070          * @param {Number/String} value The numeric value to format
13071          * @param {Number/String} value Decimal places 
13072          * @return {String} The formatted currency string
13073          */
13074         toFixed : function(v, n)
13075         {
13076             // why not use to fixed - precision is buggered???
13077             if (!n) {
13078                 return Math.round(v-0);
13079             }
13080             var fact = Math.pow(10,n+1);
13081             v = (Math.round((v-0)*fact))/fact;
13082             var z = (''+fact).substring(2);
13083             if (v == Math.floor(v)) {
13084                 return Math.floor(v) + '.' + z;
13085             }
13086             
13087             // now just padd decimals..
13088             var ps = String(v).split('.');
13089             var fd = (ps[1] + z);
13090             var r = fd.substring(0,n); 
13091             var rm = fd.substring(n); 
13092             if (rm < 5) {
13093                 return ps[0] + '.' + r;
13094             }
13095             r*=1; // turn it into a number;
13096             r++;
13097             if (String(r).length != n) {
13098                 ps[0]*=1;
13099                 ps[0]++;
13100                 r = String(r).substring(1); // chop the end off.
13101             }
13102             
13103             return ps[0] + '.' + r;
13104              
13105         },
13106         
13107         /**
13108          * Format a number as US currency
13109          * @param {Number/String} value The numeric value to format
13110          * @return {String} The formatted currency string
13111          */
13112         usMoney : function(v){
13113             v = (Math.round((v-0)*100))/100;
13114             v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
13115             v = String(v);
13116             var ps = v.split('.');
13117             var whole = ps[0];
13118             var sub = ps[1] ? '.'+ ps[1] : '.00';
13119             var r = /(\d+)(\d{3})/;
13120             while (r.test(whole)) {
13121                 whole = whole.replace(r, '$1' + ',' + '$2');
13122             }
13123             return "$" + whole + sub ;
13124         },
13125         
13126         /**
13127          * Parse a value into a formatted date using the specified format pattern.
13128          * @param {Mixed} value The value to format
13129          * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
13130          * @return {String} The formatted date string
13131          */
13132         date : function(v, format){
13133             if(!v){
13134                 return "";
13135             }
13136             if(!(v instanceof Date)){
13137                 v = new Date(Date.parse(v));
13138             }
13139             return v.dateFormat(format || "m/d/Y");
13140         },
13141
13142         /**
13143          * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
13144          * @param {String} format Any valid date format string
13145          * @return {Function} The date formatting function
13146          */
13147         dateRenderer : function(format){
13148             return function(v){
13149                 return Roo.util.Format.date(v, format);  
13150             };
13151         },
13152
13153         // private
13154         stripTagsRE : /<\/?[^>]+>/gi,
13155         
13156         /**
13157          * Strips all HTML tags
13158          * @param {Mixed} value The text from which to strip tags
13159          * @return {String} The stripped text
13160          */
13161         stripTags : function(v){
13162             return !v ? v : String(v).replace(this.stripTagsRE, "");
13163         }
13164     };
13165 }();/*
13166  * Based on:
13167  * Ext JS Library 1.1.1
13168  * Copyright(c) 2006-2007, Ext JS, LLC.
13169  *
13170  * Originally Released Under LGPL - original licence link has changed is not relivant.
13171  *
13172  * Fork - LGPL
13173  * <script type="text/javascript">
13174  */
13175
13176
13177  
13178
13179 /**
13180  * @class Roo.MasterTemplate
13181  * @extends Roo.Template
13182  * Provides a template that can have child templates. The syntax is:
13183 <pre><code>
13184 var t = new Roo.MasterTemplate(
13185         '&lt;select name="{name}"&gt;',
13186                 '&lt;tpl name="options"&gt;&lt;option value="{value:trim}"&gt;{text:ellipsis(10)}&lt;/option&gt;&lt;/tpl&gt;',
13187         '&lt;/select&gt;'
13188 );
13189 t.add('options', {value: 'foo', text: 'bar'});
13190 // or you can add multiple child elements in one shot
13191 t.addAll('options', [
13192     {value: 'foo', text: 'bar'},
13193     {value: 'foo2', text: 'bar2'},
13194     {value: 'foo3', text: 'bar3'}
13195 ]);
13196 // then append, applying the master template values
13197 t.append('my-form', {name: 'my-select'});
13198 </code></pre>
13199 * A name attribute for the child template is not required if you have only one child
13200 * template or you want to refer to them by index.
13201  */
13202 Roo.MasterTemplate = function(){
13203     Roo.MasterTemplate.superclass.constructor.apply(this, arguments);
13204     this.originalHtml = this.html;
13205     var st = {};
13206     var m, re = this.subTemplateRe;
13207     re.lastIndex = 0;
13208     var subIndex = 0;
13209     while(m = re.exec(this.html)){
13210         var name = m[1], content = m[2];
13211         st[subIndex] = {
13212             name: name,
13213             index: subIndex,
13214             buffer: [],
13215             tpl : new Roo.Template(content)
13216         };
13217         if(name){
13218             st[name] = st[subIndex];
13219         }
13220         st[subIndex].tpl.compile();
13221         st[subIndex].tpl.call = this.call.createDelegate(this);
13222         subIndex++;
13223     }
13224     this.subCount = subIndex;
13225     this.subs = st;
13226 };
13227 Roo.extend(Roo.MasterTemplate, Roo.Template, {
13228     /**
13229     * The regular expression used to match sub templates
13230     * @type RegExp
13231     * @property
13232     */
13233     subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi,
13234
13235     /**
13236      * Applies the passed values to a child template.
13237      * @param {String/Number} name (optional) The name or index of the child template
13238      * @param {Array/Object} values The values to be applied to the template
13239      * @return {MasterTemplate} this
13240      */
13241      add : function(name, values){
13242         if(arguments.length == 1){
13243             values = arguments[0];
13244             name = 0;
13245         }
13246         var s = this.subs[name];
13247         s.buffer[s.buffer.length] = s.tpl.apply(values);
13248         return this;
13249     },
13250
13251     /**
13252      * Applies all the passed values to a child template.
13253      * @param {String/Number} name (optional) The name or index of the child template
13254      * @param {Array} values The values to be applied to the template, this should be an array of objects.
13255      * @param {Boolean} reset (optional) True to reset the template first
13256      * @return {MasterTemplate} this
13257      */
13258     fill : function(name, values, reset){
13259         var a = arguments;
13260         if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){
13261             values = a[0];
13262             name = 0;
13263             reset = a[1];
13264         }
13265         if(reset){
13266             this.reset();
13267         }
13268         for(var i = 0, len = values.length; i < len; i++){
13269             this.add(name, values[i]);
13270         }
13271         return this;
13272     },
13273
13274     /**
13275      * Resets the template for reuse
13276      * @return {MasterTemplate} this
13277      */
13278      reset : function(){
13279         var s = this.subs;
13280         for(var i = 0; i < this.subCount; i++){
13281             s[i].buffer = [];
13282         }
13283         return this;
13284     },
13285
13286     applyTemplate : function(values){
13287         var s = this.subs;
13288         var replaceIndex = -1;
13289         this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){
13290             return s[++replaceIndex].buffer.join("");
13291         });
13292         return Roo.MasterTemplate.superclass.applyTemplate.call(this, values);
13293     },
13294
13295     apply : function(){
13296         return this.applyTemplate.apply(this, arguments);
13297     },
13298
13299     compile : function(){return this;}
13300 });
13301
13302 /**
13303  * Alias for fill().
13304  * @method
13305  */
13306 Roo.MasterTemplate.prototype.addAll = Roo.MasterTemplate.prototype.fill;
13307  /**
13308  * Creates a template from the passed element's value (display:none textarea, preferred) or innerHTML. e.g.
13309  * var tpl = Roo.MasterTemplate.from('element-id');
13310  * @param {String/HTMLElement} el
13311  * @param {Object} config
13312  * @static
13313  */
13314 Roo.MasterTemplate.from = function(el, config){
13315     el = Roo.getDom(el);
13316     return new Roo.MasterTemplate(el.value || el.innerHTML, config || '');
13317 };/*
13318  * Based on:
13319  * Ext JS Library 1.1.1
13320  * Copyright(c) 2006-2007, Ext JS, LLC.
13321  *
13322  * Originally Released Under LGPL - original licence link has changed is not relivant.
13323  *
13324  * Fork - LGPL
13325  * <script type="text/javascript">
13326  */
13327
13328  
13329 /**
13330  * @class Roo.util.CSS
13331  * Utility class for manipulating CSS rules
13332  * @singleton
13333  */
13334 Roo.util.CSS = function(){
13335         var rules = null;
13336         var doc = document;
13337
13338     var camelRe = /(-[a-z])/gi;
13339     var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
13340
13341    return {
13342    /**
13343     * Very simple dynamic creation of stylesheets from a text blob of rules.  The text will wrapped in a style
13344     * tag and appended to the HEAD of the document.
13345     * @param {String|Object} cssText The text containing the css rules
13346     * @param {String} id An id to add to the stylesheet for later removal
13347     * @return {StyleSheet}
13348     */
13349     createStyleSheet : function(cssText, id){
13350         var ss;
13351         var head = doc.getElementsByTagName("head")[0];
13352         var nrules = doc.createElement("style");
13353         nrules.setAttribute("type", "text/css");
13354         if(id){
13355             nrules.setAttribute("id", id);
13356         }
13357         if (typeof(cssText) != 'string') {
13358             // support object maps..
13359             // not sure if this a good idea.. 
13360             // perhaps it should be merged with the general css handling
13361             // and handle js style props.
13362             var cssTextNew = [];
13363             for(var n in cssText) {
13364                 var citems = [];
13365                 for(var k in cssText[n]) {
13366                     citems.push( k + ' : ' +cssText[n][k] + ';' );
13367                 }
13368                 cssTextNew.push( n + ' { ' + citems.join(' ') + '} ');
13369                 
13370             }
13371             cssText = cssTextNew.join("\n");
13372             
13373         }
13374        
13375        
13376        if(Roo.isIE){
13377            head.appendChild(nrules);
13378            ss = nrules.styleSheet;
13379            ss.cssText = cssText;
13380        }else{
13381            try{
13382                 nrules.appendChild(doc.createTextNode(cssText));
13383            }catch(e){
13384                nrules.cssText = cssText; 
13385            }
13386            head.appendChild(nrules);
13387            ss = nrules.styleSheet ? nrules.styleSheet : (nrules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
13388        }
13389        this.cacheStyleSheet(ss);
13390        return ss;
13391    },
13392
13393    /**
13394     * Removes a style or link tag by id
13395     * @param {String} id The id of the tag
13396     */
13397    removeStyleSheet : function(id){
13398        var existing = doc.getElementById(id);
13399        if(existing){
13400            existing.parentNode.removeChild(existing);
13401        }
13402    },
13403
13404    /**
13405     * Dynamically swaps an existing stylesheet reference for a new one
13406     * @param {String} id The id of an existing link tag to remove
13407     * @param {String} url The href of the new stylesheet to include
13408     */
13409    swapStyleSheet : function(id, url){
13410        this.removeStyleSheet(id);
13411        var ss = doc.createElement("link");
13412        ss.setAttribute("rel", "stylesheet");
13413        ss.setAttribute("type", "text/css");
13414        ss.setAttribute("id", id);
13415        ss.setAttribute("href", url);
13416        doc.getElementsByTagName("head")[0].appendChild(ss);
13417    },
13418    
13419    /**
13420     * Refresh the rule cache if you have dynamically added stylesheets
13421     * @return {Object} An object (hash) of rules indexed by selector
13422     */
13423    refreshCache : function(){
13424        return this.getRules(true);
13425    },
13426
13427    // private
13428    cacheStyleSheet : function(stylesheet){
13429        if(!rules){
13430            rules = {};
13431        }
13432        try{// try catch for cross domain access issue
13433            var ssRules = stylesheet.cssRules || stylesheet.rules;
13434            for(var j = ssRules.length-1; j >= 0; --j){
13435                rules[ssRules[j].selectorText] = ssRules[j];
13436            }
13437        }catch(e){}
13438    },
13439    
13440    /**
13441     * Gets all css rules for the document
13442     * @param {Boolean} refreshCache true to refresh the internal cache
13443     * @return {Object} An object (hash) of rules indexed by selector
13444     */
13445    getRules : function(refreshCache){
13446                 if(rules == null || refreshCache){
13447                         rules = {};
13448                         var ds = doc.styleSheets;
13449                         for(var i =0, len = ds.length; i < len; i++){
13450                             try{
13451                         this.cacheStyleSheet(ds[i]);
13452                     }catch(e){} 
13453                 }
13454                 }
13455                 return rules;
13456         },
13457         
13458         /**
13459     * Gets an an individual CSS rule by selector(s)
13460     * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
13461     * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
13462     * @return {CSSRule} The CSS rule or null if one is not found
13463     */
13464    getRule : function(selector, refreshCache){
13465                 var rs = this.getRules(refreshCache);
13466                 if(!(selector instanceof Array)){
13467                     return rs[selector];
13468                 }
13469                 for(var i = 0; i < selector.length; i++){
13470                         if(rs[selector[i]]){
13471                                 return rs[selector[i]];
13472                         }
13473                 }
13474                 return null;
13475         },
13476         
13477         
13478         /**
13479     * Updates a rule property
13480     * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
13481     * @param {String} property The css property
13482     * @param {String} value The new value for the property
13483     * @return {Boolean} true If a rule was found and updated
13484     */
13485    updateRule : function(selector, property, value){
13486                 if(!(selector instanceof Array)){
13487                         var rule = this.getRule(selector);
13488                         if(rule){
13489                                 rule.style[property.replace(camelRe, camelFn)] = value;
13490                                 return true;
13491                         }
13492                 }else{
13493                         for(var i = 0; i < selector.length; i++){
13494                                 if(this.updateRule(selector[i], property, value)){
13495                                         return true;
13496                                 }
13497                         }
13498                 }
13499                 return false;
13500         }
13501    };   
13502 }();/*
13503  * Based on:
13504  * Ext JS Library 1.1.1
13505  * Copyright(c) 2006-2007, Ext JS, LLC.
13506  *
13507  * Originally Released Under LGPL - original licence link has changed is not relivant.
13508  *
13509  * Fork - LGPL
13510  * <script type="text/javascript">
13511  */
13512
13513  
13514
13515 /**
13516  * @class Roo.util.ClickRepeater
13517  * @extends Roo.util.Observable
13518  * 
13519  * A wrapper class which can be applied to any element. Fires a "click" event while the
13520  * mouse is pressed. The interval between firings may be specified in the config but
13521  * defaults to 10 milliseconds.
13522  * 
13523  * Optionally, a CSS class may be applied to the element during the time it is pressed.
13524  * 
13525  * @cfg {String/HTMLElement/Element} el The element to act as a button.
13526  * @cfg {Number} delay The initial delay before the repeating event begins firing.
13527  * Similar to an autorepeat key delay.
13528  * @cfg {Number} interval The interval between firings of the "click" event. Default 10 ms.
13529  * @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
13530  * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
13531  *           "interval" and "delay" are ignored. "immediate" is honored.
13532  * @cfg {Boolean} preventDefault True to prevent the default click event
13533  * @cfg {Boolean} stopDefault True to stop the default click event
13534  * 
13535  * @history
13536  *     2007-02-02 jvs Original code contributed by Nige "Animal" White
13537  *     2007-02-02 jvs Renamed to ClickRepeater
13538  *   2007-02-03 jvs Modifications for FF Mac and Safari 
13539  *
13540  *  @constructor
13541  * @param {String/HTMLElement/Element} el The element to listen on
13542  * @param {Object} config
13543  **/
13544 Roo.util.ClickRepeater = function(el, config)
13545 {
13546     this.el = Roo.get(el);
13547     this.el.unselectable();
13548
13549     Roo.apply(this, config);
13550
13551     this.addEvents({
13552     /**
13553      * @event mousedown
13554      * Fires when the mouse button is depressed.
13555      * @param {Roo.util.ClickRepeater} this
13556      */
13557         "mousedown" : true,
13558     /**
13559      * @event click
13560      * Fires on a specified interval during the time the element is pressed.
13561      * @param {Roo.util.ClickRepeater} this
13562      */
13563         "click" : true,
13564     /**
13565      * @event mouseup
13566      * Fires when the mouse key is released.
13567      * @param {Roo.util.ClickRepeater} this
13568      */
13569         "mouseup" : true
13570     });
13571
13572     this.el.on("mousedown", this.handleMouseDown, this);
13573     if(this.preventDefault || this.stopDefault){
13574         this.el.on("click", function(e){
13575             if(this.preventDefault){
13576                 e.preventDefault();
13577             }
13578             if(this.stopDefault){
13579                 e.stopEvent();
13580             }
13581         }, this);
13582     }
13583
13584     // allow inline handler
13585     if(this.handler){
13586         this.on("click", this.handler,  this.scope || this);
13587     }
13588
13589     Roo.util.ClickRepeater.superclass.constructor.call(this);
13590 };
13591
13592 Roo.extend(Roo.util.ClickRepeater, Roo.util.Observable, {
13593     interval : 20,
13594     delay: 250,
13595     preventDefault : true,
13596     stopDefault : false,
13597     timer : 0,
13598
13599     // private
13600     handleMouseDown : function(){
13601         clearTimeout(this.timer);
13602         this.el.blur();
13603         if(this.pressClass){
13604             this.el.addClass(this.pressClass);
13605         }
13606         this.mousedownTime = new Date();
13607
13608         Roo.get(document).on("mouseup", this.handleMouseUp, this);
13609         this.el.on("mouseout", this.handleMouseOut, this);
13610
13611         this.fireEvent("mousedown", this);
13612         this.fireEvent("click", this);
13613         
13614         this.timer = this.click.defer(this.delay || this.interval, this);
13615     },
13616
13617     // private
13618     click : function(){
13619         this.fireEvent("click", this);
13620         this.timer = this.click.defer(this.getInterval(), this);
13621     },
13622
13623     // private
13624     getInterval: function(){
13625         if(!this.accelerate){
13626             return this.interval;
13627         }
13628         var pressTime = this.mousedownTime.getElapsed();
13629         if(pressTime < 500){
13630             return 400;
13631         }else if(pressTime < 1700){
13632             return 320;
13633         }else if(pressTime < 2600){
13634             return 250;
13635         }else if(pressTime < 3500){
13636             return 180;
13637         }else if(pressTime < 4400){
13638             return 140;
13639         }else if(pressTime < 5300){
13640             return 80;
13641         }else if(pressTime < 6200){
13642             return 50;
13643         }else{
13644             return 10;
13645         }
13646     },
13647
13648     // private
13649     handleMouseOut : function(){
13650         clearTimeout(this.timer);
13651         if(this.pressClass){
13652             this.el.removeClass(this.pressClass);
13653         }
13654         this.el.on("mouseover", this.handleMouseReturn, this);
13655     },
13656
13657     // private
13658     handleMouseReturn : function(){
13659         this.el.un("mouseover", this.handleMouseReturn);
13660         if(this.pressClass){
13661             this.el.addClass(this.pressClass);
13662         }
13663         this.click();
13664     },
13665
13666     // private
13667     handleMouseUp : function(){
13668         clearTimeout(this.timer);
13669         this.el.un("mouseover", this.handleMouseReturn);
13670         this.el.un("mouseout", this.handleMouseOut);
13671         Roo.get(document).un("mouseup", this.handleMouseUp);
13672         this.el.removeClass(this.pressClass);
13673         this.fireEvent("mouseup", this);
13674     }
13675 });/*
13676  * Based on:
13677  * Ext JS Library 1.1.1
13678  * Copyright(c) 2006-2007, Ext JS, LLC.
13679  *
13680  * Originally Released Under LGPL - original licence link has changed is not relivant.
13681  *
13682  * Fork - LGPL
13683  * <script type="text/javascript">
13684  */
13685
13686  
13687 /**
13688  * @class Roo.KeyNav
13689  * <p>Provides a convenient wrapper for normalized keyboard navigation.  KeyNav allows you to bind
13690  * navigation keys to function calls that will get called when the keys are pressed, providing an easy
13691  * way to implement custom navigation schemes for any UI component.</p>
13692  * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
13693  * pageUp, pageDown, del, home, end.  Usage:</p>
13694  <pre><code>
13695 var nav = new Roo.KeyNav("my-element", {
13696     "left" : function(e){
13697         this.moveLeft(e.ctrlKey);
13698     },
13699     "right" : function(e){
13700         this.moveRight(e.ctrlKey);
13701     },
13702     "enter" : function(e){
13703         this.save();
13704     },
13705     scope : this
13706 });
13707 </code></pre>
13708  * @constructor
13709  * @param {String/HTMLElement/Roo.Element} el The element to bind to
13710  * @param {Object} config The config
13711  */
13712 Roo.KeyNav = function(el, config){
13713     this.el = Roo.get(el);
13714     Roo.apply(this, config);
13715     if(!this.disabled){
13716         this.disabled = true;
13717         this.enable();
13718     }
13719 };
13720
13721 Roo.KeyNav.prototype = {
13722     /**
13723      * @cfg {Boolean} disabled
13724      * True to disable this KeyNav instance (defaults to false)
13725      */
13726     disabled : false,
13727     /**
13728      * @cfg {String} defaultEventAction
13729      * The method to call on the {@link Roo.EventObject} after this KeyNav intercepts a key.  Valid values are
13730      * {@link Roo.EventObject#stopEvent}, {@link Roo.EventObject#preventDefault} and
13731      * {@link Roo.EventObject#stopPropagation} (defaults to 'stopEvent')
13732      */
13733     defaultEventAction: "stopEvent",
13734     /**
13735      * @cfg {Boolean} forceKeyDown
13736      * Handle the keydown event instead of keypress (defaults to false).  KeyNav automatically does this for IE since
13737      * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
13738      * handle keydown instead of keypress.
13739      */
13740     forceKeyDown : false,
13741
13742     // private
13743     prepareEvent : function(e){
13744         var k = e.getKey();
13745         var h = this.keyToHandler[k];
13746         //if(h && this[h]){
13747         //    e.stopPropagation();
13748         //}
13749         if(Roo.isSafari && h && k >= 37 && k <= 40){
13750             e.stopEvent();
13751         }
13752     },
13753
13754     // private
13755     relay : function(e){
13756         var k = e.getKey();
13757         var h = this.keyToHandler[k];
13758         if(h && this[h]){
13759             if(this.doRelay(e, this[h], h) !== true){
13760                 e[this.defaultEventAction]();
13761             }
13762         }
13763     },
13764
13765     // private
13766     doRelay : function(e, h, hname){
13767         return h.call(this.scope || this, e);
13768     },
13769
13770     // possible handlers
13771     enter : false,
13772     left : false,
13773     right : false,
13774     up : false,
13775     down : false,
13776     tab : false,
13777     esc : false,
13778     pageUp : false,
13779     pageDown : false,
13780     del : false,
13781     home : false,
13782     end : false,
13783
13784     // quick lookup hash
13785     keyToHandler : {
13786         37 : "left",
13787         39 : "right",
13788         38 : "up",
13789         40 : "down",
13790         33 : "pageUp",
13791         34 : "pageDown",
13792         46 : "del",
13793         36 : "home",
13794         35 : "end",
13795         13 : "enter",
13796         27 : "esc",
13797         9  : "tab"
13798     },
13799
13800         /**
13801          * Enable this KeyNav
13802          */
13803         enable: function(){
13804                 if(this.disabled){
13805             // ie won't do special keys on keypress, no one else will repeat keys with keydown
13806             // the EventObject will normalize Safari automatically
13807             if(this.forceKeyDown || Roo.isIE || Roo.isAir){
13808                 this.el.on("keydown", this.relay,  this);
13809             }else{
13810                 this.el.on("keydown", this.prepareEvent,  this);
13811                 this.el.on("keypress", this.relay,  this);
13812             }
13813                     this.disabled = false;
13814                 }
13815         },
13816
13817         /**
13818          * Disable this KeyNav
13819          */
13820         disable: function(){
13821                 if(!this.disabled){
13822                     if(this.forceKeyDown || Roo.isIE || Roo.isAir){
13823                 this.el.un("keydown", this.relay);
13824             }else{
13825                 this.el.un("keydown", this.prepareEvent);
13826                 this.el.un("keypress", this.relay);
13827             }
13828                     this.disabled = true;
13829                 }
13830         }
13831 };/*
13832  * Based on:
13833  * Ext JS Library 1.1.1
13834  * Copyright(c) 2006-2007, Ext JS, LLC.
13835  *
13836  * Originally Released Under LGPL - original licence link has changed is not relivant.
13837  *
13838  * Fork - LGPL
13839  * <script type="text/javascript">
13840  */
13841
13842  
13843 /**
13844  * @class Roo.KeyMap
13845  * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
13846  * The constructor accepts the same config object as defined by {@link #addBinding}.
13847  * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
13848  * combination it will call the function with this signature (if the match is a multi-key
13849  * combination the callback will still be called only once): (String key, Roo.EventObject e)
13850  * A KeyMap can also handle a string representation of keys.<br />
13851  * Usage:
13852  <pre><code>
13853 // map one key by key code
13854 var map = new Roo.KeyMap("my-element", {
13855     key: 13, // or Roo.EventObject.ENTER
13856     fn: myHandler,
13857     scope: myObject
13858 });
13859
13860 // map multiple keys to one action by string
13861 var map = new Roo.KeyMap("my-element", {
13862     key: "a\r\n\t",
13863     fn: myHandler,
13864     scope: myObject
13865 });
13866
13867 // map multiple keys to multiple actions by strings and array of codes
13868 var map = new Roo.KeyMap("my-element", [
13869     {
13870         key: [10,13],
13871         fn: function(){ alert("Return was pressed"); }
13872     }, {
13873         key: "abc",
13874         fn: function(){ alert('a, b or c was pressed'); }
13875     }, {
13876         key: "\t",
13877         ctrl:true,
13878         shift:true,
13879         fn: function(){ alert('Control + shift + tab was pressed.'); }
13880     }
13881 ]);
13882 </code></pre>
13883  * <b>Note: A KeyMap starts enabled</b>
13884  * @constructor
13885  * @param {String/HTMLElement/Roo.Element} el The element to bind to
13886  * @param {Object} config The config (see {@link #addBinding})
13887  * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
13888  */
13889 Roo.KeyMap = function(el, config, eventName){
13890     this.el  = Roo.get(el);
13891     this.eventName = eventName || "keydown";
13892     this.bindings = [];
13893     if(config){
13894         this.addBinding(config);
13895     }
13896     this.enable();
13897 };
13898
13899 Roo.KeyMap.prototype = {
13900     /**
13901      * True to stop the event from bubbling and prevent the default browser action if the
13902      * key was handled by the KeyMap (defaults to false)
13903      * @type Boolean
13904      */
13905     stopEvent : false,
13906
13907     /**
13908      * Add a new binding to this KeyMap. The following config object properties are supported:
13909      * <pre>
13910 Property    Type             Description
13911 ----------  ---------------  ----------------------------------------------------------------------
13912 key         String/Array     A single keycode or an array of keycodes to handle
13913 shift       Boolean          True to handle key only when shift is pressed (defaults to false)
13914 ctrl        Boolean          True to handle key only when ctrl is pressed (defaults to false)
13915 alt         Boolean          True to handle key only when alt is pressed (defaults to false)
13916 fn          Function         The function to call when KeyMap finds the expected key combination
13917 scope       Object           The scope of the callback function
13918 </pre>
13919      *
13920      * Usage:
13921      * <pre><code>
13922 // Create a KeyMap
13923 var map = new Roo.KeyMap(document, {
13924     key: Roo.EventObject.ENTER,
13925     fn: handleKey,
13926     scope: this
13927 });
13928
13929 //Add a new binding to the existing KeyMap later
13930 map.addBinding({
13931     key: 'abc',
13932     shift: true,
13933     fn: handleKey,
13934     scope: this
13935 });
13936 </code></pre>
13937      * @param {Object/Array} config A single KeyMap config or an array of configs
13938      */
13939         addBinding : function(config){
13940         if(config instanceof Array){
13941             for(var i = 0, len = config.length; i < len; i++){
13942                 this.addBinding(config[i]);
13943             }
13944             return;
13945         }
13946         var keyCode = config.key,
13947             shift = config.shift, 
13948             ctrl = config.ctrl, 
13949             alt = config.alt,
13950             fn = config.fn,
13951             scope = config.scope;
13952         if(typeof keyCode == "string"){
13953             var ks = [];
13954             var keyString = keyCode.toUpperCase();
13955             for(var j = 0, len = keyString.length; j < len; j++){
13956                 ks.push(keyString.charCodeAt(j));
13957             }
13958             keyCode = ks;
13959         }
13960         var keyArray = keyCode instanceof Array;
13961         var handler = function(e){
13962             if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) &&  (!alt || e.altKey)){
13963                 var k = e.getKey();
13964                 if(keyArray){
13965                     for(var i = 0, len = keyCode.length; i < len; i++){
13966                         if(keyCode[i] == k){
13967                           if(this.stopEvent){
13968                               e.stopEvent();
13969                           }
13970                           fn.call(scope || window, k, e);
13971                           return;
13972                         }
13973                     }
13974                 }else{
13975                     if(k == keyCode){
13976                         if(this.stopEvent){
13977                            e.stopEvent();
13978                         }
13979                         fn.call(scope || window, k, e);
13980                     }
13981                 }
13982             }
13983         };
13984         this.bindings.push(handler);  
13985         },
13986
13987     /**
13988      * Shorthand for adding a single key listener
13989      * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
13990      * following options:
13991      * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
13992      * @param {Function} fn The function to call
13993      * @param {Object} scope (optional) The scope of the function
13994      */
13995     on : function(key, fn, scope){
13996         var keyCode, shift, ctrl, alt;
13997         if(typeof key == "object" && !(key instanceof Array)){
13998             keyCode = key.key;
13999             shift = key.shift;
14000             ctrl = key.ctrl;
14001             alt = key.alt;
14002         }else{
14003             keyCode = key;
14004         }
14005         this.addBinding({
14006             key: keyCode,
14007             shift: shift,
14008             ctrl: ctrl,
14009             alt: alt,
14010             fn: fn,
14011             scope: scope
14012         })
14013     },
14014
14015     // private
14016     handleKeyDown : function(e){
14017             if(this.enabled){ //just in case
14018             var b = this.bindings;
14019             for(var i = 0, len = b.length; i < len; i++){
14020                 b[i].call(this, e);
14021             }
14022             }
14023         },
14024         
14025         /**
14026          * Returns true if this KeyMap is enabled
14027          * @return {Boolean} 
14028          */
14029         isEnabled : function(){
14030             return this.enabled;  
14031         },
14032         
14033         /**
14034          * Enables this KeyMap
14035          */
14036         enable: function(){
14037                 if(!this.enabled){
14038                     this.el.on(this.eventName, this.handleKeyDown, this);
14039                     this.enabled = true;
14040                 }
14041         },
14042
14043         /**
14044          * Disable this KeyMap
14045          */
14046         disable: function(){
14047                 if(this.enabled){
14048                     this.el.removeListener(this.eventName, this.handleKeyDown, this);
14049                     this.enabled = false;
14050                 }
14051         }
14052 };/*
14053  * Based on:
14054  * Ext JS Library 1.1.1
14055  * Copyright(c) 2006-2007, Ext JS, LLC.
14056  *
14057  * Originally Released Under LGPL - original licence link has changed is not relivant.
14058  *
14059  * Fork - LGPL
14060  * <script type="text/javascript">
14061  */
14062
14063  
14064 /**
14065  * @class Roo.util.TextMetrics
14066  * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
14067  * wide, in pixels, a given block of text will be.
14068  * @singleton
14069  */
14070 Roo.util.TextMetrics = function(){
14071     var shared;
14072     return {
14073         /**
14074          * Measures the size of the specified text
14075          * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
14076          * that can affect the size of the rendered text
14077          * @param {String} text The text to measure
14078          * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
14079          * in order to accurately measure the text height
14080          * @return {Object} An object containing the text's size {width: (width), height: (height)}
14081          */
14082         measure : function(el, text, fixedWidth){
14083             if(!shared){
14084                 shared = Roo.util.TextMetrics.Instance(el, fixedWidth);
14085             }
14086             shared.bind(el);
14087             shared.setFixedWidth(fixedWidth || 'auto');
14088             return shared.getSize(text);
14089         },
14090
14091         /**
14092          * Return a unique TextMetrics instance that can be bound directly to an element and reused.  This reduces
14093          * the overhead of multiple calls to initialize the style properties on each measurement.
14094          * @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
14095          * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
14096          * in order to accurately measure the text height
14097          * @return {Roo.util.TextMetrics.Instance} instance The new instance
14098          */
14099         createInstance : function(el, fixedWidth){
14100             return Roo.util.TextMetrics.Instance(el, fixedWidth);
14101         }
14102     };
14103 }();
14104
14105  
14106
14107 Roo.util.TextMetrics.Instance = function(bindTo, fixedWidth){
14108     var ml = new Roo.Element(document.createElement('div'));
14109     document.body.appendChild(ml.dom);
14110     ml.position('absolute');
14111     ml.setLeftTop(-1000, -1000);
14112     ml.hide();
14113
14114     if(fixedWidth){
14115         ml.setWidth(fixedWidth);
14116     }
14117      
14118     var instance = {
14119         /**
14120          * Returns the size of the specified text based on the internal element's style and width properties
14121          * @memberOf Roo.util.TextMetrics.Instance#
14122          * @param {String} text The text to measure
14123          * @return {Object} An object containing the text's size {width: (width), height: (height)}
14124          */
14125         getSize : function(text){
14126             ml.update(text);
14127             var s = ml.getSize();
14128             ml.update('');
14129             return s;
14130         },
14131
14132         /**
14133          * Binds this TextMetrics instance to an element from which to copy existing CSS styles
14134          * that can affect the size of the rendered text
14135          * @memberOf Roo.util.TextMetrics.Instance#
14136          * @param {String/HTMLElement} el The element, dom node or id
14137          */
14138         bind : function(el){
14139             ml.setStyle(
14140                 Roo.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
14141             );
14142         },
14143
14144         /**
14145          * Sets a fixed width on the internal measurement element.  If the text will be multiline, you have
14146          * to set a fixed width in order to accurately measure the text height.
14147          * @memberOf Roo.util.TextMetrics.Instance#
14148          * @param {Number} width The width to set on the element
14149          */
14150         setFixedWidth : function(width){
14151             ml.setWidth(width);
14152         },
14153
14154         /**
14155          * Returns the measured width of the specified text
14156          * @memberOf Roo.util.TextMetrics.Instance#
14157          * @param {String} text The text to measure
14158          * @return {Number} width The width in pixels
14159          */
14160         getWidth : function(text){
14161             ml.dom.style.width = 'auto';
14162             return this.getSize(text).width;
14163         },
14164
14165         /**
14166          * Returns the measured height of the specified text.  For multiline text, be sure to call
14167          * {@link #setFixedWidth} if necessary.
14168          * @memberOf Roo.util.TextMetrics.Instance#
14169          * @param {String} text The text to measure
14170          * @return {Number} height The height in pixels
14171          */
14172         getHeight : function(text){
14173             return this.getSize(text).height;
14174         }
14175     };
14176
14177     instance.bind(bindTo);
14178
14179     return instance;
14180 };
14181
14182 // backwards compat
14183 Roo.Element.measureText = Roo.util.TextMetrics.measure;/*
14184  * Based on:
14185  * Ext JS Library 1.1.1
14186  * Copyright(c) 2006-2007, Ext JS, LLC.
14187  *
14188  * Originally Released Under LGPL - original licence link has changed is not relivant.
14189  *
14190  * Fork - LGPL
14191  * <script type="text/javascript">
14192  */
14193
14194 /**
14195  * @class Roo.state.Provider
14196  * Abstract base class for state provider implementations. This class provides methods
14197  * for encoding and decoding <b>typed</b> variables including dates and defines the 
14198  * Provider interface.
14199  */
14200 Roo.state.Provider = function(){
14201     /**
14202      * @event statechange
14203      * Fires when a state change occurs.
14204      * @param {Provider} this This state provider
14205      * @param {String} key The state key which was changed
14206      * @param {String} value The encoded value for the state
14207      */
14208     this.addEvents({
14209         "statechange": true
14210     });
14211     this.state = {};
14212     Roo.state.Provider.superclass.constructor.call(this);
14213 };
14214 Roo.extend(Roo.state.Provider, Roo.util.Observable, {
14215     /**
14216      * Returns the current value for a key
14217      * @param {String} name The key name
14218      * @param {Mixed} defaultValue A default value to return if the key's value is not found
14219      * @return {Mixed} The state data
14220      */
14221     get : function(name, defaultValue){
14222         return typeof this.state[name] == "undefined" ?
14223             defaultValue : this.state[name];
14224     },
14225     
14226     /**
14227      * Clears a value from the state
14228      * @param {String} name The key name
14229      */
14230     clear : function(name){
14231         delete this.state[name];
14232         this.fireEvent("statechange", this, name, null);
14233     },
14234     
14235     /**
14236      * Sets the value for a key
14237      * @param {String} name The key name
14238      * @param {Mixed} value The value to set
14239      */
14240     set : function(name, value){
14241         this.state[name] = value;
14242         this.fireEvent("statechange", this, name, value);
14243     },
14244     
14245     /**
14246      * Decodes a string previously encoded with {@link #encodeValue}.
14247      * @param {String} value The value to decode
14248      * @return {Mixed} The decoded value
14249      */
14250     decodeValue : function(cookie){
14251         var re = /^(a|n|d|b|s|o)\:(.*)$/;
14252         var matches = re.exec(unescape(cookie));
14253         if(!matches || !matches[1]) return; // non state cookie
14254         var type = matches[1];
14255         var v = matches[2];
14256         switch(type){
14257             case "n":
14258                 return parseFloat(v);
14259             case "d":
14260                 return new Date(Date.parse(v));
14261             case "b":
14262                 return (v == "1");
14263             case "a":
14264                 var all = [];
14265                 var values = v.split("^");
14266                 for(var i = 0, len = values.length; i < len; i++){
14267                     all.push(this.decodeValue(values[i]));
14268                 }
14269                 return all;
14270            case "o":
14271                 var all = {};
14272                 var values = v.split("^");
14273                 for(var i = 0, len = values.length; i < len; i++){
14274                     var kv = values[i].split("=");
14275                     all[kv[0]] = this.decodeValue(kv[1]);
14276                 }
14277                 return all;
14278            default:
14279                 return v;
14280         }
14281     },
14282     
14283     /**
14284      * Encodes a value including type information.  Decode with {@link #decodeValue}.
14285      * @param {Mixed} value The value to encode
14286      * @return {String} The encoded value
14287      */
14288     encodeValue : function(v){
14289         var enc;
14290         if(typeof v == "number"){
14291             enc = "n:" + v;
14292         }else if(typeof v == "boolean"){
14293             enc = "b:" + (v ? "1" : "0");
14294         }else if(v instanceof Date){
14295             enc = "d:" + v.toGMTString();
14296         }else if(v instanceof Array){
14297             var flat = "";
14298             for(var i = 0, len = v.length; i < len; i++){
14299                 flat += this.encodeValue(v[i]);
14300                 if(i != len-1) flat += "^";
14301             }
14302             enc = "a:" + flat;
14303         }else if(typeof v == "object"){
14304             var flat = "";
14305             for(var key in v){
14306                 if(typeof v[key] != "function"){
14307                     flat += key + "=" + this.encodeValue(v[key]) + "^";
14308                 }
14309             }
14310             enc = "o:" + flat.substring(0, flat.length-1);
14311         }else{
14312             enc = "s:" + v;
14313         }
14314         return escape(enc);        
14315     }
14316 });
14317
14318 /*
14319  * Based on:
14320  * Ext JS Library 1.1.1
14321  * Copyright(c) 2006-2007, Ext JS, LLC.
14322  *
14323  * Originally Released Under LGPL - original licence link has changed is not relivant.
14324  *
14325  * Fork - LGPL
14326  * <script type="text/javascript">
14327  */
14328 /**
14329  * @class Roo.state.Manager
14330  * This is the global state manager. By default all components that are "state aware" check this class
14331  * for state information if you don't pass them a custom state provider. In order for this class
14332  * to be useful, it must be initialized with a provider when your application initializes.
14333  <pre><code>
14334 // in your initialization function
14335 init : function(){
14336    Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
14337    ...
14338    // supposed you have a {@link Roo.BorderLayout}
14339    var layout = new Roo.BorderLayout(...);
14340    layout.restoreState();
14341    // or a {Roo.BasicDialog}
14342    var dialog = new Roo.BasicDialog(...);
14343    dialog.restoreState();
14344  </code></pre>
14345  * @singleton
14346  */
14347 Roo.state.Manager = function(){
14348     var provider = new Roo.state.Provider();
14349     
14350     return {
14351         /**
14352          * Configures the default state provider for your application
14353          * @param {Provider} stateProvider The state provider to set
14354          */
14355         setProvider : function(stateProvider){
14356             provider = stateProvider;
14357         },
14358         
14359         /**
14360          * Returns the current value for a key
14361          * @param {String} name The key name
14362          * @param {Mixed} defaultValue The default value to return if the key lookup does not match
14363          * @return {Mixed} The state data
14364          */
14365         get : function(key, defaultValue){
14366             return provider.get(key, defaultValue);
14367         },
14368         
14369         /**
14370          * Sets the value for a key
14371          * @param {String} name The key name
14372          * @param {Mixed} value The state data
14373          */
14374          set : function(key, value){
14375             provider.set(key, value);
14376         },
14377         
14378         /**
14379          * Clears a value from the state
14380          * @param {String} name The key name
14381          */
14382         clear : function(key){
14383             provider.clear(key);
14384         },
14385         
14386         /**
14387          * Gets the currently configured state provider
14388          * @return {Provider} The state provider
14389          */
14390         getProvider : function(){
14391             return provider;
14392         }
14393     };
14394 }();
14395 /*
14396  * Based on:
14397  * Ext JS Library 1.1.1
14398  * Copyright(c) 2006-2007, Ext JS, LLC.
14399  *
14400  * Originally Released Under LGPL - original licence link has changed is not relivant.
14401  *
14402  * Fork - LGPL
14403  * <script type="text/javascript">
14404  */
14405 /**
14406  * @class Roo.state.CookieProvider
14407  * @extends Roo.state.Provider
14408  * The default Provider implementation which saves state via cookies.
14409  * <br />Usage:
14410  <pre><code>
14411    var cp = new Roo.state.CookieProvider({
14412        path: "/cgi-bin/",
14413        expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30 days
14414        domain: "roojs.com"
14415    })
14416    Roo.state.Manager.setProvider(cp);
14417  </code></pre>
14418  * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
14419  * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
14420  * @cfg {String} domain The domain to save the cookie for.  Note that you cannot specify a different domain than
14421  * your page is on, but you can specify a sub-domain, or simply the domain itself like 'roojs.com' to include
14422  * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
14423  * domain the page is running on including the 'www' like 'www.roojs.com')
14424  * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
14425  * @constructor
14426  * Create a new CookieProvider
14427  * @param {Object} config The configuration object
14428  */
14429 Roo.state.CookieProvider = function(config){
14430     Roo.state.CookieProvider.superclass.constructor.call(this);
14431     this.path = "/";
14432     this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
14433     this.domain = null;
14434     this.secure = false;
14435     Roo.apply(this, config);
14436     this.state = this.readCookies();
14437 };
14438
14439 Roo.extend(Roo.state.CookieProvider, Roo.state.Provider, {
14440     // private
14441     set : function(name, value){
14442         if(typeof value == "undefined" || value === null){
14443             this.clear(name);
14444             return;
14445         }
14446         this.setCookie(name, value);
14447         Roo.state.CookieProvider.superclass.set.call(this, name, value);
14448     },
14449
14450     // private
14451     clear : function(name){
14452         this.clearCookie(name);
14453         Roo.state.CookieProvider.superclass.clear.call(this, name);
14454     },
14455
14456     // private
14457     readCookies : function(){
14458         var cookies = {};
14459         var c = document.cookie + ";";
14460         var re = /\s?(.*?)=(.*?);/g;
14461         var matches;
14462         while((matches = re.exec(c)) != null){
14463             var name = matches[1];
14464             var value = matches[2];
14465             if(name && name.substring(0,3) == "ys-"){
14466                 cookies[name.substr(3)] = this.decodeValue(value);
14467             }
14468         }
14469         return cookies;
14470     },
14471
14472     // private
14473     setCookie : function(name, value){
14474         document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
14475            ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
14476            ((this.path == null) ? "" : ("; path=" + this.path)) +
14477            ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
14478            ((this.secure == true) ? "; secure" : "");
14479     },
14480
14481     // private
14482     clearCookie : function(name){
14483         document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
14484            ((this.path == null) ? "" : ("; path=" + this.path)) +
14485            ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
14486            ((this.secure == true) ? "; secure" : "");
14487     }
14488 });