roojs-ui.js
[roojs1] / roojs-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  * @static
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         isFirefox = ua.indexOf("firefox") > -1,
57         isIE = ua.indexOf("msie") > -1,
58         isIE7 = ua.indexOf("msie 7") > -1,
59         isIE11 = /trident.*rv\:11\./.test(ua),
60         isEdge = ua.indexOf("edge") > -1,
61         isGecko = !isSafari && ua.indexOf("gecko") > -1,
62         isBorderBox = isIE && !isStrict,
63         isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1),
64         isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1),
65         isLinux = (ua.indexOf("linux") != -1),
66         isSecure = window.location.href.toLowerCase().indexOf("https") === 0,
67         isIOS = /iphone|ipad/.test(ua),
68         isAndroid = /android/.test(ua),
69         isTouch =  (function() {
70             try {
71                 if (ua.indexOf('chrome') != -1 && ua.indexOf('android') == -1) {
72                     window.addEventListener('touchstart', function __set_has_touch__ () {
73                         Roo.isTouch = true;
74                         window.removeEventListener('touchstart', __set_has_touch__);
75                     });
76                     return false; // no touch on chrome!?
77                 }
78                 document.createEvent("TouchEvent");  
79                 return true;  
80             } catch (e) {  
81                 return false;  
82             } 
83             
84         })();
85     // remove css image flicker
86         if(isIE && !isIE7){
87         try{
88             document.execCommand("BackgroundImageCache", false, true);
89         }catch(e){}
90     }
91     
92     Roo.apply(Roo, {
93         /**
94          * True if the browser is in strict mode
95          * @type Boolean
96          */
97         isStrict : isStrict,
98         /**
99          * True if the page is running over SSL
100          * @type Boolean
101          */
102         isSecure : isSecure,
103         /**
104          * True when the document is fully initialized and ready for action
105          * @type Boolean
106          */
107         isReady : false,
108         /**
109          * Turn on debugging output (currently only the factory uses this)
110          * @type Boolean
111          */
112         
113         debug: false,
114
115         /**
116          * True to automatically uncache orphaned Roo.Elements periodically (defaults to true)
117          * @type Boolean
118          */
119         enableGarbageCollector : true,
120
121         /**
122          * True to automatically purge event listeners after uncaching an element (defaults to false).
123          * Note: this only happens if enableGarbageCollector is true.
124          * @type Boolean
125          */
126         enableListenerCollection:false,
127
128         /**
129          * URL to a blank file used by Roo when in secure mode for iframe src and onReady src to prevent
130          * the IE insecure content warning (defaults to javascript:false).
131          * @type String
132          */
133         SSL_SECURE_URL : "javascript:false",
134
135         /**
136          * URL to a 1x1 transparent gif image used by Roo to create inline icons with CSS background images. (Defaults to
137          * "http://Roojs.com/s.gif" and you should change this to a URL on your server).
138          * @type String
139          */
140         BLANK_IMAGE_URL : "http:/"+"/localhost/s.gif",
141
142         emptyFn : function(){},
143         
144         /**
145          * Copies all the properties of config to obj if they don't already exist.
146          * @param {Object} obj The receiver of the properties
147          * @param {Object} config The source of the properties
148          * @return {Object} returns obj
149          */
150         applyIf : function(o, c){
151             if(o && c){
152                 for(var p in c){
153                     if(typeof o[p] == "undefined"){ o[p] = c[p]; }
154                 }
155             }
156             return o;
157         },
158
159         /**
160          * Applies event listeners to elements by selectors when the document is ready.
161          * The event name is specified with an @ suffix.
162 <pre><code>
163 Roo.addBehaviors({
164    // add a listener for click on all anchors in element with id foo
165    '#foo a@click' : function(e, t){
166        // do something
167    },
168
169    // add the same listener to multiple selectors (separated by comma BEFORE the @)
170    '#foo a, #bar span.some-class@mouseover' : function(){
171        // do something
172    }
173 });
174 </code></pre>
175          * @param {Object} obj The list of behaviors to apply
176          */
177         addBehaviors : function(o){
178             if(!Roo.isReady){
179                 Roo.onReady(function(){
180                     Roo.addBehaviors(o);
181                 });
182                 return;
183             }
184             var cache = {}; // simple cache for applying multiple behaviors to same selector does query multiple times
185             for(var b in o){
186                 var parts = b.split('@');
187                 if(parts[1]){ // for Object prototype breakers
188                     var s = parts[0];
189                     if(!cache[s]){
190                         cache[s] = Roo.select(s);
191                     }
192                     cache[s].on(parts[1], o[b]);
193                 }
194             }
195             cache = null;
196         },
197
198         /**
199          * Generates unique ids. If the element already has an id, it is unchanged
200          * @param {String/HTMLElement/Element} el (optional) The element to generate an id for
201          * @param {String} prefix (optional) Id prefix (defaults "Roo-gen")
202          * @return {String} The generated Id.
203          */
204         id : function(el, prefix){
205             prefix = prefix || "roo-gen";
206             el = Roo.getDom(el);
207             var id = prefix + (++idSeed);
208             return el ? (el.id ? el.id : (el.id = id)) : id;
209         },
210          
211        
212         /**
213          * Extends one class with another class and optionally overrides members with the passed literal. This class
214          * also adds the function "override()" to the class that can be used to override
215          * members on an instance.
216          * @param {Object} subclass The class inheriting the functionality
217          * @param {Object} superclass The class being extended
218          * @param {Object} overrides (optional) A literal with members
219          * @method extend
220          */
221         extend : function(){
222             // inline overrides
223             var io = function(o){
224                 for(var m in o){
225                     this[m] = o[m];
226                 }
227             };
228             return function(sb, sp, overrides){
229                 if(typeof sp == 'object'){ // eg. prototype, rather than function constructor..
230                     overrides = sp;
231                     sp = sb;
232                     sb = function(){sp.apply(this, arguments);};
233                 }
234                 var F = function(){}, sbp, spp = sp.prototype;
235                 F.prototype = spp;
236                 sbp = sb.prototype = new F();
237                 sbp.constructor=sb;
238                 sb.superclass=spp;
239                 
240                 if(spp.constructor == Object.prototype.constructor){
241                     spp.constructor=sp;
242                    
243                 }
244                 
245                 sb.override = function(o){
246                     Roo.override(sb, o);
247                 };
248                 sbp.override = io;
249                 Roo.override(sb, overrides);
250                 return sb;
251             };
252         }(),
253
254         /**
255          * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name.
256          * Usage:<pre><code>
257 Roo.override(MyClass, {
258     newMethod1: function(){
259         // etc.
260     },
261     newMethod2: function(foo){
262         // etc.
263     }
264 });
265  </code></pre>
266          * @param {Object} origclass The class to override
267          * @param {Object} overrides The list of functions to add to origClass.  This should be specified as an object literal
268          * containing one or more methods.
269          * @method override
270          */
271         override : function(origclass, overrides){
272             if(overrides){
273                 var p = origclass.prototype;
274                 for(var method in overrides){
275                     p[method] = overrides[method];
276                 }
277             }
278         },
279         /**
280          * Creates namespaces to be used for scoping variables and classes so that they are not global.  Usage:
281          * <pre><code>
282 Roo.namespace('Company', 'Company.data');
283 Company.Widget = function() { ... }
284 Company.data.CustomStore = function(config) { ... }
285 </code></pre>
286          * @param {String} namespace1
287          * @param {String} namespace2
288          * @param {String} etc
289          * @method namespace
290          */
291         namespace : function(){
292             var a=arguments, o=null, i, j, d, rt;
293             for (i=0; i<a.length; ++i) {
294                 d=a[i].split(".");
295                 rt = d[0];
296                 /** eval:var:o */
297                 eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
298                 for (j=1; j<d.length; ++j) {
299                     o[d[j]]=o[d[j]] || {};
300                     o=o[d[j]];
301                 }
302             }
303         },
304         /**
305          * Creates namespaces to be used for scoping variables and classes so that they are not global.  Usage:
306          * <pre><code>
307 Roo.factory({ xns: Roo.data, xtype : 'Store', .....});
308 Roo.factory(conf, Roo.data);
309 </code></pre>
310          * @param {String} classname
311          * @param {String} namespace (optional)
312          * @method factory
313          */
314          
315         factory : function(c, ns)
316         {
317             // no xtype, no ns or c.xns - or forced off by c.xns
318             if (!c.xtype   || (!ns && !c.xns) ||  (c.xns === false)) { // not enough info...
319                 return c;
320             }
321             ns = c.xns ? c.xns : ns; // if c.xns is set, then use that..
322             if (c.constructor == ns[c.xtype]) {// already created...
323                 return c;
324             }
325             if (ns[c.xtype]) {
326                 if (Roo.debug) { Roo.log("Roo.Factory(" + c.xtype + ")"); }
327                 var ret = new ns[c.xtype](c);
328                 ret.xns = false;
329                 return ret;
330             }
331             c.xns = false; // prevent recursion..
332             return c;
333         },
334          /**
335          * Logs to console if it can.
336          *
337          * @param {String|Object} string
338          * @method log
339          */
340         log : function(s)
341         {
342             if ((typeof(console) == 'undefined') || (typeof(console.log) == 'undefined')) {
343                 return; // alerT?
344             }
345             
346             console.log(s);
347         },
348         /**
349          * 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.
350          * @param {Object} o
351          * @return {String}
352          */
353         urlEncode : function(o){
354             if(!o){
355                 return "";
356             }
357             var buf = [];
358             for(var key in o){
359                 var ov = o[key], k = Roo.encodeURIComponent(key);
360                 var type = typeof ov;
361                 if(type == 'undefined'){
362                     buf.push(k, "=&");
363                 }else if(type != "function" && type != "object"){
364                     buf.push(k, "=", Roo.encodeURIComponent(ov), "&");
365                 }else if(ov instanceof Array){
366                     if (ov.length) {
367                             for(var i = 0, len = ov.length; i < len; i++) {
368                                 buf.push(k, "=", Roo.encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
369                             }
370                         } else {
371                             buf.push(k, "=&");
372                         }
373                 }
374             }
375             buf.pop();
376             return buf.join("");
377         },
378          /**
379          * Safe version of encodeURIComponent
380          * @param {String} data 
381          * @return {String} 
382          */
383         
384         encodeURIComponent : function (data)
385         {
386             try {
387                 return encodeURIComponent(data);
388             } catch(e) {} // should be an uri encode error.
389             
390             if (data == '' || data == null){
391                return '';
392             }
393             // http://stackoverflow.com/questions/2596483/unicode-and-uri-encoding-decoding-and-escaping-in-javascript
394             function nibble_to_hex(nibble){
395                 var chars = '0123456789ABCDEF';
396                 return chars.charAt(nibble);
397             }
398             data = data.toString();
399             var buffer = '';
400             for(var i=0; i<data.length; i++){
401                 var c = data.charCodeAt(i);
402                 var bs = new Array();
403                 if (c > 0x10000){
404                         // 4 bytes
405                     bs[0] = 0xF0 | ((c & 0x1C0000) >>> 18);
406                     bs[1] = 0x80 | ((c & 0x3F000) >>> 12);
407                     bs[2] = 0x80 | ((c & 0xFC0) >>> 6);
408                     bs[3] = 0x80 | (c & 0x3F);
409                 }else if (c > 0x800){
410                          // 3 bytes
411                     bs[0] = 0xE0 | ((c & 0xF000) >>> 12);
412                     bs[1] = 0x80 | ((c & 0xFC0) >>> 6);
413                     bs[2] = 0x80 | (c & 0x3F);
414                 }else if (c > 0x80){
415                        // 2 bytes
416                     bs[0] = 0xC0 | ((c & 0x7C0) >>> 6);
417                     bs[1] = 0x80 | (c & 0x3F);
418                 }else{
419                         // 1 byte
420                     bs[0] = c;
421                 }
422                 for(var j=0; j<bs.length; j++){
423                     var b = bs[j];
424                     var hex = nibble_to_hex((b & 0xF0) >>> 4) 
425                             + nibble_to_hex(b &0x0F);
426                     buffer += '%'+hex;
427                }
428             }
429             return buffer;    
430              
431         },
432
433         /**
434          * 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]}.
435          * @param {String} string
436          * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
437          * @return {Object} A literal with members
438          */
439         urlDecode : function(string, overwrite){
440             if(!string || !string.length){
441                 return {};
442             }
443             var obj = {};
444             var pairs = string.split('&');
445             var pair, name, value;
446             for(var i = 0, len = pairs.length; i < len; i++){
447                 pair = pairs[i].split('=');
448                 name = decodeURIComponent(pair[0]);
449                 value = decodeURIComponent(pair[1]);
450                 if(overwrite !== true){
451                     if(typeof obj[name] == "undefined"){
452                         obj[name] = value;
453                     }else if(typeof obj[name] == "string"){
454                         obj[name] = [obj[name]];
455                         obj[name].push(value);
456                     }else{
457                         obj[name].push(value);
458                     }
459                 }else{
460                     obj[name] = value;
461                 }
462             }
463             return obj;
464         },
465
466         /**
467          * Iterates an array calling the passed function with each item, stopping if your function returns false. If the
468          * passed array is not really an array, your function is called once with it.
469          * The supplied function is called with (Object item, Number index, Array allItems).
470          * @param {Array/NodeList/Mixed} array
471          * @param {Function} fn
472          * @param {Object} scope
473          */
474         each : function(array, fn, scope){
475             if(typeof array.length == "undefined" || typeof array == "string"){
476                 array = [array];
477             }
478             for(var i = 0, len = array.length; i < len; i++){
479                 if(fn.call(scope || array[i], array[i], i, array) === false){ return i; };
480             }
481         },
482
483         // deprecated
484         combine : function(){
485             var as = arguments, l = as.length, r = [];
486             for(var i = 0; i < l; i++){
487                 var a = as[i];
488                 if(a instanceof Array){
489                     r = r.concat(a);
490                 }else if(a.length !== undefined && !a.substr){
491                     r = r.concat(Array.prototype.slice.call(a, 0));
492                 }else{
493                     r.push(a);
494                 }
495             }
496             return r;
497         },
498
499         /**
500          * Escapes the passed string for use in a regular expression
501          * @param {String} str
502          * @return {String}
503          */
504         escapeRe : function(s) {
505             return s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1");
506         },
507
508         // internal
509         callback : function(cb, scope, args, delay){
510             if(typeof cb == "function"){
511                 if(delay){
512                     cb.defer(delay, scope, args || []);
513                 }else{
514                     cb.apply(scope, args || []);
515                 }
516             }
517         },
518
519         /**
520          * Return the dom node for the passed string (id), dom node, or Roo.Element
521          * @param {String/HTMLElement/Roo.Element} el
522          * @return HTMLElement
523          */
524         getDom : function(el){
525             if(!el){
526                 return null;
527             }
528             return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
529         },
530
531         /**
532         * Shorthand for {@link Roo.ComponentMgr#get}
533         * @param {String} id
534         * @return Roo.Component
535         */
536         getCmp : function(id){
537             return Roo.ComponentMgr.get(id);
538         },
539          
540         num : function(v, defaultValue){
541             if(typeof v != 'number'){
542                 return defaultValue;
543             }
544             return v;
545         },
546
547         destroy : function(){
548             for(var i = 0, a = arguments, len = a.length; i < len; i++) {
549                 var as = a[i];
550                 if(as){
551                     if(as.dom){
552                         as.removeAllListeners();
553                         as.remove();
554                         continue;
555                     }
556                     if(typeof as.purgeListeners == 'function'){
557                         as.purgeListeners();
558                     }
559                     if(typeof as.destroy == 'function'){
560                         as.destroy();
561                     }
562                 }
563             }
564         },
565
566         // inpired by a similar function in mootools library
567         /**
568          * Returns the type of object that is passed in. If the object passed in is null or undefined it
569          * return false otherwise it returns one of the following values:<ul>
570          * <li><b>string</b>: If the object passed is a string</li>
571          * <li><b>number</b>: If the object passed is a number</li>
572          * <li><b>boolean</b>: If the object passed is a boolean value</li>
573          * <li><b>function</b>: If the object passed is a function reference</li>
574          * <li><b>object</b>: If the object passed is an object</li>
575          * <li><b>array</b>: If the object passed is an array</li>
576          * <li><b>regexp</b>: If the object passed is a regular expression</li>
577          * <li><b>element</b>: If the object passed is a DOM Element</li>
578          * <li><b>nodelist</b>: If the object passed is a DOM NodeList</li>
579          * <li><b>textnode</b>: If the object passed is a DOM text node and contains something other than whitespace</li>
580          * <li><b>whitespace</b>: If the object passed is a DOM text node and contains only whitespace</li>
581          * @param {Mixed} object
582          * @return {String}
583          */
584         type : function(o){
585             if(o === undefined || o === null){
586                 return false;
587             }
588             if(o.htmlElement){
589                 return 'element';
590             }
591             var t = typeof o;
592             if(t == 'object' && o.nodeName) {
593                 switch(o.nodeType) {
594                     case 1: return 'element';
595                     case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace';
596                 }
597             }
598             if(t == 'object' || t == 'function') {
599                 switch(o.constructor) {
600                     case Array: return 'array';
601                     case RegExp: return 'regexp';
602                 }
603                 if(typeof o.length == 'number' && typeof o.item == 'function') {
604                     return 'nodelist';
605                 }
606             }
607             return t;
608         },
609
610         /**
611          * Returns true if the passed value is null, undefined or an empty string (optional).
612          * @param {Mixed} value The value to test
613          * @param {Boolean} allowBlank (optional) Pass true if an empty string is not considered empty
614          * @return {Boolean}
615          */
616         isEmpty : function(v, allowBlank){
617             return v === null || v === undefined || (!allowBlank ? v === '' : false);
618         },
619         
620         /** @type Boolean */
621         isOpera : isOpera,
622         /** @type Boolean */
623         isSafari : isSafari,
624         /** @type Boolean */
625         isFirefox : isFirefox,
626         /** @type Boolean */
627         isIE : isIE,
628         /** @type Boolean */
629         isIE7 : isIE7,
630         /** @type Boolean */
631         isIE11 : isIE11,
632         /** @type Boolean */
633         isEdge : isEdge,
634         /** @type Boolean */
635         isGecko : isGecko,
636         /** @type Boolean */
637         isBorderBox : isBorderBox,
638         /** @type Boolean */
639         isWindows : isWindows,
640         /** @type Boolean */
641         isLinux : isLinux,
642         /** @type Boolean */
643         isMac : isMac,
644         /** @type Boolean */
645         isIOS : isIOS,
646         /** @type Boolean */
647         isAndroid : isAndroid,
648         /** @type Boolean */
649         isTouch : isTouch,
650
651         /**
652          * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
653          * you may want to set this to true.
654          * @type Boolean
655          */
656         useShims : ((isIE && !isIE7) || (isGecko && isMac)),
657         
658         
659                 
660         /**
661          * Selects a single element as a Roo Element
662          * This is about as close as you can get to jQuery's $('do crazy stuff')
663          * @param {String} selector The selector/xpath query
664          * @param {Node} root (optional) The start of the query (defaults to document).
665          * @return {Roo.Element}
666          */
667         selectNode : function(selector, root) 
668         {
669             var node = Roo.DomQuery.selectNode(selector,root);
670             return node ? Roo.get(node) : new Roo.Element(false);
671         },
672                 /**
673                  * Find the current bootstrap width Grid size
674                  * Note xs is the default for smaller.. - this is currently used by grids to render correct columns
675                  * @returns {String} (xs|sm|md|lg|xl)
676                  */
677                 
678                 getGridSize : function()
679                 {
680                         var w = Roo.lib.Dom.getViewWidth();
681                         switch(true) {
682                                 case w > 1200:
683                                         return 'xl';
684                                 case w > 992:
685                                         return 'lg';
686                                 case w > 768:
687                                         return 'md';
688                                 case w > 576:
689                                         return 'sm';
690                                 default:
691                                         return 'xs'
692                         }
693                         
694                 }
695         
696     });
697
698
699 })();
700
701 Roo.namespace("Roo", "Roo.util", "Roo.grid", "Roo.dd", "Roo.tree", "Roo.data",
702                 "Roo.form", "Roo.menu", "Roo.state", "Roo.lib", "Roo.layout",
703                 "Roo.app", "Roo.ux" 
704                );
705 /*
706  * Based on:
707  * Ext JS Library 1.1.1
708  * Copyright(c) 2006-2007, Ext JS, LLC.
709  *
710  * Originally Released Under LGPL - original licence link has changed is not relivant.
711  *
712  * Fork - LGPL
713  * <script type="text/javascript">
714  */
715
716 (function() {    
717     // wrappedn so fnCleanup is not in global scope...
718     if(Roo.isIE) {
719         function fnCleanUp() {
720             var p = Function.prototype;
721             delete p.createSequence;
722             delete p.defer;
723             delete p.createDelegate;
724             delete p.createCallback;
725             delete p.createInterceptor;
726
727             window.detachEvent("onunload", fnCleanUp);
728         }
729         window.attachEvent("onunload", fnCleanUp);
730     }
731 })();
732
733
734 /**
735  * @class Function
736  * These functions are available on every Function object (any JavaScript function).
737  */
738 Roo.apply(Function.prototype, {
739      /**
740      * Creates a callback that passes arguments[0], arguments[1], arguments[2], ...
741      * Call directly on any function. Example: <code>myFunction.createCallback(myarg, myarg2)</code>
742      * Will create a function that is bound to those 2 args.
743      * @return {Function} The new function
744     */
745     createCallback : function(/*args...*/){
746         // make args available, in function below
747         var args = arguments;
748         var method = this;
749         return function() {
750             return method.apply(window, args);
751         };
752     },
753
754     /**
755      * Creates a delegate (callback) that sets the scope to obj.
756      * Call directly on any function. Example: <code>this.myFunction.createDelegate(this)</code>
757      * Will create a function that is automatically scoped to this.
758      * @param {Object} obj (optional) The object for which the scope is set
759      * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
760      * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
761      *                                             if a number the args are inserted at the specified position
762      * @return {Function} The new function
763      */
764     createDelegate : function(obj, args, appendArgs){
765         var method = this;
766         return function() {
767             var callArgs = args || arguments;
768             if(appendArgs === true){
769                 callArgs = Array.prototype.slice.call(arguments, 0);
770                 callArgs = callArgs.concat(args);
771             }else if(typeof appendArgs == "number"){
772                 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
773                 var applyArgs = [appendArgs, 0].concat(args); // create method call params
774                 Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
775             }
776             return method.apply(obj || window, callArgs);
777         };
778     },
779
780     /**
781      * Calls this function after the number of millseconds specified.
782      * @param {Number} millis The number of milliseconds for the setTimeout call (if 0 the function is executed immediately)
783      * @param {Object} obj (optional) The object for which the scope is set
784      * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
785      * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
786      *                                             if a number the args are inserted at the specified position
787      * @return {Number} The timeout id that can be used with clearTimeout
788      */
789     defer : function(millis, obj, args, appendArgs){
790         var fn = this.createDelegate(obj, args, appendArgs);
791         if(millis){
792             return setTimeout(fn, millis);
793         }
794         fn();
795         return 0;
796     },
797     /**
798      * Create a combined function call sequence of the original function + the passed function.
799      * The resulting function returns the results of the original function.
800      * The passed fcn is called with the parameters of the original function
801      * @param {Function} fcn The function to sequence
802      * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
803      * @return {Function} The new function
804      */
805     createSequence : function(fcn, scope){
806         if(typeof fcn != "function"){
807             return this;
808         }
809         var method = this;
810         return function() {
811             var retval = method.apply(this || window, arguments);
812             fcn.apply(scope || this || window, arguments);
813             return retval;
814         };
815     },
816
817     /**
818      * Creates an interceptor function. The passed fcn is called before the original one. If it returns false, the original one is not called.
819      * The resulting function returns the results of the original function.
820      * The passed fcn is called with the parameters of the original function.
821      * @addon
822      * @param {Function} fcn The function to call before the original
823      * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
824      * @return {Function} The new function
825      */
826     createInterceptor : function(fcn, scope){
827         if(typeof fcn != "function"){
828             return this;
829         }
830         var method = this;
831         return function() {
832             fcn.target = this;
833             fcn.method = method;
834             if(fcn.apply(scope || this || window, arguments) === false){
835                 return;
836             }
837             return method.apply(this || window, arguments);
838         };
839     }
840 });
841 /*
842  * Based on:
843  * Ext JS Library 1.1.1
844  * Copyright(c) 2006-2007, Ext JS, LLC.
845  *
846  * Originally Released Under LGPL - original licence link has changed is not relivant.
847  *
848  * Fork - LGPL
849  * <script type="text/javascript">
850  */
851
852 Roo.applyIf(String, {
853     
854     /** @scope String */
855     
856     /**
857      * Escapes the passed string for ' and \
858      * @param {String} string The string to escape
859      * @return {String} The escaped string
860      * @static
861      */
862     escape : function(string) {
863         return string.replace(/('|\\)/g, "\\$1");
864     },
865
866     /**
867      * Pads the left side of a string with a specified character.  This is especially useful
868      * for normalizing number and date strings.  Example usage:
869      * <pre><code>
870 var s = String.leftPad('123', 5, '0');
871 // s now contains the string: '00123'
872 </code></pre>
873      * @param {String} string The original string
874      * @param {Number} size The total length of the output string
875      * @param {String} char (optional) The character with which to pad the original string (defaults to empty string " ")
876      * @return {String} The padded string
877      * @static
878      */
879     leftPad : function (val, size, ch) {
880         var result = new String(val);
881         if(ch === null || ch === undefined || ch === '') {
882             ch = " ";
883         }
884         while (result.length < size) {
885             result = ch + result;
886         }
887         return result;
888     },
889
890     /**
891      * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens.  Each
892      * token must be unique, and must increment in the format {0}, {1}, etc.  Example usage:
893      * <pre><code>
894 var cls = 'my-class', text = 'Some text';
895 var s = String.format('<div class="{0}">{1}</div>', cls, text);
896 // s now contains the string: '<div class="my-class">Some text</div>'
897 </code></pre>
898      * @param {String} string The tokenized string to be formatted
899      * @param {String} value1 The value to replace token {0}
900      * @param {String} value2 Etc...
901      * @return {String} The formatted string
902      * @static
903      */
904     format : function(format){
905         var args = Array.prototype.slice.call(arguments, 1);
906         return format.replace(/\{(\d+)\}/g, function(m, i){
907             return Roo.util.Format.htmlEncode(args[i]);
908         });
909     }
910   
911     
912 });
913
914 /**
915  * Utility function that allows you to easily switch a string between two alternating values.  The passed value
916  * is compared to the current string, and if they are equal, the other value that was passed in is returned.  If
917  * they are already different, the first value passed in is returned.  Note that this method returns the new value
918  * but does not change the current string.
919  * <pre><code>
920 // alternate sort directions
921 sort = sort.toggle('ASC', 'DESC');
922
923 // instead of conditional logic:
924 sort = (sort == 'ASC' ? 'DESC' : 'ASC');
925 </code></pre>
926  * @param {String} value The value to compare to the current string
927  * @param {String} other The new value to use if the string already equals the first value passed in
928  * @return {String} The new value
929  */
930  
931 String.prototype.toggle = function(value, other){
932     return this == value ? other : value;
933 };
934
935
936 /**
937   * Remove invalid unicode characters from a string 
938   *
939   * @return {String} The clean string
940   */
941 String.prototype.unicodeClean = function () {
942     return this.replace(/[\s\S]/g,
943         function(character) {
944             if (character.charCodeAt()< 256) {
945               return character;
946            }
947            try {
948                 encodeURIComponent(character);
949            } catch(e) { 
950               return '';
951            }
952            return character;
953         }
954     );
955 };
956   
957
958 /**
959   * Make the first letter of a string uppercase
960   *
961   * @return {String} The new string.
962   */
963 String.prototype.toUpperCaseFirst = function () {
964     return this.charAt(0).toUpperCase() + this.slice(1);
965 };  
966   
967 /*
968  * Based on:
969  * Ext JS Library 1.1.1
970  * Copyright(c) 2006-2007, Ext JS, LLC.
971  *
972  * Originally Released Under LGPL - original licence link has changed is not relivant.
973  *
974  * Fork - LGPL
975  * <script type="text/javascript">
976  */
977
978  /**
979  * @class Number
980  */
981 Roo.applyIf(Number.prototype, {
982     /**
983      * Checks whether or not the current number is within a desired range.  If the number is already within the
984      * range it is returned, otherwise the min or max value is returned depending on which side of the range is
985      * exceeded.  Note that this method returns the constrained value but does not change the current number.
986      * @param {Number} min The minimum number in the range
987      * @param {Number} max The maximum number in the range
988      * @return {Number} The constrained value if outside the range, otherwise the current value
989      */
990     constrain : function(min, max){
991         return Math.min(Math.max(this, min), max);
992     }
993 });/*
994  * Based on:
995  * Ext JS Library 1.1.1
996  * Copyright(c) 2006-2007, Ext JS, LLC.
997  *
998  * Originally Released Under LGPL - original licence link has changed is not relivant.
999  *
1000  * Fork - LGPL
1001  * <script type="text/javascript">
1002  */
1003  /**
1004  * @class Array
1005  */
1006 Roo.applyIf(Array.prototype, {
1007     /**
1008      * 
1009      * Checks whether or not the specified object exists in the array.
1010      * @param {Object} o The object to check for
1011      * @return {Number} The index of o in the array (or -1 if it is not found)
1012      */
1013     indexOf : function(o){
1014        for (var i = 0, len = this.length; i < len; i++){
1015               if(this[i] == o) { return i; }
1016        }
1017            return -1;
1018     },
1019
1020     /**
1021      * Removes the specified object from the array.  If the object is not found nothing happens.
1022      * @param {Object} o The object to remove
1023      */
1024     remove : function(o){
1025        var index = this.indexOf(o);
1026        if(index != -1){
1027            this.splice(index, 1);
1028        }
1029     },
1030     /**
1031      * Map (JS 1.6 compatibility)
1032      * @param {Function} function  to call
1033      */
1034     map : function(fun )
1035     {
1036         var len = this.length >>> 0;
1037         if (typeof fun != "function") {
1038             throw new TypeError();
1039         }
1040         var res = new Array(len);
1041         var thisp = arguments[1];
1042         for (var i = 0; i < len; i++)
1043         {
1044             if (i in this) {
1045                 res[i] = fun.call(thisp, this[i], i, this);
1046             }
1047         }
1048
1049         return res;
1050     },
1051     /**
1052      * equals
1053      * @param {Array} o The array to compare to
1054      * @returns {Boolean} true if the same
1055      */
1056     equals : function(b)
1057     {
1058             // https://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript
1059         if (this === b) {
1060             return true;
1061         }
1062         if (b == null) {
1063             return false;
1064         }
1065         if (this.length !== b.length) {
1066             return false;
1067         }
1068           
1069         // sort?? a.sort().equals(b.sort());
1070           
1071         for (var i = 0; i < this.length; ++i) {
1072             if (this[i] !== b[i]) {
1073             return false;
1074             }
1075         }
1076         return true;
1077     } 
1078     
1079     
1080     
1081     
1082 });
1083
1084 Roo.applyIf(Array, {
1085  /**
1086      * from
1087      * @static
1088      * @param {Array} o Or Array like object (eg. nodelist)
1089      * @returns {Array} 
1090      */
1091     from : function(o)
1092     {
1093         var ret= [];
1094     
1095         for (var i =0; i < o.length; i++) { 
1096             ret[i] = o[i];
1097         }
1098         return ret;
1099       
1100     }
1101 });
1102 /*
1103  * Based on:
1104  * Ext JS Library 1.1.1
1105  * Copyright(c) 2006-2007, Ext JS, LLC.
1106  *
1107  * Originally Released Under LGPL - original licence link has changed is not relivant.
1108  *
1109  * Fork - LGPL
1110  * <script type="text/javascript">
1111  */
1112
1113 /**
1114  * @class Date
1115  *
1116  * The date parsing and format syntax is a subset of
1117  * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
1118  * supported will provide results equivalent to their PHP versions.
1119  *
1120  * Following is the list of all currently supported formats:
1121  *<pre>
1122 Sample date:
1123 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
1124
1125 Format  Output      Description
1126 ------  ----------  --------------------------------------------------------------
1127   d      10         Day of the month, 2 digits with leading zeros
1128   D      Wed        A textual representation of a day, three letters
1129   j      10         Day of the month without leading zeros
1130   l      Wednesday  A full textual representation of the day of the week
1131   S      th         English ordinal day of month suffix, 2 chars (use with j)
1132   w      3          Numeric representation of the day of the week
1133   z      9          The julian date, or day of the year (0-365)
1134   W      01         ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
1135   F      January    A full textual representation of the month
1136   m      01         Numeric representation of a month, with leading zeros
1137   M      Jan        Month name abbreviation, three letters
1138   n      1          Numeric representation of a month, without leading zeros
1139   t      31         Number of days in the given month
1140   L      0          Whether it's a leap year (1 if it is a leap year, else 0)
1141   Y      2007       A full numeric representation of a year, 4 digits
1142   y      07         A two digit representation of a year
1143   a      pm         Lowercase Ante meridiem and Post meridiem
1144   A      PM         Uppercase Ante meridiem and Post meridiem
1145   g      3          12-hour format of an hour without leading zeros
1146   G      15         24-hour format of an hour without leading zeros
1147   h      03         12-hour format of an hour with leading zeros
1148   H      15         24-hour format of an hour with leading zeros
1149   i      05         Minutes with leading zeros
1150   s      01         Seconds, with leading zeros
1151   O      -0600      Difference to Greenwich time (GMT) in hours (Allows +08, without minutes)
1152   P      -06:00     Difference to Greenwich time (GMT) with colon between hours and minutes
1153   T      CST        Timezone setting of the machine running the code
1154   Z      -21600     Timezone offset in seconds (negative if west of UTC, positive if east)
1155 </pre>
1156  *
1157  * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
1158  * <pre><code>
1159 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
1160 document.write(dt.format('Y-m-d'));                         //2007-01-10
1161 document.write(dt.format('F j, Y, g:i a'));                 //January 10, 2007, 3:05 pm
1162 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
1163  </code></pre>
1164  *
1165  * Here are some standard date/time patterns that you might find helpful.  They
1166  * are not part of the source of Date.js, but to use them you can simply copy this
1167  * block of code into any script that is included after Date.js and they will also become
1168  * globally available on the Date object.  Feel free to add or remove patterns as needed in your code.
1169  * <pre><code>
1170 Date.patterns = {
1171     ISO8601Long:"Y-m-d H:i:s",
1172     ISO8601Short:"Y-m-d",
1173     ShortDate: "n/j/Y",
1174     LongDate: "l, F d, Y",
1175     FullDateTime: "l, F d, Y g:i:s A",
1176     MonthDay: "F d",
1177     ShortTime: "g:i A",
1178     LongTime: "g:i:s A",
1179     SortableDateTime: "Y-m-d\\TH:i:s",
1180     UniversalSortableDateTime: "Y-m-d H:i:sO",
1181     YearMonth: "F, Y"
1182 };
1183 </code></pre>
1184  *
1185  * Example usage:
1186  * <pre><code>
1187 var dt = new Date();
1188 document.write(dt.format(Date.patterns.ShortDate));
1189  </code></pre>
1190  */
1191
1192 /*
1193  * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
1194  * They generate precompiled functions from date formats instead of parsing and
1195  * processing the pattern every time you format a date.  These functions are available
1196  * on every Date object (any javascript function).
1197  *
1198  * The original article and download are here:
1199  * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
1200  *
1201  */
1202  
1203  
1204  // was in core
1205 /**
1206  Returns the number of milliseconds between this date and date
1207  @param {Date} date (optional) Defaults to now
1208  @return {Number} The diff in milliseconds
1209  @member Date getElapsed
1210  */
1211 Date.prototype.getElapsed = function(date) {
1212         return Math.abs((date || new Date()).getTime()-this.getTime());
1213 };
1214 // was in date file..
1215
1216
1217 // private
1218 Date.parseFunctions = {count:0};
1219 // private
1220 Date.parseRegexes = [];
1221 // private
1222 Date.formatFunctions = {count:0};
1223
1224 // private
1225 Date.prototype.dateFormat = function(format) {
1226     if (Date.formatFunctions[format] == null) {
1227         Date.createNewFormat(format);
1228     }
1229     var func = Date.formatFunctions[format];
1230     return this[func]();
1231 };
1232
1233
1234 /**
1235  * Formats a date given the supplied format string
1236  * @param {String} format The format string
1237  * @return {String} The formatted date
1238  * @method
1239  */
1240 Date.prototype.format = Date.prototype.dateFormat;
1241
1242 // private
1243 Date.createNewFormat = function(format) {
1244     var funcName = "format" + Date.formatFunctions.count++;
1245     Date.formatFunctions[format] = funcName;
1246     var code = "Date.prototype." + funcName + " = function(){return ";
1247     var special = false;
1248     var ch = '';
1249     for (var i = 0; i < format.length; ++i) {
1250         ch = format.charAt(i);
1251         if (!special && ch == "\\") {
1252             special = true;
1253         }
1254         else if (special) {
1255             special = false;
1256             code += "'" + String.escape(ch) + "' + ";
1257         }
1258         else {
1259             code += Date.getFormatCode(ch);
1260         }
1261     }
1262     /** eval:var:zzzzzzzzzzzzz */
1263     eval(code.substring(0, code.length - 3) + ";}");
1264 };
1265
1266 // private
1267 Date.getFormatCode = function(character) {
1268     switch (character) {
1269     case "d":
1270         return "String.leftPad(this.getDate(), 2, '0') + ";
1271     case "D":
1272         return "Date.dayNames[this.getDay()].substring(0, 3) + ";
1273     case "j":
1274         return "this.getDate() + ";
1275     case "l":
1276         return "Date.dayNames[this.getDay()] + ";
1277     case "S":
1278         return "this.getSuffix() + ";
1279     case "w":
1280         return "this.getDay() + ";
1281     case "z":
1282         return "this.getDayOfYear() + ";
1283     case "W":
1284         return "this.getWeekOfYear() + ";
1285     case "F":
1286         return "Date.monthNames[this.getMonth()] + ";
1287     case "m":
1288         return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
1289     case "M":
1290         return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
1291     case "n":
1292         return "(this.getMonth() + 1) + ";
1293     case "t":
1294         return "this.getDaysInMonth() + ";
1295     case "L":
1296         return "(this.isLeapYear() ? 1 : 0) + ";
1297     case "Y":
1298         return "this.getFullYear() + ";
1299     case "y":
1300         return "('' + this.getFullYear()).substring(2, 4) + ";
1301     case "a":
1302         return "(this.getHours() < 12 ? 'am' : 'pm') + ";
1303     case "A":
1304         return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
1305     case "g":
1306         return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
1307     case "G":
1308         return "this.getHours() + ";
1309     case "h":
1310         return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
1311     case "H":
1312         return "String.leftPad(this.getHours(), 2, '0') + ";
1313     case "i":
1314         return "String.leftPad(this.getMinutes(), 2, '0') + ";
1315     case "s":
1316         return "String.leftPad(this.getSeconds(), 2, '0') + ";
1317     case "O":
1318         return "this.getGMTOffset() + ";
1319     case "P":
1320         return "this.getGMTColonOffset() + ";
1321     case "T":
1322         return "this.getTimezone() + ";
1323     case "Z":
1324         return "(this.getTimezoneOffset() * -60) + ";
1325     default:
1326         return "'" + String.escape(character) + "' + ";
1327     }
1328 };
1329
1330 /**
1331  * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
1332  * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates.  Any part of
1333  * the date format that is not specified will default to the current date value for that part.  Time parts can also
1334  * be specified, but default to 0.  Keep in mind that the input date string must precisely match the specified format
1335  * string or the parse operation will fail.
1336  * Example Usage:
1337 <pre><code>
1338 //dt = Fri May 25 2007 (current date)
1339 var dt = new Date();
1340
1341 //dt = Thu May 25 2006 (today's month/day in 2006)
1342 dt = Date.parseDate("2006", "Y");
1343
1344 //dt = Sun Jan 15 2006 (all date parts specified)
1345 dt = Date.parseDate("2006-1-15", "Y-m-d");
1346
1347 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
1348 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
1349 </code></pre>
1350  * @param {String} input The unparsed date as a string
1351  * @param {String} format The format the date is in
1352  * @return {Date} The parsed date
1353  * @static
1354  */
1355 Date.parseDate = function(input, format) {
1356     if (Date.parseFunctions[format] == null) {
1357         Date.createParser(format);
1358     }
1359     var func = Date.parseFunctions[format];
1360     return Date[func](input);
1361 };
1362 /**
1363  * @private
1364  */
1365
1366 Date.createParser = function(format) {
1367     var funcName = "parse" + Date.parseFunctions.count++;
1368     var regexNum = Date.parseRegexes.length;
1369     var currentGroup = 1;
1370     Date.parseFunctions[format] = funcName;
1371
1372     var code = "Date." + funcName + " = function(input){\n"
1373         + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
1374         + "var d = new Date();\n"
1375         + "y = d.getFullYear();\n"
1376         + "m = d.getMonth();\n"
1377         + "d = d.getDate();\n"
1378         + "if (typeof(input) !== 'string') { input = input.toString(); }\n"
1379         + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
1380         + "if (results && results.length > 0) {";
1381     var regex = "";
1382
1383     var special = false;
1384     var ch = '';
1385     for (var i = 0; i < format.length; ++i) {
1386         ch = format.charAt(i);
1387         if (!special && ch == "\\") {
1388             special = true;
1389         }
1390         else if (special) {
1391             special = false;
1392             regex += String.escape(ch);
1393         }
1394         else {
1395             var obj = Date.formatCodeToRegex(ch, currentGroup);
1396             currentGroup += obj.g;
1397             regex += obj.s;
1398             if (obj.g && obj.c) {
1399                 code += obj.c;
1400             }
1401         }
1402     }
1403
1404     code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
1405         + "{v = new Date(y, m, d, h, i, s); v.setFullYear(y);}\n"
1406         + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
1407         + "{v = new Date(y, m, d, h, i); v.setFullYear(y);}\n"
1408         + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
1409         + "{v = new Date(y, m, d, h); v.setFullYear(y);}\n"
1410         + "else if (y >= 0 && m >= 0 && d > 0)\n"
1411         + "{v = new Date(y, m, d); v.setFullYear(y);}\n"
1412         + "else if (y >= 0 && m >= 0)\n"
1413         + "{v = new Date(y, m); v.setFullYear(y);}\n"
1414         + "else if (y >= 0)\n"
1415         + "{v = new Date(y); v.setFullYear(y);}\n"
1416         + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
1417         + "    ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
1418         + "        v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
1419         + ";}";
1420
1421     Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
1422     /** eval:var:zzzzzzzzzzzzz */
1423     eval(code);
1424 };
1425
1426 // private
1427 Date.formatCodeToRegex = function(character, currentGroup) {
1428     switch (character) {
1429     case "D":
1430         return {g:0,
1431         c:null,
1432         s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
1433     case "j":
1434         return {g:1,
1435             c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1436             s:"(\\d{1,2})"}; // day of month without leading zeroes
1437     case "d":
1438         return {g:1,
1439             c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1440             s:"(\\d{2})"}; // day of month with leading zeroes
1441     case "l":
1442         return {g:0,
1443             c:null,
1444             s:"(?:" + Date.dayNames.join("|") + ")"};
1445     case "S":
1446         return {g:0,
1447             c:null,
1448             s:"(?:st|nd|rd|th)"};
1449     case "w":
1450         return {g:0,
1451             c:null,
1452             s:"\\d"};
1453     case "z":
1454         return {g:0,
1455             c:null,
1456             s:"(?:\\d{1,3})"};
1457     case "W":
1458         return {g:0,
1459             c:null,
1460             s:"(?:\\d{2})"};
1461     case "F":
1462         return {g:1,
1463             c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
1464             s:"(" + Date.monthNames.join("|") + ")"};
1465     case "M":
1466         return {g:1,
1467             c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
1468             s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
1469     case "n":
1470         return {g:1,
1471             c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1472             s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
1473     case "m":
1474         return {g:1,
1475             c:"m = Math.max(0,parseInt(results[" + currentGroup + "], 10) - 1);\n",
1476             s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
1477     case "t":
1478         return {g:0,
1479             c:null,
1480             s:"\\d{1,2}"};
1481     case "L":
1482         return {g:0,
1483             c:null,
1484             s:"(?:1|0)"};
1485     case "Y":
1486         return {g:1,
1487             c:"y = parseInt(results[" + currentGroup + "], 10);\n",
1488             s:"(\\d{4})"};
1489     case "y":
1490         return {g:1,
1491             c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
1492                 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
1493             s:"(\\d{1,2})"};
1494     case "a":
1495         return {g:1,
1496             c:"if (results[" + currentGroup + "] == 'am') {\n"
1497                 + "if (h == 12) { h = 0; }\n"
1498                 + "} else { if (h < 12) { h += 12; }}",
1499             s:"(am|pm)"};
1500     case "A":
1501         return {g:1,
1502             c:"if (results[" + currentGroup + "] == 'AM') {\n"
1503                 + "if (h == 12) { h = 0; }\n"
1504                 + "} else { if (h < 12) { h += 12; }}",
1505             s:"(AM|PM)"};
1506     case "g":
1507     case "G":
1508         return {g:1,
1509             c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1510             s:"(\\d{1,2})"}; // 12/24-hr format  format of an hour without leading zeroes
1511     case "h":
1512     case "H":
1513         return {g:1,
1514             c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1515             s:"(\\d{2})"}; //  12/24-hr format  format of an hour with leading zeroes
1516     case "i":
1517         return {g:1,
1518             c:"i = parseInt(results[" + currentGroup + "], 10);\n",
1519             s:"(\\d{2})"};
1520     case "s":
1521         return {g:1,
1522             c:"s = parseInt(results[" + currentGroup + "], 10);\n",
1523             s:"(\\d{2})"};
1524     case "O":
1525         return {g:1,
1526             c:[
1527                 "o = results[", currentGroup, "];\n",
1528                 "var sn = o.substring(0,1);\n", // get + / - sign
1529                 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
1530                 "var mn = o.substring(3,5) % 60;\n", // get minutes
1531                 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
1532                 "    (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1533             ].join(""),
1534             s:"([+\-]\\d{2,4})"};
1535     
1536     
1537     case "P":
1538         return {g:1,
1539                 c:[
1540                    "o = results[", currentGroup, "];\n",
1541                    "var sn = o.substring(0,1);\n",
1542                    "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n",
1543                    "var mn = o.substring(4,6) % 60;\n",
1544                    "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n",
1545                         "    (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1546             ].join(""),
1547             s:"([+\-]\\d{4})"};
1548     case "T":
1549         return {g:0,
1550             c:null,
1551             s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
1552     case "Z":
1553         return {g:1,
1554             c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
1555                   + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
1556             s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
1557     default:
1558         return {g:0,
1559             c:null,
1560             s:String.escape(character)};
1561     }
1562 };
1563
1564 /**
1565  * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
1566  * @return {String} The abbreviated timezone name (e.g. 'CST')
1567  */
1568 Date.prototype.getTimezone = function() {
1569     return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
1570 };
1571
1572 /**
1573  * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
1574  * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
1575  */
1576 Date.prototype.getGMTOffset = function() {
1577     return (this.getTimezoneOffset() > 0 ? "-" : "+")
1578         + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1579         + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
1580 };
1581
1582 /**
1583  * Get the offset from GMT of the current date (equivalent to the format specifier 'P').
1584  * @return {String} 2-characters representing hours and 2-characters representing minutes
1585  * seperated by a colon and prefixed with + or - (e.g. '-06:00')
1586  */
1587 Date.prototype.getGMTColonOffset = function() {
1588         return (this.getTimezoneOffset() > 0 ? "-" : "+")
1589                 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1590                 + ":"
1591                 + String.leftPad(this.getTimezoneOffset() %60, 2, "0");
1592 }
1593
1594 /**
1595  * Get the numeric day number of the year, adjusted for leap year.
1596  * @return {Number} 0 through 364 (365 in leap years)
1597  */
1598 Date.prototype.getDayOfYear = function() {
1599     var num = 0;
1600     Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1601     for (var i = 0; i < this.getMonth(); ++i) {
1602         num += Date.daysInMonth[i];
1603     }
1604     return num + this.getDate() - 1;
1605 };
1606
1607 /**
1608  * Get the string representation of the numeric week number of the year
1609  * (equivalent to the format specifier 'W').
1610  * @return {String} '00' through '52'
1611  */
1612 Date.prototype.getWeekOfYear = function() {
1613     // Skip to Thursday of this week
1614     var now = this.getDayOfYear() + (4 - this.getDay());
1615     // Find the first Thursday of the year
1616     var jan1 = new Date(this.getFullYear(), 0, 1);
1617     var then = (7 - jan1.getDay() + 4);
1618     return String.leftPad(((now - then) / 7) + 1, 2, "0");
1619 };
1620
1621 /**
1622  * Whether or not the current date is in a leap year.
1623  * @return {Boolean} True if the current date is in a leap year, else false
1624  */
1625 Date.prototype.isLeapYear = function() {
1626     var year = this.getFullYear();
1627     return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
1628 };
1629
1630 /**
1631  * Get the first day of the current month, adjusted for leap year.  The returned value
1632  * is the numeric day index within the week (0-6) which can be used in conjunction with
1633  * the {@link #monthNames} array to retrieve the textual day name.
1634  * Example:
1635  *<pre><code>
1636 var dt = new Date('1/10/2007');
1637 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
1638 </code></pre>
1639  * @return {Number} The day number (0-6)
1640  */
1641 Date.prototype.getFirstDayOfMonth = function() {
1642     var day = (this.getDay() - (this.getDate() - 1)) % 7;
1643     return (day < 0) ? (day + 7) : day;
1644 };
1645
1646 /**
1647  * Get the last day of the current month, adjusted for leap year.  The returned value
1648  * is the numeric day index within the week (0-6) which can be used in conjunction with
1649  * the {@link #monthNames} array to retrieve the textual day name.
1650  * Example:
1651  *<pre><code>
1652 var dt = new Date('1/10/2007');
1653 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
1654 </code></pre>
1655  * @return {Number} The day number (0-6)
1656  */
1657 Date.prototype.getLastDayOfMonth = function() {
1658     var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
1659     return (day < 0) ? (day + 7) : day;
1660 };
1661
1662
1663 /**
1664  * Get the first date of this date's month
1665  * @return {Date}
1666  */
1667 Date.prototype.getFirstDateOfMonth = function() {
1668     return new Date(this.getFullYear(), this.getMonth(), 1);
1669 };
1670
1671 /**
1672  * Get the last date of this date's month
1673  * @return {Date}
1674  */
1675 Date.prototype.getLastDateOfMonth = function() {
1676     return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
1677 };
1678 /**
1679  * Get the number of days in the current month, adjusted for leap year.
1680  * @return {Number} The number of days in the month
1681  */
1682 Date.prototype.getDaysInMonth = function() {
1683     Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1684     return Date.daysInMonth[this.getMonth()];
1685 };
1686
1687 /**
1688  * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
1689  * @return {String} 'st, 'nd', 'rd' or 'th'
1690  */
1691 Date.prototype.getSuffix = function() {
1692     switch (this.getDate()) {
1693         case 1:
1694         case 21:
1695         case 31:
1696             return "st";
1697         case 2:
1698         case 22:
1699             return "nd";
1700         case 3:
1701         case 23:
1702             return "rd";
1703         default:
1704             return "th";
1705     }
1706 };
1707
1708 // private
1709 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
1710
1711 /**
1712  * An array of textual month names.
1713  * Override these values for international dates, for example...
1714  * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
1715  * @type Array
1716  * @static
1717  */
1718 Date.monthNames =
1719    ["January",
1720     "February",
1721     "March",
1722     "April",
1723     "May",
1724     "June",
1725     "July",
1726     "August",
1727     "September",
1728     "October",
1729     "November",
1730     "December"];
1731
1732 /**
1733  * An array of textual day names.
1734  * Override these values for international dates, for example...
1735  * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
1736  * @type Array
1737  * @static
1738  */
1739 Date.dayNames =
1740    ["Sunday",
1741     "Monday",
1742     "Tuesday",
1743     "Wednesday",
1744     "Thursday",
1745     "Friday",
1746     "Saturday"];
1747
1748 // private
1749 Date.y2kYear = 50;
1750 // private
1751 Date.monthNumbers = {
1752     Jan:0,
1753     Feb:1,
1754     Mar:2,
1755     Apr:3,
1756     May:4,
1757     Jun:5,
1758     Jul:6,
1759     Aug:7,
1760     Sep:8,
1761     Oct:9,
1762     Nov:10,
1763     Dec:11};
1764
1765 /**
1766  * Creates and returns a new Date instance with the exact same date value as the called instance.
1767  * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
1768  * variable will also be changed.  When the intention is to create a new variable that will not
1769  * modify the original instance, you should create a clone.
1770  *
1771  * Example of correctly cloning a date:
1772  * <pre><code>
1773 //wrong way:
1774 var orig = new Date('10/1/2006');
1775 var copy = orig;
1776 copy.setDate(5);
1777 document.write(orig);  //returns 'Thu Oct 05 2006'!
1778
1779 //correct way:
1780 var orig = new Date('10/1/2006');
1781 var copy = orig.clone();
1782 copy.setDate(5);
1783 document.write(orig);  //returns 'Thu Oct 01 2006'
1784 </code></pre>
1785  * @return {Date} The new Date instance
1786  */
1787 Date.prototype.clone = function() {
1788         return new Date(this.getTime());
1789 };
1790
1791 /**
1792  * Clears any time information from this date
1793  @param {Boolean} clone true to create a clone of this date, clear the time and return it
1794  @return {Date} this or the clone
1795  */
1796 Date.prototype.clearTime = function(clone){
1797     if(clone){
1798         return this.clone().clearTime();
1799     }
1800     this.setHours(0);
1801     this.setMinutes(0);
1802     this.setSeconds(0);
1803     this.setMilliseconds(0);
1804     return this;
1805 };
1806
1807 // private
1808 // safari setMonth is broken -- check that this is only donw once...
1809 if(Roo.isSafari && typeof(Date.brokenSetMonth) == 'undefined'){
1810     Date.brokenSetMonth = Date.prototype.setMonth;
1811         Date.prototype.setMonth = function(num){
1812                 if(num <= -1){
1813                         var n = Math.ceil(-num);
1814                         var back_year = Math.ceil(n/12);
1815                         var month = (n % 12) ? 12 - n % 12 : 0 ;
1816                         this.setFullYear(this.getFullYear() - back_year);
1817                         return Date.brokenSetMonth.call(this, month);
1818                 } else {
1819                         return Date.brokenSetMonth.apply(this, arguments);
1820                 }
1821         };
1822 }
1823
1824 /** Date interval constant 
1825 * @static 
1826 * @type String */
1827 Date.MILLI = "ms";
1828 /** Date interval constant 
1829 * @static 
1830 * @type String */
1831 Date.SECOND = "s";
1832 /** Date interval constant 
1833 * @static 
1834 * @type String */
1835 Date.MINUTE = "mi";
1836 /** Date interval constant 
1837 * @static 
1838 * @type String */
1839 Date.HOUR = "h";
1840 /** Date interval constant 
1841 * @static 
1842 * @type String */
1843 Date.DAY = "d";
1844 /** Date interval constant 
1845 * @static 
1846 * @type String */
1847 Date.MONTH = "mo";
1848 /** Date interval constant 
1849 * @static 
1850 * @type String */
1851 Date.YEAR = "y";
1852
1853 /**
1854  * Provides a convenient method of performing basic date arithmetic.  This method
1855  * does not modify the Date instance being called - it creates and returns
1856  * a new Date instance containing the resulting date value.
1857  *
1858  * Examples:
1859  * <pre><code>
1860 //Basic usage:
1861 var dt = new Date('10/29/2006').add(Date.DAY, 5);
1862 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
1863
1864 //Negative values will subtract correctly:
1865 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
1866 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
1867
1868 //You can even chain several calls together in one line!
1869 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
1870 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
1871  </code></pre>
1872  *
1873  * @param {String} interval   A valid date interval enum value
1874  * @param {Number} value      The amount to add to the current date
1875  * @return {Date} The new Date instance
1876  */
1877 Date.prototype.add = function(interval, value){
1878   var d = this.clone();
1879   if (!interval || value === 0) { return d; }
1880   switch(interval.toLowerCase()){
1881     case Date.MILLI:
1882       d.setMilliseconds(this.getMilliseconds() + value);
1883       break;
1884     case Date.SECOND:
1885       d.setSeconds(this.getSeconds() + value);
1886       break;
1887     case Date.MINUTE:
1888       d.setMinutes(this.getMinutes() + value);
1889       break;
1890     case Date.HOUR:
1891       d.setHours(this.getHours() + value);
1892       break;
1893     case Date.DAY:
1894       d.setDate(this.getDate() + value);
1895       break;
1896     case Date.MONTH:
1897       var day = this.getDate();
1898       if(day > 28){
1899           day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
1900       }
1901       d.setDate(day);
1902       d.setMonth(this.getMonth() + value);
1903       break;
1904     case Date.YEAR:
1905       d.setFullYear(this.getFullYear() + value);
1906       break;
1907   }
1908   return d;
1909 };
1910 /**
1911  * @class Roo.lib.Dom
1912  * @licence LGPL
1913  * @static
1914  * 
1915  * Dom utils (from YIU afaik)
1916  *
1917  * 
1918  **/
1919 Roo.lib.Dom = {
1920     /**
1921      * Get the view width
1922      * @param {Boolean} full True will get the full document, otherwise it's the view width
1923      * @return {Number} The width
1924      */
1925      
1926     getViewWidth : function(full) {
1927         return full ? this.getDocumentWidth() : this.getViewportWidth();
1928     },
1929     /**
1930      * Get the view height
1931      * @param {Boolean} full True will get the full document, otherwise it's the view height
1932      * @return {Number} The height
1933      */
1934     getViewHeight : function(full) {
1935         return full ? this.getDocumentHeight() : this.getViewportHeight();
1936     },
1937     /**
1938      * Get the Full Document height 
1939      * @return {Number} The height
1940      */
1941     getDocumentHeight: function() {
1942         var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
1943         return Math.max(scrollHeight, this.getViewportHeight());
1944     },
1945     /**
1946      * Get the Full Document width
1947      * @return {Number} The width
1948      */
1949     getDocumentWidth: function() {
1950         var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
1951         return Math.max(scrollWidth, this.getViewportWidth());
1952     },
1953     /**
1954      * Get the Window Viewport height
1955      * @return {Number} The height
1956      */
1957     getViewportHeight: function() {
1958         var height = self.innerHeight;
1959         var mode = document.compatMode;
1960
1961         if ((mode || Roo.isIE) && !Roo.isOpera) {
1962             height = (mode == "CSS1Compat") ?
1963                      document.documentElement.clientHeight :
1964                      document.body.clientHeight;
1965         }
1966
1967         return height;
1968     },
1969     /**
1970      * Get the Window Viewport width
1971      * @return {Number} The width
1972      */
1973     getViewportWidth: function() {
1974         var width = self.innerWidth;
1975         var mode = document.compatMode;
1976
1977         if (mode || Roo.isIE) {
1978             width = (mode == "CSS1Compat") ?
1979                     document.documentElement.clientWidth :
1980                     document.body.clientWidth;
1981         }
1982         return width;
1983     },
1984
1985     isAncestor : function(p, c) {
1986         p = Roo.getDom(p);
1987         c = Roo.getDom(c);
1988         if (!p || !c) {
1989             return false;
1990         }
1991
1992         if (p.contains && !Roo.isSafari) {
1993             return p.contains(c);
1994         } else if (p.compareDocumentPosition) {
1995             return !!(p.compareDocumentPosition(c) & 16);
1996         } else {
1997             var parent = c.parentNode;
1998             while (parent) {
1999                 if (parent == p) {
2000                     return true;
2001                 }
2002                 else if (!parent.tagName || parent.tagName.toUpperCase() == "HTML") {
2003                     return false;
2004                 }
2005                 parent = parent.parentNode;
2006             }
2007             return false;
2008         }
2009     },
2010
2011     getRegion : function(el) {
2012         return Roo.lib.Region.getRegion(el);
2013     },
2014
2015     getY : function(el) {
2016         return this.getXY(el)[1];
2017     },
2018
2019     getX : function(el) {
2020         return this.getXY(el)[0];
2021     },
2022
2023     getXY : function(el) {
2024         var p, pe, b, scroll, bd = document.body;
2025         el = Roo.getDom(el);
2026         var fly = Roo.lib.AnimBase.fly;
2027         if (el.getBoundingClientRect) {
2028             b = el.getBoundingClientRect();
2029             scroll = fly(document).getScroll();
2030             return [b.left + scroll.left, b.top + scroll.top];
2031         }
2032         var x = 0, y = 0;
2033
2034         p = el;
2035
2036         var hasAbsolute = fly(el).getStyle("position") == "absolute";
2037
2038         while (p) {
2039
2040             x += p.offsetLeft;
2041             y += p.offsetTop;
2042
2043             if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
2044                 hasAbsolute = true;
2045             }
2046
2047             if (Roo.isGecko) {
2048                 pe = fly(p);
2049
2050                 var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
2051                 var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
2052
2053
2054                 x += bl;
2055                 y += bt;
2056
2057
2058                 if (p != el && pe.getStyle('overflow') != 'visible') {
2059                     x += bl;
2060                     y += bt;
2061                 }
2062             }
2063             p = p.offsetParent;
2064         }
2065
2066         if (Roo.isSafari && hasAbsolute) {
2067             x -= bd.offsetLeft;
2068             y -= bd.offsetTop;
2069         }
2070
2071         if (Roo.isGecko && !hasAbsolute) {
2072             var dbd = fly(bd);
2073             x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
2074             y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
2075         }
2076
2077         p = el.parentNode;
2078         while (p && p != bd) {
2079             if (!Roo.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
2080                 x -= p.scrollLeft;
2081                 y -= p.scrollTop;
2082             }
2083             p = p.parentNode;
2084         }
2085         return [x, y];
2086     },
2087  
2088   
2089
2090
2091     setXY : function(el, xy) {
2092         el = Roo.fly(el, '_setXY');
2093         el.position();
2094         var pts = el.translatePoints(xy);
2095         if (xy[0] !== false) {
2096             el.dom.style.left = pts.left + "px";
2097         }
2098         if (xy[1] !== false) {
2099             el.dom.style.top = pts.top + "px";
2100         }
2101     },
2102
2103     setX : function(el, x) {
2104         this.setXY(el, [x, false]);
2105     },
2106
2107     setY : function(el, y) {
2108         this.setXY(el, [false, y]);
2109     }
2110 };
2111 /*
2112  * Portions of this file are based on pieces of Yahoo User Interface Library
2113  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2114  * YUI licensed under the BSD License:
2115  * http://developer.yahoo.net/yui/license.txt
2116  * <script type="text/javascript">
2117  *
2118  */
2119
2120 Roo.lib.Event = function() {
2121     var loadComplete = false;
2122     var listeners = [];
2123     var unloadListeners = [];
2124     var retryCount = 0;
2125     var onAvailStack = [];
2126     var counter = 0;
2127     var lastError = null;
2128
2129     return {
2130         POLL_RETRYS: 200,
2131         POLL_INTERVAL: 20,
2132         EL: 0,
2133         TYPE: 1,
2134         FN: 2,
2135         WFN: 3,
2136         OBJ: 3,
2137         ADJ_SCOPE: 4,
2138         _interval: null,
2139
2140         startInterval: function() {
2141             if (!this._interval) {
2142                 var self = this;
2143                 var callback = function() {
2144                     self._tryPreloadAttach();
2145                 };
2146                 this._interval = setInterval(callback, this.POLL_INTERVAL);
2147
2148             }
2149         },
2150
2151         onAvailable: function(p_id, p_fn, p_obj, p_override) {
2152             onAvailStack.push({ id:         p_id,
2153                 fn:         p_fn,
2154                 obj:        p_obj,
2155                 override:   p_override,
2156                 checkReady: false    });
2157
2158             retryCount = this.POLL_RETRYS;
2159             this.startInterval();
2160         },
2161
2162
2163         addListener: function(el, eventName, fn) {
2164             el = Roo.getDom(el);
2165             if (!el || !fn) {
2166                 return false;
2167             }
2168
2169             if ("unload" == eventName) {
2170                 unloadListeners[unloadListeners.length] =
2171                 [el, eventName, fn];
2172                 return true;
2173             }
2174
2175             var wrappedFn = function(e) {
2176                 return fn(Roo.lib.Event.getEvent(e));
2177             };
2178
2179             var li = [el, eventName, fn, wrappedFn];
2180
2181             var index = listeners.length;
2182             listeners[index] = li;
2183
2184             this.doAdd(el, eventName, wrappedFn, false);
2185             return true;
2186
2187         },
2188
2189
2190         removeListener: function(el, eventName, fn) {
2191             var i, len;
2192
2193             el = Roo.getDom(el);
2194
2195             if(!fn) {
2196                 return this.purgeElement(el, false, eventName);
2197             }
2198
2199
2200             if ("unload" == eventName) {
2201
2202                 for (i = 0,len = unloadListeners.length; i < len; i++) {
2203                     var li = unloadListeners[i];
2204                     if (li &&
2205                         li[0] == el &&
2206                         li[1] == eventName &&
2207                         li[2] == fn) {
2208                         unloadListeners.splice(i, 1);
2209                         return true;
2210                     }
2211                 }
2212
2213                 return false;
2214             }
2215
2216             var cacheItem = null;
2217
2218
2219             var index = arguments[3];
2220
2221             if ("undefined" == typeof index) {
2222                 index = this._getCacheIndex(el, eventName, fn);
2223             }
2224
2225             if (index >= 0) {
2226                 cacheItem = listeners[index];
2227             }
2228
2229             if (!el || !cacheItem) {
2230                 return false;
2231             }
2232
2233             this.doRemove(el, eventName, cacheItem[this.WFN], false);
2234
2235             delete listeners[index][this.WFN];
2236             delete listeners[index][this.FN];
2237             listeners.splice(index, 1);
2238
2239             return true;
2240
2241         },
2242
2243
2244         getTarget: function(ev, resolveTextNode) {
2245             ev = ev.browserEvent || ev;
2246             ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev )  : ev;
2247             var t = ev.target || ev.srcElement;
2248             return this.resolveTextNode(t);
2249         },
2250
2251
2252         resolveTextNode: function(node) {
2253             if (Roo.isSafari && node && 3 == node.nodeType) {
2254                 return node.parentNode;
2255             } else {
2256                 return node;
2257             }
2258         },
2259
2260
2261         getPageX: function(ev) {
2262             ev = ev.browserEvent || ev;
2263             ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev )  : ev;
2264             var x = ev.pageX;
2265             if (!x && 0 !== x) {
2266                 x = ev.clientX || 0;
2267
2268                 if (Roo.isIE) {
2269                     x += this.getScroll()[1];
2270                 }
2271             }
2272
2273             return x;
2274         },
2275
2276
2277         getPageY: function(ev) {
2278             ev = ev.browserEvent || ev;
2279             ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev )  : ev;
2280             var y = ev.pageY;
2281             if (!y && 0 !== y) {
2282                 y = ev.clientY || 0;
2283
2284                 if (Roo.isIE) {
2285                     y += this.getScroll()[0];
2286                 }
2287             }
2288
2289
2290             return y;
2291         },
2292
2293
2294         getXY: function(ev) {
2295             ev = ev.browserEvent || ev;
2296             ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev )  : ev;
2297             return [this.getPageX(ev), this.getPageY(ev)];
2298         },
2299
2300
2301         getRelatedTarget: function(ev) {
2302             ev = ev.browserEvent || ev;
2303             ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev )  : ev;
2304             var t = ev.relatedTarget;
2305             if (!t) {
2306                 if (ev.type == "mouseout") {
2307                     t = ev.toElement;
2308                 } else if (ev.type == "mouseover") {
2309                     t = ev.fromElement;
2310                 }
2311             }
2312
2313             return this.resolveTextNode(t);
2314         },
2315
2316
2317         getTime: function(ev) {
2318             ev = ev.browserEvent || ev;
2319             ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev )  : ev;
2320             if (!ev.time) {
2321                 var t = new Date().getTime();
2322                 try {
2323                     ev.time = t;
2324                 } catch(ex) {
2325                     this.lastError = ex;
2326                     return t;
2327                 }
2328             }
2329
2330             return ev.time;
2331         },
2332
2333
2334         stopEvent: function(ev) {
2335             this.stopPropagation(ev);
2336             this.preventDefault(ev);
2337         },
2338
2339
2340         stopPropagation: function(ev) {
2341             ev = ev.browserEvent || ev;
2342             if (ev.stopPropagation) {
2343                 ev.stopPropagation();
2344             } else {
2345                 ev.cancelBubble = true;
2346             }
2347         },
2348
2349
2350         preventDefault: function(ev) {
2351             ev = ev.browserEvent || ev;
2352             if(ev.preventDefault) {
2353                 ev.preventDefault();
2354             } else {
2355                 ev.returnValue = false;
2356             }
2357         },
2358
2359
2360         getEvent: function(e) {
2361             var ev = e || window.event;
2362             if (!ev) {
2363                 var c = this.getEvent.caller;
2364                 while (c) {
2365                     ev = c.arguments[0];
2366                     if (ev && Event == ev.constructor) {
2367                         break;
2368                     }
2369                     c = c.caller;
2370                 }
2371             }
2372             return ev;
2373         },
2374
2375
2376         getCharCode: function(ev) {
2377             ev = ev.browserEvent || ev;
2378             return ev.charCode || ev.keyCode || 0;
2379         },
2380
2381
2382         _getCacheIndex: function(el, eventName, fn) {
2383             for (var i = 0,len = listeners.length; i < len; ++i) {
2384                 var li = listeners[i];
2385                 if (li &&
2386                     li[this.FN] == fn &&
2387                     li[this.EL] == el &&
2388                     li[this.TYPE] == eventName) {
2389                     return i;
2390                 }
2391             }
2392
2393             return -1;
2394         },
2395
2396
2397         elCache: {},
2398
2399
2400         getEl: function(id) {
2401             return document.getElementById(id);
2402         },
2403
2404
2405         clearCache: function() {
2406         },
2407
2408
2409         _load: function(e) {
2410             loadComplete = true;
2411             var EU = Roo.lib.Event;
2412
2413
2414             if (Roo.isIE) {
2415                 EU.doRemove(window, "load", EU._load);
2416             }
2417         },
2418
2419
2420         _tryPreloadAttach: function() {
2421
2422             if (this.locked) {
2423                 return false;
2424             }
2425
2426             this.locked = true;
2427
2428
2429             var tryAgain = !loadComplete;
2430             if (!tryAgain) {
2431                 tryAgain = (retryCount > 0);
2432             }
2433
2434
2435             var notAvail = [];
2436             for (var i = 0,len = onAvailStack.length; i < len; ++i) {
2437                 var item = onAvailStack[i];
2438                 if (item) {
2439                     var el = this.getEl(item.id);
2440
2441                     if (el) {
2442                         if (!item.checkReady ||
2443                             loadComplete ||
2444                             el.nextSibling ||
2445                             (document && document.body)) {
2446
2447                             var scope = el;
2448                             if (item.override) {
2449                                 if (item.override === true) {
2450                                     scope = item.obj;
2451                                 } else {
2452                                     scope = item.override;
2453                                 }
2454                             }
2455                             item.fn.call(scope, item.obj);
2456                             onAvailStack[i] = null;
2457                         }
2458                     } else {
2459                         notAvail.push(item);
2460                     }
2461                 }
2462             }
2463
2464             retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;
2465
2466             if (tryAgain) {
2467
2468                 this.startInterval();
2469             } else {
2470                 clearInterval(this._interval);
2471                 this._interval = null;
2472             }
2473
2474             this.locked = false;
2475
2476             return true;
2477
2478         },
2479
2480
2481         purgeElement: function(el, recurse, eventName) {
2482             var elListeners = this.getListeners(el, eventName);
2483             if (elListeners) {
2484                 for (var i = 0,len = elListeners.length; i < len; ++i) {
2485                     var l = elListeners[i];
2486                     this.removeListener(el, l.type, l.fn);
2487                 }
2488             }
2489
2490             if (recurse && el && el.childNodes) {
2491                 for (i = 0,len = el.childNodes.length; i < len; ++i) {
2492                     this.purgeElement(el.childNodes[i], recurse, eventName);
2493                 }
2494             }
2495         },
2496
2497
2498         getListeners: function(el, eventName) {
2499             var results = [], searchLists;
2500             if (!eventName) {
2501                 searchLists = [listeners, unloadListeners];
2502             } else if (eventName == "unload") {
2503                 searchLists = [unloadListeners];
2504             } else {
2505                 searchLists = [listeners];
2506             }
2507
2508             for (var j = 0; j < searchLists.length; ++j) {
2509                 var searchList = searchLists[j];
2510                 if (searchList && searchList.length > 0) {
2511                     for (var i = 0,len = searchList.length; i < len; ++i) {
2512                         var l = searchList[i];
2513                         if (l && l[this.EL] === el &&
2514                             (!eventName || eventName === l[this.TYPE])) {
2515                             results.push({
2516                                 type:   l[this.TYPE],
2517                                 fn:     l[this.FN],
2518                                 obj:    l[this.OBJ],
2519                                 adjust: l[this.ADJ_SCOPE],
2520                                 index:  i
2521                             });
2522                         }
2523                     }
2524                 }
2525             }
2526
2527             return (results.length) ? results : null;
2528         },
2529
2530
2531         _unload: function(e) {
2532
2533             var EU = Roo.lib.Event, i, j, l, len, index;
2534
2535             for (i = 0,len = unloadListeners.length; i < len; ++i) {
2536                 l = unloadListeners[i];
2537                 if (l) {
2538                     var scope = window;
2539                     if (l[EU.ADJ_SCOPE]) {
2540                         if (l[EU.ADJ_SCOPE] === true) {
2541                             scope = l[EU.OBJ];
2542                         } else {
2543                             scope = l[EU.ADJ_SCOPE];
2544                         }
2545                     }
2546                     l[EU.FN].call(scope, EU.getEvent(e), l[EU.OBJ]);
2547                     unloadListeners[i] = null;
2548                     l = null;
2549                     scope = null;
2550                 }
2551             }
2552
2553             unloadListeners = null;
2554
2555             if (listeners && listeners.length > 0) {
2556                 j = listeners.length;
2557                 while (j) {
2558                     index = j - 1;
2559                     l = listeners[index];
2560                     if (l) {
2561                         EU.removeListener(l[EU.EL], l[EU.TYPE],
2562                                 l[EU.FN], index);
2563                     }
2564                     j = j - 1;
2565                 }
2566                 l = null;
2567
2568                 EU.clearCache();
2569             }
2570
2571             EU.doRemove(window, "unload", EU._unload);
2572
2573         },
2574
2575
2576         getScroll: function() {
2577             var dd = document.documentElement, db = document.body;
2578             if (dd && (dd.scrollTop || dd.scrollLeft)) {
2579                 return [dd.scrollTop, dd.scrollLeft];
2580             } else if (db) {
2581                 return [db.scrollTop, db.scrollLeft];
2582             } else {
2583                 return [0, 0];
2584             }
2585         },
2586
2587
2588         doAdd: function () {
2589             if (window.addEventListener) {
2590                 return function(el, eventName, fn, capture) {
2591                     el.addEventListener(eventName, fn, (capture));
2592                 };
2593             } else if (window.attachEvent) {
2594                 return function(el, eventName, fn, capture) {
2595                     el.attachEvent("on" + eventName, fn);
2596                 };
2597             } else {
2598                 return function() {
2599                 };
2600             }
2601         }(),
2602
2603
2604         doRemove: function() {
2605             if (window.removeEventListener) {
2606                 return function (el, eventName, fn, capture) {
2607                     el.removeEventListener(eventName, fn, (capture));
2608                 };
2609             } else if (window.detachEvent) {
2610                 return function (el, eventName, fn) {
2611                     el.detachEvent("on" + eventName, fn);
2612                 };
2613             } else {
2614                 return function() {
2615                 };
2616             }
2617         }()
2618     };
2619     
2620 }();
2621 (function() {     
2622    
2623     var E = Roo.lib.Event;
2624     E.on = E.addListener;
2625     E.un = E.removeListener;
2626
2627     if (document && document.body) {
2628         E._load();
2629     } else {
2630         E.doAdd(window, "load", E._load);
2631     }
2632     E.doAdd(window, "unload", E._unload);
2633     E._tryPreloadAttach();
2634 })();
2635
2636  
2637
2638 (function() {
2639     /**
2640      * @class Roo.lib.Ajax
2641      *
2642      * provide a simple Ajax request utility functions
2643      * 
2644      * Portions of this file are based on pieces of Yahoo User Interface Library
2645     * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2646     * YUI licensed under the BSD License:
2647     * http://developer.yahoo.net/yui/license.txt
2648     * <script type="text/javascript">
2649     *
2650      *
2651      */
2652     Roo.lib.Ajax = {
2653         /**
2654          * @static 
2655          */
2656         request : function(method, uri, cb, data, options) {
2657             if(options){
2658                 var hs = options.headers;
2659                 if(hs){
2660                     for(var h in hs){
2661                         if(hs.hasOwnProperty(h)){
2662                             this.initHeader(h, hs[h], false);
2663                         }
2664                     }
2665                 }
2666                 if(options.xmlData){
2667                     this.initHeader('Content-Type', 'text/xml', false);
2668                     method = 'POST';
2669                     data = options.xmlData;
2670                 }
2671             }
2672
2673             return this.asyncRequest(method, uri, cb, data);
2674         },
2675         /**
2676          * serialize a form
2677          *
2678          * @static
2679          * @param {DomForm} form element
2680          * @return {String} urlencode form output.
2681          */
2682         serializeForm : function(form) {
2683             if(typeof form == 'string') {
2684                 form = (document.getElementById(form) || document.forms[form]);
2685             }
2686
2687             var el, name, val, disabled, data = '', hasSubmit = false;
2688             for (var i = 0; i < form.elements.length; i++) {
2689                 el = form.elements[i];
2690                 disabled = form.elements[i].disabled;
2691                 name = form.elements[i].name;
2692                 val = form.elements[i].value;
2693
2694                 if (!disabled && name){
2695                     switch (el.type)
2696                             {
2697                         case 'select-one':
2698                         case 'select-multiple':
2699                             for (var j = 0; j < el.options.length; j++) {
2700                                 if (el.options[j].selected) {
2701                                     if (Roo.isIE) {
2702                                         data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].attributes['value'].specified ? el.options[j].value : el.options[j].text) + '&';
2703                                     }
2704                                     else {
2705                                         data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].hasAttribute('value') ? el.options[j].value : el.options[j].text) + '&';
2706                                     }
2707                                 }
2708                             }
2709                             break;
2710                         case 'radio':
2711                         case 'checkbox':
2712                             if (el.checked) {
2713                                 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2714                             }
2715                             break;
2716                         case 'file':
2717
2718                         case undefined:
2719
2720                         case 'reset':
2721
2722                         case 'button':
2723
2724                             break;
2725                         case 'submit':
2726                             if(hasSubmit == false) {
2727                                 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2728                                 hasSubmit = true;
2729                             }
2730                             break;
2731                         default:
2732                             data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2733                             break;
2734                     }
2735                 }
2736             }
2737             data = data.substr(0, data.length - 1);
2738             return data;
2739         },
2740
2741         headers:{},
2742
2743         hasHeaders:false,
2744
2745         useDefaultHeader:true,
2746
2747         defaultPostHeader:'application/x-www-form-urlencoded',
2748
2749         useDefaultXhrHeader:true,
2750
2751         defaultXhrHeader:'XMLHttpRequest',
2752
2753         hasDefaultHeaders:true,
2754
2755         defaultHeaders:{},
2756
2757         poll:{},
2758
2759         timeout:{},
2760
2761         pollInterval:50,
2762
2763         transactionId:0,
2764
2765         setProgId:function(id)
2766         {
2767             this.activeX.unshift(id);
2768         },
2769
2770         setDefaultPostHeader:function(b)
2771         {
2772             this.useDefaultHeader = b;
2773         },
2774
2775         setDefaultXhrHeader:function(b)
2776         {
2777             this.useDefaultXhrHeader = b;
2778         },
2779
2780         setPollingInterval:function(i)
2781         {
2782             if (typeof i == 'number' && isFinite(i)) {
2783                 this.pollInterval = i;
2784             }
2785         },
2786
2787         createXhrObject:function(transactionId)
2788         {
2789             var obj,http;
2790             try
2791             {
2792
2793                 http = new XMLHttpRequest();
2794
2795                 obj = { conn:http, tId:transactionId };
2796             }
2797             catch(e)
2798             {
2799                 for (var i = 0; i < this.activeX.length; ++i) {
2800                     try
2801                     {
2802
2803                         http = new ActiveXObject(this.activeX[i]);
2804
2805                         obj = { conn:http, tId:transactionId };
2806                         break;
2807                     }
2808                     catch(e) {
2809                     }
2810                 }
2811             }
2812             finally
2813             {
2814                 return obj;
2815             }
2816         },
2817
2818         getConnectionObject:function()
2819         {
2820             var o;
2821             var tId = this.transactionId;
2822
2823             try
2824             {
2825                 o = this.createXhrObject(tId);
2826                 if (o) {
2827                     this.transactionId++;
2828                 }
2829             }
2830             catch(e) {
2831             }
2832             finally
2833             {
2834                 return o;
2835             }
2836         },
2837
2838         asyncRequest:function(method, uri, callback, postData)
2839         {
2840             var o = this.getConnectionObject();
2841
2842             if (!o) {
2843                 return null;
2844             }
2845             else {
2846                 o.conn.open(method, uri, true);
2847
2848                 if (this.useDefaultXhrHeader) {
2849                     if (!this.defaultHeaders['X-Requested-With']) {
2850                         this.initHeader('X-Requested-With', this.defaultXhrHeader, true);
2851                     }
2852                 }
2853
2854                 if(postData && this.useDefaultHeader){
2855                     this.initHeader('Content-Type', this.defaultPostHeader);
2856                 }
2857
2858                  if (this.hasDefaultHeaders || this.hasHeaders) {
2859                     this.setHeader(o);
2860                 }
2861
2862                 this.handleReadyState(o, callback);
2863                 o.conn.send(postData || null);
2864
2865                 return o;
2866             }
2867         },
2868
2869         handleReadyState:function(o, callback)
2870         {
2871             var oConn = this;
2872
2873             if (callback && callback.timeout) {
2874                 
2875                 this.timeout[o.tId] = window.setTimeout(function() {
2876                     oConn.abort(o, callback, true);
2877                 }, callback.timeout);
2878             }
2879
2880             this.poll[o.tId] = window.setInterval(
2881                     function() {
2882                         if (o.conn && o.conn.readyState == 4) {
2883                             window.clearInterval(oConn.poll[o.tId]);
2884                             delete oConn.poll[o.tId];
2885
2886                             if(callback && callback.timeout) {
2887                                 window.clearTimeout(oConn.timeout[o.tId]);
2888                                 delete oConn.timeout[o.tId];
2889                             }
2890
2891                             oConn.handleTransactionResponse(o, callback);
2892                         }
2893                     }
2894                     , this.pollInterval);
2895         },
2896
2897         handleTransactionResponse:function(o, callback, isAbort)
2898         {
2899
2900             if (!callback) {
2901                 this.releaseObject(o);
2902                 return;
2903             }
2904
2905             var httpStatus, responseObject;
2906
2907             try
2908             {
2909                 if (o.conn.status !== undefined && o.conn.status != 0) {
2910                     httpStatus = o.conn.status;
2911                 }
2912                 else {
2913                     httpStatus = 13030;
2914                 }
2915             }
2916             catch(e) {
2917
2918
2919                 httpStatus = 13030;
2920             }
2921
2922             if (httpStatus >= 200 && httpStatus < 300) {
2923                 responseObject = this.createResponseObject(o, callback.argument);
2924                 if (callback.success) {
2925                     if (!callback.scope) {
2926                         callback.success(responseObject);
2927                     }
2928                     else {
2929
2930
2931                         callback.success.apply(callback.scope, [responseObject]);
2932                     }
2933                 }
2934             }
2935             else {
2936                 switch (httpStatus) {
2937
2938                     case 12002:
2939                     case 12029:
2940                     case 12030:
2941                     case 12031:
2942                     case 12152:
2943                     case 13030:
2944                         responseObject = this.createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false));
2945                         if (callback.failure) {
2946                             if (!callback.scope) {
2947                                 callback.failure(responseObject);
2948                             }
2949                             else {
2950                                 callback.failure.apply(callback.scope, [responseObject]);
2951                             }
2952                         }
2953                         break;
2954                     default:
2955                         responseObject = this.createResponseObject(o, callback.argument);
2956                         if (callback.failure) {
2957                             if (!callback.scope) {
2958                                 callback.failure(responseObject);
2959                             }
2960                             else {
2961                                 callback.failure.apply(callback.scope, [responseObject]);
2962                             }
2963                         }
2964                 }
2965             }
2966
2967             this.releaseObject(o);
2968             responseObject = null;
2969         },
2970
2971         createResponseObject:function(o, callbackArg)
2972         {
2973             var obj = {};
2974             var headerObj = {};
2975
2976             try
2977             {
2978                 var headerStr = o.conn.getAllResponseHeaders();
2979                 var header = headerStr.split('\n');
2980                 for (var i = 0; i < header.length; i++) {
2981                     var delimitPos = header[i].indexOf(':');
2982                     if (delimitPos != -1) {
2983                         headerObj[header[i].substring(0, delimitPos)] = header[i].substring(delimitPos + 2);
2984                     }
2985                 }
2986             }
2987             catch(e) {
2988             }
2989
2990             obj.tId = o.tId;
2991             obj.status = o.conn.status;
2992             obj.statusText = o.conn.statusText;
2993             obj.getResponseHeader = headerObj;
2994             obj.getAllResponseHeaders = headerStr;
2995             obj.responseText = o.conn.responseText;
2996             obj.responseXML = o.conn.responseXML;
2997
2998             if (typeof callbackArg !== undefined) {
2999                 obj.argument = callbackArg;
3000             }
3001
3002             return obj;
3003         },
3004
3005         createExceptionObject:function(tId, callbackArg, isAbort)
3006         {
3007             var COMM_CODE = 0;
3008             var COMM_ERROR = 'communication failure';
3009             var ABORT_CODE = -1;
3010             var ABORT_ERROR = 'transaction aborted';
3011
3012             var obj = {};
3013
3014             obj.tId = tId;
3015             if (isAbort) {
3016                 obj.status = ABORT_CODE;
3017                 obj.statusText = ABORT_ERROR;
3018             }
3019             else {
3020                 obj.status = COMM_CODE;
3021                 obj.statusText = COMM_ERROR;
3022             }
3023
3024             if (callbackArg) {
3025                 obj.argument = callbackArg;
3026             }
3027
3028             return obj;
3029         },
3030
3031         initHeader:function(label, value, isDefault)
3032         {
3033             var headerObj = (isDefault) ? this.defaultHeaders : this.headers;
3034
3035             if (headerObj[label] === undefined) {
3036                 headerObj[label] = value;
3037             }
3038             else {
3039
3040
3041                 headerObj[label] = value + "," + headerObj[label];
3042             }
3043
3044             if (isDefault) {
3045                 this.hasDefaultHeaders = true;
3046             }
3047             else {
3048                 this.hasHeaders = true;
3049             }
3050         },
3051
3052
3053         setHeader:function(o)
3054         {
3055             if (this.hasDefaultHeaders) {
3056                 for (var prop in this.defaultHeaders) {
3057                     if (this.defaultHeaders.hasOwnProperty(prop)) {
3058                         o.conn.setRequestHeader(prop, this.defaultHeaders[prop]);
3059                     }
3060                 }
3061             }
3062
3063             if (this.hasHeaders) {
3064                 for (var prop in this.headers) {
3065                     if (this.headers.hasOwnProperty(prop)) {
3066                         o.conn.setRequestHeader(prop, this.headers[prop]);
3067                     }
3068                 }
3069                 this.headers = {};
3070                 this.hasHeaders = false;
3071             }
3072         },
3073
3074         resetDefaultHeaders:function() {
3075             delete this.defaultHeaders;
3076             this.defaultHeaders = {};
3077             this.hasDefaultHeaders = false;
3078         },
3079
3080         abort:function(o, callback, isTimeout)
3081         {
3082             if(this.isCallInProgress(o)) {
3083                 o.conn.abort();
3084                 window.clearInterval(this.poll[o.tId]);
3085                 delete this.poll[o.tId];
3086                 if (isTimeout) {
3087                     delete this.timeout[o.tId];
3088                 }
3089
3090                 this.handleTransactionResponse(o, callback, true);
3091
3092                 return true;
3093             }
3094             else {
3095                 return false;
3096             }
3097         },
3098
3099
3100         isCallInProgress:function(o)
3101         {
3102             if (o && o.conn) {
3103                 return o.conn.readyState != 4 && o.conn.readyState != 0;
3104             }
3105             else {
3106
3107                 return false;
3108             }
3109         },
3110
3111
3112         releaseObject:function(o)
3113         {
3114
3115             o.conn = null;
3116
3117             o = null;
3118         },
3119
3120         activeX:[
3121         'MSXML2.XMLHTTP.3.0',
3122         'MSXML2.XMLHTTP',
3123         'Microsoft.XMLHTTP'
3124         ]
3125
3126
3127     };
3128 })();/*
3129  * Portions of this file are based on pieces of Yahoo User Interface Library
3130  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3131  * YUI licensed under the BSD License:
3132  * http://developer.yahoo.net/yui/license.txt
3133  * <script type="text/javascript">
3134  *
3135  */
3136
3137 Roo.lib.Region = function(t, r, b, l) {
3138     this.top = t;
3139     this[1] = t;
3140     this.right = r;
3141     this.bottom = b;
3142     this.left = l;
3143     this[0] = l;
3144 };
3145
3146
3147 Roo.lib.Region.prototype = {
3148     contains : function(region) {
3149         return ( region.left >= this.left &&
3150                  region.right <= this.right &&
3151                  region.top >= this.top &&
3152                  region.bottom <= this.bottom    );
3153
3154     },
3155
3156     getArea : function() {
3157         return ( (this.bottom - this.top) * (this.right - this.left) );
3158     },
3159
3160     intersect : function(region) {
3161         var t = Math.max(this.top, region.top);
3162         var r = Math.min(this.right, region.right);
3163         var b = Math.min(this.bottom, region.bottom);
3164         var l = Math.max(this.left, region.left);
3165
3166         if (b >= t && r >= l) {
3167             return new Roo.lib.Region(t, r, b, l);
3168         } else {
3169             return null;
3170         }
3171     },
3172     union : function(region) {
3173         var t = Math.min(this.top, region.top);
3174         var r = Math.max(this.right, region.right);
3175         var b = Math.max(this.bottom, region.bottom);
3176         var l = Math.min(this.left, region.left);
3177
3178         return new Roo.lib.Region(t, r, b, l);
3179     },
3180
3181     adjust : function(t, l, b, r) {
3182         this.top += t;
3183         this.left += l;
3184         this.right += r;
3185         this.bottom += b;
3186         return this;
3187     }
3188 };
3189
3190 Roo.lib.Region.getRegion = function(el) {
3191     var p = Roo.lib.Dom.getXY(el);
3192
3193     var t = p[1];
3194     var r = p[0] + el.offsetWidth;
3195     var b = p[1] + el.offsetHeight;
3196     var l = p[0];
3197
3198     return new Roo.lib.Region(t, r, b, l);
3199 };
3200 /*
3201  * Portions of this file are based on pieces of Yahoo User Interface Library
3202  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3203  * YUI licensed under the BSD License:
3204  * http://developer.yahoo.net/yui/license.txt
3205  * <script type="text/javascript">
3206  *
3207  */
3208 //@@dep Roo.lib.Region
3209
3210
3211 Roo.lib.Point = function(x, y) {
3212     if (x instanceof Array) {
3213         y = x[1];
3214         x = x[0];
3215     }
3216     this.x = this.right = this.left = this[0] = x;
3217     this.y = this.top = this.bottom = this[1] = y;
3218 };
3219
3220 Roo.lib.Point.prototype = new Roo.lib.Region();
3221 /*
3222  * Portions of this file are based on pieces of Yahoo User Interface Library
3223  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3224  * YUI licensed under the BSD License:
3225  * http://developer.yahoo.net/yui/license.txt
3226  * <script type="text/javascript">
3227  *
3228  */
3229  
3230 (function() {   
3231
3232     Roo.lib.Anim = {
3233         scroll : function(el, args, duration, easing, cb, scope) {
3234             this.run(el, args, duration, easing, cb, scope, Roo.lib.Scroll);
3235         },
3236
3237         motion : function(el, args, duration, easing, cb, scope) {
3238             this.run(el, args, duration, easing, cb, scope, Roo.lib.Motion);
3239         },
3240
3241         color : function(el, args, duration, easing, cb, scope) {
3242             this.run(el, args, duration, easing, cb, scope, Roo.lib.ColorAnim);
3243         },
3244
3245         run : function(el, args, duration, easing, cb, scope, type) {
3246             type = type || Roo.lib.AnimBase;
3247             if (typeof easing == "string") {
3248                 easing = Roo.lib.Easing[easing];
3249             }
3250             var anim = new type(el, args, duration, easing);
3251             anim.animateX(function() {
3252                 Roo.callback(cb, scope);
3253             });
3254             return anim;
3255         }
3256     };
3257 })();/*
3258  * Portions of this file are based on pieces of Yahoo User Interface Library
3259  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3260  * YUI licensed under the BSD License:
3261  * http://developer.yahoo.net/yui/license.txt
3262  * <script type="text/javascript">
3263  *
3264  */
3265
3266 (function() {    
3267     var libFlyweight;
3268     
3269     function fly(el) {
3270         if (!libFlyweight) {
3271             libFlyweight = new Roo.Element.Flyweight();
3272         }
3273         libFlyweight.dom = el;
3274         return libFlyweight;
3275     }
3276
3277     // since this uses fly! - it cant be in DOM (which does not have fly yet..)
3278     
3279    
3280     
3281     Roo.lib.AnimBase = function(el, attributes, duration, method) {
3282         if (el) {
3283             this.init(el, attributes, duration, method);
3284         }
3285     };
3286
3287     Roo.lib.AnimBase.fly = fly;
3288     
3289     
3290     
3291     Roo.lib.AnimBase.prototype = {
3292
3293         toString: function() {
3294             var el = this.getEl();
3295             var id = el.id || el.tagName;
3296             return ("Anim " + id);
3297         },
3298
3299         patterns: {
3300             noNegatives:        /width|height|opacity|padding/i,
3301             offsetAttribute:  /^((width|height)|(top|left))$/,
3302             defaultUnit:        /width|height|top$|bottom$|left$|right$/i,
3303             offsetUnit:         /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i
3304         },
3305
3306
3307         doMethod: function(attr, start, end) {
3308             return this.method(this.currentFrame, start, end - start, this.totalFrames);
3309         },
3310
3311
3312         setAttribute: function(attr, val, unit) {
3313             if (this.patterns.noNegatives.test(attr)) {
3314                 val = (val > 0) ? val : 0;
3315             }
3316
3317             Roo.fly(this.getEl(), '_anim').setStyle(attr, val + unit);
3318         },
3319
3320
3321         getAttribute: function(attr) {
3322             var el = this.getEl();
3323             var val = fly(el).getStyle(attr);
3324
3325             if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) {
3326                 return parseFloat(val);
3327             }
3328
3329             var a = this.patterns.offsetAttribute.exec(attr) || [];
3330             var pos = !!( a[3] );
3331             var box = !!( a[2] );
3332
3333
3334             if (box || (fly(el).getStyle('position') == 'absolute' && pos)) {
3335                 val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)];
3336             } else {
3337                 val = 0;
3338             }
3339
3340             return val;
3341         },
3342
3343
3344         getDefaultUnit: function(attr) {
3345             if (this.patterns.defaultUnit.test(attr)) {
3346                 return 'px';
3347             }
3348
3349             return '';
3350         },
3351
3352         animateX : function(callback, scope) {
3353             var f = function() {
3354                 this.onComplete.removeListener(f);
3355                 if (typeof callback == "function") {
3356                     callback.call(scope || this, this);
3357                 }
3358             };
3359             this.onComplete.addListener(f, this);
3360             this.animate();
3361         },
3362
3363
3364         setRuntimeAttribute: function(attr) {
3365             var start;
3366             var end;
3367             var attributes = this.attributes;
3368
3369             this.runtimeAttributes[attr] = {};
3370
3371             var isset = function(prop) {
3372                 return (typeof prop !== 'undefined');
3373             };
3374
3375             if (!isset(attributes[attr]['to']) && !isset(attributes[attr]['by'])) {
3376                 return false;
3377             }
3378
3379             start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr);
3380
3381
3382             if (isset(attributes[attr]['to'])) {
3383                 end = attributes[attr]['to'];
3384             } else if (isset(attributes[attr]['by'])) {
3385                 if (start.constructor == Array) {
3386                     end = [];
3387                     for (var i = 0, len = start.length; i < len; ++i) {
3388                         end[i] = start[i] + attributes[attr]['by'][i];
3389                     }
3390                 } else {
3391                     end = start + attributes[attr]['by'];
3392                 }
3393             }
3394
3395             this.runtimeAttributes[attr].start = start;
3396             this.runtimeAttributes[attr].end = end;
3397
3398
3399             this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr);
3400         },
3401
3402
3403         init: function(el, attributes, duration, method) {
3404
3405             var isAnimated = false;
3406
3407
3408             var startTime = null;
3409
3410
3411             var actualFrames = 0;
3412
3413
3414             el = Roo.getDom(el);
3415
3416
3417             this.attributes = attributes || {};
3418
3419
3420             this.duration = duration || 1;
3421
3422
3423             this.method = method || Roo.lib.Easing.easeNone;
3424
3425
3426             this.useSeconds = true;
3427
3428
3429             this.currentFrame = 0;
3430
3431
3432             this.totalFrames = Roo.lib.AnimMgr.fps;
3433
3434
3435             this.getEl = function() {
3436                 return el;
3437             };
3438
3439
3440             this.isAnimated = function() {
3441                 return isAnimated;
3442             };
3443
3444
3445             this.getStartTime = function() {
3446                 return startTime;
3447             };
3448
3449             this.runtimeAttributes = {};
3450
3451
3452             this.animate = function() {
3453                 if (this.isAnimated()) {
3454                     return false;
3455                 }
3456
3457                 this.currentFrame = 0;
3458
3459                 this.totalFrames = ( this.useSeconds ) ? Math.ceil(Roo.lib.AnimMgr.fps * this.duration) : this.duration;
3460
3461                 Roo.lib.AnimMgr.registerElement(this);
3462             };
3463
3464
3465             this.stop = function(finish) {
3466                 if (finish) {
3467                     this.currentFrame = this.totalFrames;
3468                     this._onTween.fire();
3469                 }
3470                 Roo.lib.AnimMgr.stop(this);
3471             };
3472
3473             var onStart = function() {
3474                 this.onStart.fire();
3475
3476                 this.runtimeAttributes = {};
3477                 for (var attr in this.attributes) {
3478                     this.setRuntimeAttribute(attr);
3479                 }
3480
3481                 isAnimated = true;
3482                 actualFrames = 0;
3483                 startTime = new Date();
3484             };
3485
3486
3487             var onTween = function() {
3488                 var data = {
3489                     duration: new Date() - this.getStartTime(),
3490                     currentFrame: this.currentFrame
3491                 };
3492
3493                 data.toString = function() {
3494                     return (
3495                             'duration: ' + data.duration +
3496                             ', currentFrame: ' + data.currentFrame
3497                             );
3498                 };
3499
3500                 this.onTween.fire(data);
3501
3502                 var runtimeAttributes = this.runtimeAttributes;
3503
3504                 for (var attr in runtimeAttributes) {
3505                     this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit);
3506                 }
3507
3508                 actualFrames += 1;
3509             };
3510
3511             var onComplete = function() {
3512                 var actual_duration = (new Date() - startTime) / 1000 ;
3513
3514                 var data = {
3515                     duration: actual_duration,
3516                     frames: actualFrames,
3517                     fps: actualFrames / actual_duration
3518                 };
3519
3520                 data.toString = function() {
3521                     return (
3522                             'duration: ' + data.duration +
3523                             ', frames: ' + data.frames +
3524                             ', fps: ' + data.fps
3525                             );
3526                 };
3527
3528                 isAnimated = false;
3529                 actualFrames = 0;
3530                 this.onComplete.fire(data);
3531             };
3532
3533
3534             this._onStart = new Roo.util.Event(this);
3535             this.onStart = new Roo.util.Event(this);
3536             this.onTween = new Roo.util.Event(this);
3537             this._onTween = new Roo.util.Event(this);
3538             this.onComplete = new Roo.util.Event(this);
3539             this._onComplete = new Roo.util.Event(this);
3540             this._onStart.addListener(onStart);
3541             this._onTween.addListener(onTween);
3542             this._onComplete.addListener(onComplete);
3543         }
3544     };
3545 })();
3546 /*
3547  * Portions of this file are based on pieces of Yahoo User Interface Library
3548  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3549  * YUI licensed under the BSD License:
3550  * http://developer.yahoo.net/yui/license.txt
3551  * <script type="text/javascript">
3552  *
3553  */
3554
3555 Roo.lib.AnimMgr = new function() {
3556
3557     var thread = null;
3558
3559
3560     var queue = [];
3561
3562
3563     var tweenCount = 0;
3564
3565
3566     this.fps = 1000;
3567
3568
3569     this.delay = 1;
3570
3571
3572     this.registerElement = function(tween) {
3573         queue[queue.length] = tween;
3574         tweenCount += 1;
3575         tween._onStart.fire();
3576         this.start();
3577     };
3578
3579
3580     this.unRegister = function(tween, index) {
3581         tween._onComplete.fire();
3582         index = index || getIndex(tween);
3583         if (index != -1) {
3584             queue.splice(index, 1);
3585         }
3586
3587         tweenCount -= 1;
3588         if (tweenCount <= 0) {
3589             this.stop();
3590         }
3591     };
3592
3593
3594     this.start = function() {
3595         if (thread === null) {
3596             thread = setInterval(this.run, this.delay);
3597         }
3598     };
3599
3600
3601     this.stop = function(tween) {
3602         if (!tween) {
3603             clearInterval(thread);
3604
3605             for (var i = 0, len = queue.length; i < len; ++i) {
3606                 if (queue[0].isAnimated()) {
3607                     this.unRegister(queue[0], 0);
3608                 }
3609             }
3610
3611             queue = [];
3612             thread = null;
3613             tweenCount = 0;
3614         }
3615         else {
3616             this.unRegister(tween);
3617         }
3618     };
3619
3620
3621     this.run = function() {
3622         for (var i = 0, len = queue.length; i < len; ++i) {
3623             var tween = queue[i];
3624             if (!tween || !tween.isAnimated()) {
3625                 continue;
3626             }
3627
3628             if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null)
3629             {
3630                 tween.currentFrame += 1;
3631
3632                 if (tween.useSeconds) {
3633                     correctFrame(tween);
3634                 }
3635                 tween._onTween.fire();
3636             }
3637             else {
3638                 Roo.lib.AnimMgr.stop(tween, i);
3639             }
3640         }
3641     };
3642
3643     var getIndex = function(anim) {
3644         for (var i = 0, len = queue.length; i < len; ++i) {
3645             if (queue[i] == anim) {
3646                 return i;
3647             }
3648         }
3649         return -1;
3650     };
3651
3652
3653     var correctFrame = function(tween) {
3654         var frames = tween.totalFrames;
3655         var frame = tween.currentFrame;
3656         var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames);
3657         var elapsed = (new Date() - tween.getStartTime());
3658         var tweak = 0;
3659
3660         if (elapsed < tween.duration * 1000) {
3661             tweak = Math.round((elapsed / expected - 1) * tween.currentFrame);
3662         } else {
3663             tweak = frames - (frame + 1);
3664         }
3665         if (tweak > 0 && isFinite(tweak)) {
3666             if (tween.currentFrame + tweak >= frames) {
3667                 tweak = frames - (frame + 1);
3668             }
3669
3670             tween.currentFrame += tweak;
3671         }
3672     };
3673 };
3674
3675     /*
3676  * Portions of this file are based on pieces of Yahoo User Interface Library
3677  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3678  * YUI licensed under the BSD License:
3679  * http://developer.yahoo.net/yui/license.txt
3680  * <script type="text/javascript">
3681  *
3682  */
3683 Roo.lib.Bezier = new function() {
3684
3685         this.getPosition = function(points, t) {
3686             var n = points.length;
3687             var tmp = [];
3688
3689             for (var i = 0; i < n; ++i) {
3690                 tmp[i] = [points[i][0], points[i][1]];
3691             }
3692
3693             for (var j = 1; j < n; ++j) {
3694                 for (i = 0; i < n - j; ++i) {
3695                     tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
3696                     tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
3697                 }
3698             }
3699
3700             return [ tmp[0][0], tmp[0][1] ];
3701
3702         };
3703     }; 
3704
3705 /**
3706  * @class Roo.lib.Color
3707  * @constructor
3708  * An abstract Color implementation. Concrete Color implementations should use
3709  * an instance of this function as their prototype, and implement the getRGB and
3710  * getHSL functions. getRGB should return an object representing the RGB
3711  * components of this Color, with the red, green, and blue components in the
3712  * range [0,255] and the alpha component in the range [0,100]. getHSL should
3713  * return an object representing the HSL components of this Color, with the hue
3714  * component in the range [0,360), the saturation and lightness components in
3715  * the range [0,100], and the alpha component in the range [0,1].
3716  *
3717  *
3718  * Color.js
3719  *
3720  * Functions for Color handling and processing.
3721  *
3722  * http://www.safalra.com/web-design/javascript/Color-handling-and-processing/
3723  *
3724  * The author of this program, Safalra (Stephen Morley), irrevocably releases all
3725  * rights to this program, with the intention of it becoming part of the public
3726  * domain. Because this program is released into the public domain, it comes with
3727  * no warranty either expressed or implied, to the extent permitted by law.
3728  * 
3729  * For more free and public domain JavaScript code by the same author, visit:
3730  * http://www.safalra.com/web-design/javascript/
3731  * 
3732  */
3733 Roo.lib.Color = function() { }
3734
3735
3736 Roo.apply(Roo.lib.Color.prototype, {
3737   
3738   rgb : null,
3739   hsv : null,
3740   hsl : null,
3741   
3742   /**
3743    * getIntegerRGB
3744    * @return {Object} an object representing the RGBA components of this Color. The red,
3745    * green, and blue components are converted to integers in the range [0,255].
3746    * The alpha is a value in the range [0,1].
3747    */
3748   getIntegerRGB : function(){
3749
3750     // get the RGB components of this Color
3751     var rgb = this.getRGB();
3752
3753     // return the integer components
3754     return {
3755       'r' : Math.round(rgb.r),
3756       'g' : Math.round(rgb.g),
3757       'b' : Math.round(rgb.b),
3758       'a' : rgb.a
3759     };
3760
3761   },
3762
3763   /**
3764    * getPercentageRGB
3765    * @return {Object} an object representing the RGBA components of this Color. The red,
3766    * green, and blue components are converted to numbers in the range [0,100].
3767    * The alpha is a value in the range [0,1].
3768    */
3769   getPercentageRGB : function(){
3770
3771     // get the RGB components of this Color
3772     var rgb = this.getRGB();
3773
3774     // return the percentage components
3775     return {
3776       'r' : 100 * rgb.r / 255,
3777       'g' : 100 * rgb.g / 255,
3778       'b' : 100 * rgb.b / 255,
3779       'a' : rgb.a
3780     };
3781
3782   },
3783
3784   /**
3785    * getCSSHexadecimalRGB
3786    * @return {String} a string representing this Color as a CSS hexadecimal RGB Color
3787    * value - that is, a string of the form #RRGGBB where each of RR, GG, and BB
3788    * are two-digit hexadecimal numbers.
3789    */
3790   getCSSHexadecimalRGB : function()
3791   {
3792
3793     // get the integer RGB components
3794     var rgb = this.getIntegerRGB();
3795
3796     // determine the hexadecimal equivalents
3797     var r16 = rgb.r.toString(16);
3798     var g16 = rgb.g.toString(16);
3799     var b16 = rgb.b.toString(16);
3800
3801     // return the CSS RGB Color value
3802     return '#'
3803         + (r16.length == 2 ? r16 : '0' + r16)
3804         + (g16.length == 2 ? g16 : '0' + g16)
3805         + (b16.length == 2 ? b16 : '0' + b16);
3806
3807   },
3808
3809   /**
3810    * getCSSIntegerRGB
3811    * @return {String} a string representing this Color as a CSS integer RGB Color
3812    * value - that is, a string of the form rgb(r,g,b) where each of r, g, and b
3813    * are integers in the range [0,255].
3814    */
3815   getCSSIntegerRGB : function(){
3816
3817     // get the integer RGB components
3818     var rgb = this.getIntegerRGB();
3819
3820     // return the CSS RGB Color value
3821     return 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
3822
3823   },
3824
3825   /**
3826    * getCSSIntegerRGBA
3827    * @return {String} Returns a string representing this Color as a CSS integer RGBA Color
3828    * value - that is, a string of the form rgba(r,g,b,a) where each of r, g, and
3829    * b are integers in the range [0,255] and a is in the range [0,1].
3830    */
3831   getCSSIntegerRGBA : function(){
3832
3833     // get the integer RGB components
3834     var rgb = this.getIntegerRGB();
3835
3836     // return the CSS integer RGBA Color value
3837     return 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + rgb.a + ')';
3838
3839   },
3840
3841   /**
3842    * getCSSPercentageRGB
3843    * @return {String} a string representing this Color as a CSS percentage RGB Color
3844    * value - that is, a string of the form rgb(r%,g%,b%) where each of r, g, and
3845    * b are in the range [0,100].
3846    */
3847   getCSSPercentageRGB : function(){
3848
3849     // get the percentage RGB components
3850     var rgb = this.getPercentageRGB();
3851
3852     // return the CSS RGB Color value
3853     return 'rgb(' + rgb.r + '%,' + rgb.g + '%,' + rgb.b + '%)';
3854
3855   },
3856
3857   /**
3858    * getCSSPercentageRGBA
3859    * @return {String} a string representing this Color as a CSS percentage RGBA Color
3860    * value - that is, a string of the form rgba(r%,g%,b%,a) where each of r, g,
3861    * and b are in the range [0,100] and a is in the range [0,1].
3862    */
3863   getCSSPercentageRGBA : function(){
3864
3865     // get the percentage RGB components
3866     var rgb = this.getPercentageRGB();
3867
3868     // return the CSS percentage RGBA Color value
3869     return 'rgb(' + rgb.r + '%,' + rgb.g + '%,' + rgb.b + '%,' + rgb.a + ')';
3870
3871   },
3872
3873   /**
3874    * getCSSHSL
3875    * @return {String} a string representing this Color as a CSS HSL Color value - that
3876    * is, a string of the form hsl(h,s%,l%) where h is in the range [0,100] and
3877    * s and l are in the range [0,100].
3878    */
3879   getCSSHSL : function(){
3880
3881     // get the HSL components
3882     var hsl = this.getHSL();
3883
3884     // return the CSS HSL Color value
3885     return 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%)';
3886
3887   },
3888
3889   /**
3890    * getCSSHSLA
3891    * @return {String} a string representing this Color as a CSS HSLA Color value - that
3892    * is, a string of the form hsla(h,s%,l%,a) where h is in the range [0,100],
3893    * s and l are in the range [0,100], and a is in the range [0,1].
3894    */
3895   getCSSHSLA : function(){
3896
3897     // get the HSL components
3898     var hsl = this.getHSL();
3899
3900     // return the CSS HSL Color value
3901     return 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%,' + hsl.a + ')';
3902
3903   },
3904
3905   /**
3906    * Sets the Color of the specified node to this Color. This functions sets
3907    * the CSS 'color' property for the node. The parameter is:
3908    * 
3909    * @param {DomElement} node - the node whose Color should be set
3910    */
3911   setNodeColor : function(node){
3912
3913     // set the Color of the node
3914     node.style.color = this.getCSSHexadecimalRGB();
3915
3916   },
3917
3918   /**
3919    * Sets the background Color of the specified node to this Color. This
3920    * functions sets the CSS 'background-color' property for the node. The
3921    * parameter is:
3922    *
3923    * @param {DomElement} node - the node whose background Color should be set
3924    */
3925   setNodeBackgroundColor : function(node){
3926
3927     // set the background Color of the node
3928     node.style.backgroundColor = this.getCSSHexadecimalRGB();
3929
3930   },
3931   // convert between formats..
3932   toRGB: function()
3933   {
3934     var r = this.getIntegerRGB();
3935     return new Roo.lib.RGBColor(r.r,r.g,r.b,r.a);
3936     
3937   },
3938   toHSL : function()
3939   {
3940      var hsl = this.getHSL();
3941   // return the CSS HSL Color value
3942     return new Roo.lib.HSLColor(hsl.h,  hsl.s, hsl.l ,  hsl.a );
3943     
3944   },
3945   
3946   toHSV : function()
3947   {
3948     var rgb = this.toRGB();
3949     var hsv = rgb.getHSV();
3950    // return the CSS HSL Color value
3951     return new Roo.lib.HSVColor(hsv.h,  hsv.s, hsv.v ,  hsv.a );
3952     
3953   },
3954   
3955   // modify  v = 0 ... 1 (eg. 0.5)
3956   saturate : function(v)
3957   {
3958       var rgb = this.toRGB();
3959       var hsv = rgb.getHSV();
3960       return new Roo.lib.HSVColor(hsv.h,  hsv.s * v, hsv.v ,  hsv.a );
3961       
3962   
3963   },
3964   
3965    
3966   /**
3967    * getRGB
3968    * @return {Object} the RGB and alpha components of this Color as an object with r,
3969    * g, b, and a properties. r, g, and b are in the range [0,255] and a is in
3970    * the range [0,1].
3971    */
3972   getRGB: function(){
3973    
3974     // return the RGB components
3975     return {
3976       'r' : this.rgb.r,
3977       'g' : this.rgb.g,
3978       'b' : this.rgb.b,
3979       'a' : this.alpha
3980     };
3981
3982   },
3983
3984   /**
3985    * getHSV
3986    * @return {Object} the HSV and alpha components of this Color as an object with h,
3987    * s, v, and a properties. h is in the range [0,360), s and v are in the range
3988    * [0,100], and a is in the range [0,1].
3989    */
3990   getHSV : function()
3991   {
3992     
3993     // calculate the HSV components if necessary
3994     if (this.hsv == null) {
3995       this.calculateHSV();
3996     }
3997
3998     // return the HSV components
3999     return {
4000       'h' : this.hsv.h,
4001       's' : this.hsv.s,
4002       'v' : this.hsv.v,
4003       'a' : this.alpha
4004     };
4005
4006   },
4007
4008   /**
4009    * getHSL
4010    * @return {Object} the HSL and alpha components of this Color as an object with h,
4011    * s, l, and a properties. h is in the range [0,360), s and l are in the range
4012    * [0,100], and a is in the range [0,1].
4013    */
4014   getHSL : function(){
4015     
4016      
4017     // calculate the HSV components if necessary
4018     if (this.hsl == null) { this.calculateHSL(); }
4019
4020     // return the HSL components
4021     return {
4022       'h' : this.hsl.h,
4023       's' : this.hsl.s,
4024       'l' : this.hsl.l,
4025       'a' : this.alpha
4026     };
4027
4028   }
4029   
4030
4031 });
4032
4033
4034 /**
4035  * @class Roo.lib.RGBColor
4036  * @extends Roo.lib.Color
4037  * Creates a Color specified in the RGB Color space, with an optional alpha
4038  * component. The parameters are:
4039  * @constructor
4040  * 
4041
4042  * @param {Number} r - the red component, clipped to the range [0,255]
4043  * @param {Number} g - the green component, clipped to the range [0,255]
4044  * @param {Number} b - the blue component, clipped to the range [0,255]
4045  * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4046  *     optional and defaults to 1
4047  */
4048 Roo.lib.RGBColor = function (r, g, b, a){
4049
4050   // store the alpha component after clipping it if necessary
4051   this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4052
4053   // store the RGB components after clipping them if necessary
4054   this.rgb =
4055       {
4056         'r' : Math.max(0, Math.min(255, r)),
4057         'g' : Math.max(0, Math.min(255, g)),
4058         'b' : Math.max(0, Math.min(255, b))
4059       };
4060
4061   // initialise the HSV and HSL components to null
4062   
4063
4064   /* 
4065    * //private returns the HSV or HSL hue component of this RGBColor. The hue is in the
4066    * range [0,360). The parameters are:
4067    *
4068    * maximum - the maximum of the RGB component values
4069    * range   - the range of the RGB component values
4070    */
4071    
4072
4073 }
4074 // this does an 'exteds'
4075 Roo.extend(Roo.lib.RGBColor, Roo.lib.Color, {
4076
4077   
4078     getHue  : function(maximum, range)
4079     {
4080       var rgb = this.rgb;
4081        
4082       // check whether the range is zero
4083       if (range == 0){
4084   
4085         // set the hue to zero (any hue is acceptable as the Color is grey)
4086         var hue = 0;
4087   
4088       }else{
4089   
4090         // determine which of the components has the highest value and set the hue
4091         switch (maximum){
4092   
4093           // red has the highest value
4094           case rgb.r:
4095             var hue = (rgb.g - rgb.b) / range * 60;
4096             if (hue < 0) { hue += 360; }
4097             break;
4098   
4099           // green has the highest value
4100           case rgb.g:
4101             var hue = (rgb.b - rgb.r) / range * 60 + 120;
4102             break;
4103   
4104           // blue has the highest value
4105           case rgb.b:
4106             var hue = (rgb.r - rgb.g) / range * 60 + 240;
4107             break;
4108   
4109         }
4110   
4111       }
4112   
4113       // return the hue
4114       return hue;
4115   
4116     },
4117
4118   /* //private Calculates and stores the HSV components of this RGBColor so that they can
4119    * be returned be the getHSV function.
4120    */
4121    calculateHSV : function(){
4122     var rgb = this.rgb;
4123     // get the maximum and range of the RGB component values
4124     var maximum = Math.max(rgb.r, rgb.g, rgb.b);
4125     var range   = maximum - Math.min(rgb.r, rgb.g, rgb.b);
4126
4127     // store the HSV components
4128     this.hsv =
4129         {
4130           'h' : this.getHue(maximum, range),
4131           's' : (maximum == 0 ? 0 : 100 * range / maximum),
4132           'v' : maximum / 2.55
4133         };
4134
4135   },
4136
4137   /* //private Calculates and stores the HSL components of this RGBColor so that they can
4138    * be returned be the getHSL function.
4139    */
4140    calculateHSL : function(){
4141     var rgb = this.rgb;
4142     // get the maximum and range of the RGB component values
4143     var maximum = Math.max(rgb.r, rgb.g, rgb.b);
4144     var range   = maximum - Math.min(rgb.r, rgb.g, rgb.b);
4145
4146     // determine the lightness in the range [0,1]
4147     var l = maximum / 255 - range / 510;
4148
4149     // store the HSL components
4150     this.hsl =
4151         {
4152           'h' : this.getHue(maximum, range),
4153           's' : (range == 0 ? 0 : range / 2.55 / (l < 0.5 ? l * 2 : 2 - l * 2)),
4154           'l' : 100 * l
4155         };
4156
4157   }
4158
4159 });
4160
4161 /**
4162  * @class Roo.lib.HSVColor
4163  * @extends Roo.lib.Color
4164  * Creates a Color specified in the HSV Color space, with an optional alpha
4165  * component. The parameters are:
4166  * @constructor
4167  *
4168  * @param {Number} h - the hue component, wrapped to the range [0,360)
4169  * @param {Number} s - the saturation component, clipped to the range [0,100]
4170  * @param {Number} v - the value component, clipped to the range [0,100]
4171  * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4172  *     optional and defaults to 1
4173  */
4174 Roo.lib.HSVColor = function (h, s, v, a){
4175
4176   // store the alpha component after clipping it if necessary
4177   this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4178
4179   // store the HSV components after clipping or wrapping them if necessary
4180   this.hsv =
4181       {
4182         'h' : (h % 360 + 360) % 360,
4183         's' : Math.max(0, Math.min(100, s)),
4184         'v' : Math.max(0, Math.min(100, v))
4185       };
4186
4187   // initialise the RGB and HSL components to null
4188   this.rgb = null;
4189   this.hsl = null;
4190 }
4191
4192 Roo.extend(Roo.lib.HSVColor, Roo.lib.Color, {
4193   /* Calculates and stores the RGB components of this HSVColor so that they can
4194    * be returned be the getRGB function.
4195    */
4196   calculateRGB: function ()
4197   {
4198     var hsv = this.hsv;
4199     // check whether the saturation is zero
4200     if (hsv.s == 0){
4201
4202       // set the Color to the appropriate shade of grey
4203       var r = hsv.v;
4204       var g = hsv.v;
4205       var b = hsv.v;
4206
4207     }else{
4208
4209       // set some temporary values
4210       var f  = hsv.h / 60 - Math.floor(hsv.h / 60);
4211       var p  = hsv.v * (1 - hsv.s / 100);
4212       var q  = hsv.v * (1 - hsv.s / 100 * f);
4213       var t  = hsv.v * (1 - hsv.s / 100 * (1 - f));
4214
4215       // set the RGB Color components to their temporary values
4216       switch (Math.floor(hsv.h / 60)){
4217         case 0: var r = hsv.v; var g = t; var b = p; break;
4218         case 1: var r = q; var g = hsv.v; var b = p; break;
4219         case 2: var r = p; var g = hsv.v; var b = t; break;
4220         case 3: var r = p; var g = q; var b = hsv.v; break;
4221         case 4: var r = t; var g = p; var b = hsv.v; break;
4222         case 5: var r = hsv.v; var g = p; var b = q; break;
4223       }
4224
4225     }
4226
4227     // store the RGB components
4228     this.rgb =
4229         {
4230           'r' : r * 2.55,
4231           'g' : g * 2.55,
4232           'b' : b * 2.55
4233         };
4234
4235   },
4236
4237   /* Calculates and stores the HSL components of this HSVColor so that they can
4238    * be returned be the getHSL function.
4239    */
4240   calculateHSL : function (){
4241
4242     var hsv = this.hsv;
4243     // determine the lightness in the range [0,100]
4244     var l = (2 - hsv.s / 100) * hsv.v / 2;
4245
4246     // store the HSL components
4247     this.hsl =
4248         {
4249           'h' : hsv.h,
4250           's' : hsv.s * hsv.v / (l < 50 ? l * 2 : 200 - l * 2),
4251           'l' : l
4252         };
4253
4254     // correct a division-by-zero error
4255     if (isNaN(hsl.s)) { hsl.s = 0; }
4256
4257   } 
4258  
4259
4260 });
4261  
4262
4263 /**
4264  * @class Roo.lib.HSLColor
4265  * @extends Roo.lib.Color
4266  *
4267  * @constructor
4268  * Creates a Color specified in the HSL Color space, with an optional alpha
4269  * component. The parameters are:
4270  *
4271  * @param {Number} h - the hue component, wrapped to the range [0,360)
4272  * @param {Number} s - the saturation component, clipped to the range [0,100]
4273  * @param {Number} l - the lightness component, clipped to the range [0,100]
4274  * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4275  *     optional and defaults to 1
4276  */
4277
4278 Roo.lib.HSLColor = function(h, s, l, a){
4279
4280   // store the alpha component after clipping it if necessary
4281   this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4282
4283   // store the HSL components after clipping or wrapping them if necessary
4284   this.hsl =
4285       {
4286         'h' : (h % 360 + 360) % 360,
4287         's' : Math.max(0, Math.min(100, s)),
4288         'l' : Math.max(0, Math.min(100, l))
4289       };
4290
4291   // initialise the RGB and HSV components to null
4292 }
4293
4294 Roo.extend(Roo.lib.HSLColor, Roo.lib.Color, {
4295
4296   /* Calculates and stores the RGB components of this HSLColor so that they can
4297    * be returned be the getRGB function.
4298    */
4299   calculateRGB: function (){
4300
4301     // check whether the saturation is zero
4302     if (this.hsl.s == 0){
4303
4304       // store the RGB components representing the appropriate shade of grey
4305       this.rgb =
4306           {
4307             'r' : this.hsl.l * 2.55,
4308             'g' : this.hsl.l * 2.55,
4309             'b' : this.hsl.l * 2.55
4310           };
4311
4312     }else{
4313
4314       // set some temporary values
4315       var p = this.hsl.l < 50
4316             ? this.hsl.l * (1 + hsl.s / 100)
4317             : this.hsl.l + hsl.s - hsl.l * hsl.s / 100;
4318       var q = 2 * hsl.l - p;
4319
4320       // initialise the RGB components
4321       this.rgb =
4322           {
4323             'r' : (h + 120) / 60 % 6,
4324             'g' : h / 60,
4325             'b' : (h + 240) / 60 % 6
4326           };
4327
4328       // loop over the RGB components
4329       for (var key in this.rgb){
4330
4331         // ensure that the property is not inherited from the root object
4332         if (this.rgb.hasOwnProperty(key)){
4333
4334           // set the component to its value in the range [0,100]
4335           if (this.rgb[key] < 1){
4336             this.rgb[key] = q + (p - q) * this.rgb[key];
4337           }else if (this.rgb[key] < 3){
4338             this.rgb[key] = p;
4339           }else if (this.rgb[key] < 4){
4340             this.rgb[key] = q + (p - q) * (4 - this.rgb[key]);
4341           }else{
4342             this.rgb[key] = q;
4343           }
4344
4345           // set the component to its value in the range [0,255]
4346           this.rgb[key] *= 2.55;
4347
4348         }
4349
4350       }
4351
4352     }
4353
4354   },
4355
4356   /* Calculates and stores the HSV components of this HSLColor so that they can
4357    * be returned be the getHSL function.
4358    */
4359    calculateHSV : function(){
4360
4361     // set a temporary value
4362     var t = this.hsl.s * (this.hsl.l < 50 ? this.hsl.l : 100 - this.hsl.l) / 100;
4363
4364     // store the HSV components
4365     this.hsv =
4366         {
4367           'h' : this.hsl.h,
4368           's' : 200 * t / (this.hsl.l + t),
4369           'v' : t + this.hsl.l
4370         };
4371
4372     // correct a division-by-zero error
4373     if (isNaN(this.hsv.s)) { this.hsv.s = 0; }
4374
4375   }
4376  
4377
4378 });
4379 /*
4380  * Portions of this file are based on pieces of Yahoo User Interface Library
4381  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4382  * YUI licensed under the BSD License:
4383  * http://developer.yahoo.net/yui/license.txt
4384  * <script type="text/javascript">
4385  *
4386  */
4387 (function() {
4388
4389     Roo.lib.ColorAnim = function(el, attributes, duration, method) {
4390         Roo.lib.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method);
4391     };
4392
4393     Roo.extend(Roo.lib.ColorAnim, Roo.lib.AnimBase);
4394
4395     var fly = Roo.lib.AnimBase.fly;
4396     var Y = Roo.lib;
4397     var superclass = Y.ColorAnim.superclass;
4398     var proto = Y.ColorAnim.prototype;
4399
4400     proto.toString = function() {
4401         var el = this.getEl();
4402         var id = el.id || el.tagName;
4403         return ("ColorAnim " + id);
4404     };
4405
4406     proto.patterns.color = /color$/i;
4407     proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;
4408     proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;
4409     proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;
4410     proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/;
4411
4412
4413     proto.parseColor = function(s) {
4414         if (s.length == 3) {
4415             return s;
4416         }
4417
4418         var c = this.patterns.hex.exec(s);
4419         if (c && c.length == 4) {
4420             return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ];
4421         }
4422
4423         c = this.patterns.rgb.exec(s);
4424         if (c && c.length == 4) {
4425             return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ];
4426         }
4427
4428         c = this.patterns.hex3.exec(s);
4429         if (c && c.length == 4) {
4430             return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ];
4431         }
4432
4433         return null;
4434     };
4435     // since this uses fly! - it cant be in ColorAnim (which does not have fly yet..)
4436     proto.getAttribute = function(attr) {
4437         var el = this.getEl();
4438         if (this.patterns.color.test(attr)) {
4439             var val = fly(el).getStyle(attr);
4440
4441             if (this.patterns.transparent.test(val)) {
4442                 var parent = el.parentNode;
4443                 val = fly(parent).getStyle(attr);
4444
4445                 while (parent && this.patterns.transparent.test(val)) {
4446                     parent = parent.parentNode;
4447                     val = fly(parent).getStyle(attr);
4448                     if (parent.tagName.toUpperCase() == 'HTML') {
4449                         val = '#fff';
4450                     }
4451                 }
4452             }
4453         } else {
4454             val = superclass.getAttribute.call(this, attr);
4455         }
4456
4457         return val;
4458     };
4459     proto.getAttribute = function(attr) {
4460         var el = this.getEl();
4461         if (this.patterns.color.test(attr)) {
4462             var val = fly(el).getStyle(attr);
4463
4464             if (this.patterns.transparent.test(val)) {
4465                 var parent = el.parentNode;
4466                 val = fly(parent).getStyle(attr);
4467
4468                 while (parent && this.patterns.transparent.test(val)) {
4469                     parent = parent.parentNode;
4470                     val = fly(parent).getStyle(attr);
4471                     if (parent.tagName.toUpperCase() == 'HTML') {
4472                         val = '#fff';
4473                     }
4474                 }
4475             }
4476         } else {
4477             val = superclass.getAttribute.call(this, attr);
4478         }
4479
4480         return val;
4481     };
4482
4483     proto.doMethod = function(attr, start, end) {
4484         var val;
4485
4486         if (this.patterns.color.test(attr)) {
4487             val = [];
4488             for (var i = 0, len = start.length; i < len; ++i) {
4489                 val[i] = superclass.doMethod.call(this, attr, start[i], end[i]);
4490             }
4491
4492             val = 'rgb(' + Math.floor(val[0]) + ',' + Math.floor(val[1]) + ',' + Math.floor(val[2]) + ')';
4493         }
4494         else {
4495             val = superclass.doMethod.call(this, attr, start, end);
4496         }
4497
4498         return val;
4499     };
4500
4501     proto.setRuntimeAttribute = function(attr) {
4502         superclass.setRuntimeAttribute.call(this, attr);
4503
4504         if (this.patterns.color.test(attr)) {
4505             var attributes = this.attributes;
4506             var start = this.parseColor(this.runtimeAttributes[attr].start);
4507             var end = this.parseColor(this.runtimeAttributes[attr].end);
4508
4509             if (typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined') {
4510                 end = this.parseColor(attributes[attr].by);
4511
4512                 for (var i = 0, len = start.length; i < len; ++i) {
4513                     end[i] = start[i] + end[i];
4514                 }
4515             }
4516
4517             this.runtimeAttributes[attr].start = start;
4518             this.runtimeAttributes[attr].end = end;
4519         }
4520     };
4521 })();
4522
4523 /*
4524  * Portions of this file are based on pieces of Yahoo User Interface Library
4525  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4526  * YUI licensed under the BSD License:
4527  * http://developer.yahoo.net/yui/license.txt
4528  * <script type="text/javascript">
4529  *
4530  */
4531 Roo.lib.Easing = {
4532
4533
4534     easeNone: function (t, b, c, d) {
4535         return c * t / d + b;
4536     },
4537
4538
4539     easeIn: function (t, b, c, d) {
4540         return c * (t /= d) * t + b;
4541     },
4542
4543
4544     easeOut: function (t, b, c, d) {
4545         return -c * (t /= d) * (t - 2) + b;
4546     },
4547
4548
4549     easeBoth: function (t, b, c, d) {
4550         if ((t /= d / 2) < 1) {
4551             return c / 2 * t * t + b;
4552         }
4553
4554         return -c / 2 * ((--t) * (t - 2) - 1) + b;
4555     },
4556
4557
4558     easeInStrong: function (t, b, c, d) {
4559         return c * (t /= d) * t * t * t + b;
4560     },
4561
4562
4563     easeOutStrong: function (t, b, c, d) {
4564         return -c * ((t = t / d - 1) * t * t * t - 1) + b;
4565     },
4566
4567
4568     easeBothStrong: function (t, b, c, d) {
4569         if ((t /= d / 2) < 1) {
4570             return c / 2 * t * t * t * t + b;
4571         }
4572
4573         return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
4574     },
4575
4576
4577
4578     elasticIn: function (t, b, c, d, a, p) {
4579         if (t == 0) {
4580             return b;
4581         }
4582         if ((t /= d) == 1) {
4583             return b + c;
4584         }
4585         if (!p) {
4586             p = d * .3;
4587         }
4588
4589         if (!a || a < Math.abs(c)) {
4590             a = c;
4591             var s = p / 4;
4592         }
4593         else {
4594             var s = p / (2 * Math.PI) * Math.asin(c / a);
4595         }
4596
4597         return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
4598     },
4599
4600
4601     elasticOut: function (t, b, c, d, a, p) {
4602         if (t == 0) {
4603             return b;
4604         }
4605         if ((t /= d) == 1) {
4606             return b + c;
4607         }
4608         if (!p) {
4609             p = d * .3;
4610         }
4611
4612         if (!a || a < Math.abs(c)) {
4613             a = c;
4614             var s = p / 4;
4615         }
4616         else {
4617             var s = p / (2 * Math.PI) * Math.asin(c / a);
4618         }
4619
4620         return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
4621     },
4622
4623
4624     elasticBoth: function (t, b, c, d, a, p) {
4625         if (t == 0) {
4626             return b;
4627         }
4628
4629         if ((t /= d / 2) == 2) {
4630             return b + c;
4631         }
4632
4633         if (!p) {
4634             p = d * (.3 * 1.5);
4635         }
4636
4637         if (!a || a < Math.abs(c)) {
4638             a = c;
4639             var s = p / 4;
4640         }
4641         else {
4642             var s = p / (2 * Math.PI) * Math.asin(c / a);
4643         }
4644
4645         if (t < 1) {
4646             return -.5 * (a * Math.pow(2, 10 * (t -= 1)) *
4647                           Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
4648         }
4649         return a * Math.pow(2, -10 * (t -= 1)) *
4650                Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
4651     },
4652
4653
4654
4655     backIn: function (t, b, c, d, s) {
4656         if (typeof s == 'undefined') {
4657             s = 1.70158;
4658         }
4659         return c * (t /= d) * t * ((s + 1) * t - s) + b;
4660     },
4661
4662
4663     backOut: function (t, b, c, d, s) {
4664         if (typeof s == 'undefined') {
4665             s = 1.70158;
4666         }
4667         return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
4668     },
4669
4670
4671     backBoth: function (t, b, c, d, s) {
4672         if (typeof s == 'undefined') {
4673             s = 1.70158;
4674         }
4675
4676         if ((t /= d / 2 ) < 1) {
4677             return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
4678         }
4679         return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
4680     },
4681
4682
4683     bounceIn: function (t, b, c, d) {
4684         return c - Roo.lib.Easing.bounceOut(d - t, 0, c, d) + b;
4685     },
4686
4687
4688     bounceOut: function (t, b, c, d) {
4689         if ((t /= d) < (1 / 2.75)) {
4690             return c * (7.5625 * t * t) + b;
4691         } else if (t < (2 / 2.75)) {
4692             return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
4693         } else if (t < (2.5 / 2.75)) {
4694             return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
4695         }
4696         return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
4697     },
4698
4699
4700     bounceBoth: function (t, b, c, d) {
4701         if (t < d / 2) {
4702             return Roo.lib.Easing.bounceIn(t * 2, 0, c, d) * .5 + b;
4703         }
4704         return Roo.lib.Easing.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
4705     }
4706 };/*
4707  * Portions of this file are based on pieces of Yahoo User Interface Library
4708  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4709  * YUI licensed under the BSD License:
4710  * http://developer.yahoo.net/yui/license.txt
4711  * <script type="text/javascript">
4712  *
4713  */
4714     (function() {
4715         Roo.lib.Motion = function(el, attributes, duration, method) {
4716             if (el) {
4717                 Roo.lib.Motion.superclass.constructor.call(this, el, attributes, duration, method);
4718             }
4719         };
4720
4721         Roo.extend(Roo.lib.Motion, Roo.lib.ColorAnim);
4722
4723
4724         var Y = Roo.lib;
4725         var superclass = Y.Motion.superclass;
4726         var proto = Y.Motion.prototype;
4727
4728         proto.toString = function() {
4729             var el = this.getEl();
4730             var id = el.id || el.tagName;
4731             return ("Motion " + id);
4732         };
4733
4734         proto.patterns.points = /^points$/i;
4735
4736         proto.setAttribute = function(attr, val, unit) {
4737             if (this.patterns.points.test(attr)) {
4738                 unit = unit || 'px';
4739                 superclass.setAttribute.call(this, 'left', val[0], unit);
4740                 superclass.setAttribute.call(this, 'top', val[1], unit);
4741             } else {
4742                 superclass.setAttribute.call(this, attr, val, unit);
4743             }
4744         };
4745
4746         proto.getAttribute = function(attr) {
4747             if (this.patterns.points.test(attr)) {
4748                 var val = [
4749                         superclass.getAttribute.call(this, 'left'),
4750                         superclass.getAttribute.call(this, 'top')
4751                         ];
4752             } else {
4753                 val = superclass.getAttribute.call(this, attr);
4754             }
4755
4756             return val;
4757         };
4758
4759         proto.doMethod = function(attr, start, end) {
4760             var val = null;
4761
4762             if (this.patterns.points.test(attr)) {
4763                 var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100;
4764                 val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t);
4765             } else {
4766                 val = superclass.doMethod.call(this, attr, start, end);
4767             }
4768             return val;
4769         };
4770
4771         proto.setRuntimeAttribute = function(attr) {
4772             if (this.patterns.points.test(attr)) {
4773                 var el = this.getEl();
4774                 var attributes = this.attributes;
4775                 var start;
4776                 var control = attributes['points']['control'] || [];
4777                 var end;
4778                 var i, len;
4779
4780                 if (control.length > 0 && !(control[0] instanceof Array)) {
4781                     control = [control];
4782                 } else {
4783                     var tmp = [];
4784                     for (i = 0,len = control.length; i < len; ++i) {
4785                         tmp[i] = control[i];
4786                     }
4787                     control = tmp;
4788                 }
4789
4790                 Roo.fly(el).position();
4791
4792                 if (isset(attributes['points']['from'])) {
4793                     Roo.lib.Dom.setXY(el, attributes['points']['from']);
4794                 }
4795                 else {
4796                     Roo.lib.Dom.setXY(el, Roo.lib.Dom.getXY(el));
4797                 }
4798
4799                 start = this.getAttribute('points');
4800
4801
4802                 if (isset(attributes['points']['to'])) {
4803                     end = translateValues.call(this, attributes['points']['to'], start);
4804
4805                     var pageXY = Roo.lib.Dom.getXY(this.getEl());
4806                     for (i = 0,len = control.length; i < len; ++i) {
4807                         control[i] = translateValues.call(this, control[i], start);
4808                     }
4809
4810
4811                 } else if (isset(attributes['points']['by'])) {
4812                     end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ];
4813
4814                     for (i = 0,len = control.length; i < len; ++i) {
4815                         control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ];
4816                     }
4817                 }
4818
4819                 this.runtimeAttributes[attr] = [start];
4820
4821                 if (control.length > 0) {
4822                     this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control);
4823                 }
4824
4825                 this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end;
4826             }
4827             else {
4828                 superclass.setRuntimeAttribute.call(this, attr);
4829             }
4830         };
4831
4832         var translateValues = function(val, start) {
4833             var pageXY = Roo.lib.Dom.getXY(this.getEl());
4834             val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ];
4835
4836             return val;
4837         };
4838
4839         var isset = function(prop) {
4840             return (typeof prop !== 'undefined');
4841         };
4842     })();
4843 /*
4844  * Portions of this file are based on pieces of Yahoo User Interface Library
4845  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4846  * YUI licensed under the BSD License:
4847  * http://developer.yahoo.net/yui/license.txt
4848  * <script type="text/javascript">
4849  *
4850  */
4851     (function() {
4852         Roo.lib.Scroll = function(el, attributes, duration, method) {
4853             if (el) {
4854                 Roo.lib.Scroll.superclass.constructor.call(this, el, attributes, duration, method);
4855             }
4856         };
4857
4858         Roo.extend(Roo.lib.Scroll, Roo.lib.ColorAnim);
4859
4860
4861         var Y = Roo.lib;
4862         var superclass = Y.Scroll.superclass;
4863         var proto = Y.Scroll.prototype;
4864
4865         proto.toString = function() {
4866             var el = this.getEl();
4867             var id = el.id || el.tagName;
4868             return ("Scroll " + id);
4869         };
4870
4871         proto.doMethod = function(attr, start, end) {
4872             var val = null;
4873
4874             if (attr == 'scroll') {
4875                 val = [
4876                         this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames),
4877                         this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames)
4878                         ];
4879
4880             } else {
4881                 val = superclass.doMethod.call(this, attr, start, end);
4882             }
4883             return val;
4884         };
4885
4886         proto.getAttribute = function(attr) {
4887             var val = null;
4888             var el = this.getEl();
4889
4890             if (attr == 'scroll') {
4891                 val = [ el.scrollLeft, el.scrollTop ];
4892             } else {
4893                 val = superclass.getAttribute.call(this, attr);
4894             }
4895
4896             return val;
4897         };
4898
4899         proto.setAttribute = function(attr, val, unit) {
4900             var el = this.getEl();
4901
4902             if (attr == 'scroll') {
4903                 el.scrollLeft = val[0];
4904                 el.scrollTop = val[1];
4905             } else {
4906                 superclass.setAttribute.call(this, attr, val, unit);
4907             }
4908         };
4909     })();
4910 /**
4911  * Originally based of this code... - refactored for Roo...
4912  * https://github.com/aaalsaleh/undo-manager
4913  
4914  * undo-manager.js
4915  * @author  Abdulrahman Alsaleh 
4916  * @copyright 2015 Abdulrahman Alsaleh 
4917  * @license  MIT License (c) 
4918  *
4919  * Hackily modifyed by alan@roojs.com
4920  *
4921  *
4922  *  
4923  *
4924  *  TOTALLY UNTESTED...
4925  *
4926  *  Documentation to be done....
4927  */
4928  
4929
4930 /**
4931 * @class Roo.lib.UndoManager
4932 * An undo manager implementation in JavaScript. It follows the W3C UndoManager and DOM Transaction
4933 * Draft and the undocumented and disabled Mozilla Firefox's UndoManager implementation.
4934
4935  * Usage:
4936  * <pre><code>
4937
4938
4939 editor.undoManager = new Roo.lib.UndoManager(1000, editor);
4940  
4941 </code></pre>
4942
4943 * For more information see this blog post with examples:
4944 *  <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
4945      - Create Elements using DOM, HTML fragments and Templates</a>. 
4946 * @constructor
4947 * @param {Number} limit how far back to go ... use 1000?
4948 * @param {Object} scope usually use document..
4949 */
4950
4951 Roo.lib.UndoManager = function (limit, undoScopeHost)
4952 {
4953     this.stack = [];
4954     this.limit = limit;
4955     this.scope = undoScopeHost;
4956     this.fireEvent = typeof CustomEvent != 'undefined' && undoScopeHost && undoScopeHost.dispatchEvent;
4957     if (this.fireEvent) {
4958         this.bindEvents();
4959     }
4960     this.reset();
4961     
4962 };
4963         
4964 Roo.lib.UndoManager.prototype = {
4965     
4966     limit : false,
4967     stack : false,
4968     scope :  false,
4969     fireEvent : false,
4970     position : 0,
4971     length : 0,
4972     
4973     
4974      /**
4975      * To push and execute a transaction, the method undoManager.transact
4976      * must be called by passing a transaction object as the first argument, and a merge
4977      * flag as the second argument. A transaction object has the following properties:
4978      *
4979      * Usage:
4980 <pre><code>
4981 undoManager.transact({
4982     label: 'Typing',
4983     execute: function() { ... },
4984     undo: function() { ... },
4985     // redo same as execute
4986     redo: function() { this.execute(); }
4987 }, false);
4988
4989 // merge transaction
4990 undoManager.transact({
4991     label: 'Typing',
4992     execute: function() { ... },  // this will be run...
4993     undo: function() { ... }, // what to do when undo is run.
4994     // redo same as execute
4995     redo: function() { this.execute(); }
4996 }, true); 
4997 </code></pre> 
4998      *
4999      * 
5000      * @param {Object} transaction The transaction to add to the stack.
5001      * @return {String} The HTML fragment
5002      */
5003     
5004     
5005     transact : function (transaction, merge)
5006     {
5007         if (arguments.length < 2) {
5008             throw new TypeError('Not enough arguments to UndoManager.transact.');
5009         }
5010
5011         transaction.execute();
5012
5013         this.stack.splice(0, this.position);
5014         if (merge && this.length) {
5015             this.stack[0].push(transaction);
5016         } else {
5017             this.stack.unshift([transaction]);
5018         }
5019     
5020         this.position = 0;
5021
5022         if (this.limit && this.stack.length > this.limit) {
5023             this.length = this.stack.length = this.limit;
5024         } else {
5025             this.length = this.stack.length;
5026         }
5027
5028         if (this.fireEvent) {
5029             this.scope.dispatchEvent(
5030                 new CustomEvent('DOMTransaction', {
5031                     detail: {
5032                         transactions: this.stack[0].slice()
5033                     },
5034                     bubbles: true,
5035                     cancelable: false
5036                 })
5037             );
5038         }
5039         
5040         //Roo.log("transaction: pos:" + this.position + " len: " + this.length + " slen:" + this.stack.length);
5041       
5042         
5043     },
5044
5045     undo : function ()
5046     {
5047         //Roo.log("undo: pos:" + this.position + " len: " + this.length + " slen:" + this.stack.length);
5048         
5049         if (this.position < this.length) {
5050             for (var i = this.stack[this.position].length - 1; i >= 0; i--) {
5051                 this.stack[this.position][i].undo();
5052             }
5053             this.position++;
5054
5055             if (this.fireEvent) {
5056                 this.scope.dispatchEvent(
5057                     new CustomEvent('undo', {
5058                         detail: {
5059                             transactions: this.stack[this.position - 1].slice()
5060                         },
5061                         bubbles: true,
5062                         cancelable: false
5063                     })
5064                 );
5065             }
5066         }
5067     },
5068
5069     redo : function ()
5070     {
5071         if (this.position > 0) {
5072             for (var i = 0, n = this.stack[this.position - 1].length; i < n; i++) {
5073                 this.stack[this.position - 1][i].redo();
5074             }
5075             this.position--;
5076
5077             if (this.fireEvent) {
5078                 this.scope.dispatchEvent(
5079                     new CustomEvent('redo', {
5080                         detail: {
5081                             transactions: this.stack[this.position].slice()
5082                         },
5083                         bubbles: true,
5084                         cancelable: false
5085                     })
5086                 );
5087             }
5088         }
5089     },
5090
5091     item : function (index)
5092     {
5093         if (index >= 0 && index < this.length) {
5094             return this.stack[index].slice();
5095         }
5096         return null;
5097     },
5098
5099     clearUndo : function () {
5100         this.stack.length = this.length = this.position;
5101     },
5102
5103     clearRedo : function () {
5104         this.stack.splice(0, this.position);
5105         this.position = 0;
5106         this.length = this.stack.length;
5107     },
5108     /**
5109      * Reset the undo - probaly done on load to clear all history.
5110      */
5111     reset : function()
5112     {
5113         this.stack = [];
5114         this.position = 0;
5115         this.length = 0;
5116         this.current_html = this.scope.innerHTML;
5117         if (this.timer !== false) {
5118             clearTimeout(this.timer);
5119         }
5120         this.timer = false;
5121         this.merge = false;
5122         this.addEvent();
5123         
5124     },
5125     current_html : '',
5126     timer : false,
5127     merge : false,
5128     
5129     
5130     // this will handle the undo/redo on the element.?
5131     bindEvents : function()
5132     {
5133         var el  = this.scope;
5134         el.undoManager = this;
5135         
5136         
5137         this.scope.addEventListener('keydown', function(e) {
5138             if ((e.ctrlKey || e.metaKey) && e.keyCode === 90) {
5139                 if (e.shiftKey) {
5140                     el.undoManager.redo(); // Ctrl/Command + Shift + Z
5141                 } else {
5142                     el.undoManager.undo(); // Ctrl/Command + Z
5143                 }
5144         
5145                 e.preventDefault();
5146             }
5147         });
5148         /// ignore keyup..
5149         this.scope.addEventListener('keyup', function(e) {
5150             if ((e.ctrlKey || e.metaKey) && e.keyCode === 90) {
5151                 e.preventDefault();
5152             }
5153         });
5154         
5155         
5156         
5157         var t = this;
5158         
5159         el.addEventListener('input', function(e) {
5160             if(el.innerHTML == t.current_html) {
5161                 return;
5162             }
5163             // only record events every second.
5164             if (t.timer !== false) {
5165                clearTimeout(t.timer);
5166                t.timer = false;
5167             }
5168             t.timer = setTimeout(function() { t.merge = false; }, 1000);
5169             
5170             t.addEvent(t.merge);
5171             t.merge = true; // ignore changes happening every second..
5172         });
5173         },
5174     /**
5175      * Manually add an event.
5176      * Normall called without arguements - and it will just get added to the stack.
5177      * 
5178      */
5179     
5180     addEvent : function(merge)
5181     {
5182         //Roo.log("undomanager +" + (merge ? 'Y':'n'));
5183         // not sure if this should clear the timer 
5184         merge = typeof(merge) == 'undefined' ? false : merge; 
5185         
5186         this.scope.undoManager.transact({
5187             scope : this.scope,
5188             oldHTML: this.current_html,
5189             newHTML: this.scope.innerHTML,
5190             // nothing to execute (content already changed when input is fired)
5191             execute: function() { },
5192             undo: function() {
5193                 this.scope.innerHTML = this.current_html = this.oldHTML;
5194             },
5195             redo: function() {
5196                 this.scope.innerHTML = this.current_html = this.newHTML;
5197             }
5198         }, false); //merge);
5199         
5200         this.merge = merge;
5201         
5202         this.current_html = this.scope.innerHTML;
5203     }
5204     
5205     
5206      
5207     
5208     
5209     
5210 };
5211 /**
5212  * @class Roo.lib.Range
5213  * @constructor
5214  * This is a toolkit, normally used to copy features into a Dom Range element
5215  * Roo.lib.Range.wrap(x);
5216  *
5217  *
5218  *
5219  */
5220 Roo.lib.Range = function() { };
5221
5222 /**
5223  * Wrap a Dom Range object, to give it new features...
5224  * @static
5225  * @param {Range} the range to wrap
5226  */
5227 Roo.lib.Range.wrap = function(r) {
5228     return Roo.apply(r, Roo.lib.Range.prototype);
5229 };
5230 /**
5231  * find a parent node eg. LI / OL
5232  * @param {string|Array} node name or array of nodenames
5233  * @return {DomElement|false}
5234  */
5235 Roo.apply(Roo.lib.Range.prototype,
5236 {
5237     
5238     closest : function(str)
5239     {
5240         if (typeof(str) != 'string') {
5241             // assume it's a array.
5242             for(var i = 0;i < str.length;i++) {
5243                 var r = this.closest(str[i]);
5244                 if (r !== false) {
5245                     return r;
5246                 }
5247                 
5248             }
5249             return false;
5250         }
5251         str = str.toLowerCase();
5252         var n = this.commonAncestorContainer; // might not be a node
5253         while (n.nodeType != 1) {
5254             n = n.parentNode;
5255         }
5256         
5257         if (n.nodeName.toLowerCase() == str ) {
5258             return n;
5259         }
5260         if (n.nodeName.toLowerCase() == 'body') {
5261             return false;
5262         }
5263             
5264         return n.closest(str) || false;
5265         
5266     },
5267     cloneRange : function()
5268     {
5269         return Roo.lib.Range.wrap(Range.prototype.cloneRange.call(this));
5270     }
5271 });/**
5272  * @class Roo.lib.Selection
5273  * @constructor
5274  * This is a toolkit, normally used to copy features into a Dom Selection element
5275  * Roo.lib.Selection.wrap(x);
5276  *
5277  *
5278  *
5279  */
5280 Roo.lib.Selection = function() { };
5281
5282 /**
5283  * Wrap a Dom Range object, to give it new features...
5284  * @static
5285  * @param {Range} the range to wrap
5286  */
5287 Roo.lib.Selection.wrap = function(r, doc) {
5288     Roo.apply(r, Roo.lib.Selection.prototype);
5289     r.ownerDocument = doc; // usefull so we dont have to keep referening to it.
5290     return r;
5291 };
5292 /**
5293  * find a parent node eg. LI / OL
5294  * @param {string|Array} node name or array of nodenames
5295  * @return {DomElement|false}
5296  */
5297 Roo.apply(Roo.lib.Selection.prototype,
5298 {
5299     /**
5300      * the owner document
5301      */
5302     ownerDocument : false,
5303     
5304     getRangeAt : function(n)
5305     {
5306         return Roo.lib.Range.wrap(Selection.prototype.getRangeAt.call(this,n));
5307     },
5308     
5309     /**
5310      * insert node at selection 
5311      * @param {DomElement|string} node
5312      * @param {string} cursor (after|in|none) where to place the cursor after inserting.
5313      */
5314     insertNode: function(node, cursor)
5315     {
5316         if (typeof(node) == 'string') {
5317             node = this.ownerDocument.createElement(node);
5318             if (cursor == 'in') {
5319                 node.innerHTML = '&nbsp;';
5320             }
5321         }
5322         
5323         var range = this.getRangeAt(0);
5324         
5325         if (this.type != 'Caret') {
5326             range.deleteContents();
5327         }
5328         var sn = node.childNodes[0]; // select the contents.
5329
5330         
5331         
5332         range.insertNode(node);
5333         if (cursor == 'after') {
5334             node.insertAdjacentHTML('afterend', '&nbsp;');
5335             sn = node.nextSibling;
5336         }
5337         
5338         if (cursor == 'none') {
5339             return;
5340         }
5341         
5342         this.cursorText(sn);
5343     },
5344     
5345     cursorText : function(n)
5346     {
5347        
5348         //var range = this.getRangeAt(0);
5349         range = Roo.lib.Range.wrap(new Range());
5350         //range.selectNode(n);
5351         
5352         var ix = Array.from(n.parentNode.childNodes).indexOf(n);
5353         range.setStart(n.parentNode,ix);
5354         range.setEnd(n.parentNode,ix+1);
5355         //range.collapse(false);
5356          
5357         this.removeAllRanges();
5358         this.addRange(range);
5359         
5360         Roo.log([n, range, this,this.baseOffset,this.extentOffset, this.type]);
5361     },
5362     cursorAfter : function(n)
5363     {
5364         if (!n.nextSibling || n.nextSibling.nodeValue != '&nbsp;') {
5365             n.insertAdjacentHTML('afterend', '&nbsp;');
5366         }
5367         this.cursorText (n.nextSibling);
5368     }
5369         
5370     
5371 });/*
5372  * Based on:
5373  * Ext JS Library 1.1.1
5374  * Copyright(c) 2006-2007, Ext JS, LLC.
5375  *
5376  * Originally Released Under LGPL - original licence link has changed is not relivant.
5377  *
5378  * Fork - LGPL
5379  * <script type="text/javascript">
5380  */
5381
5382
5383 // nasty IE9 hack - what a pile of crap that is..
5384
5385  if (typeof Range != "undefined" && typeof Range.prototype.createContextualFragment == "undefined") {
5386     Range.prototype.createContextualFragment = function (html) {
5387         var doc = window.document;
5388         var container = doc.createElement("div");
5389         container.innerHTML = html;
5390         var frag = doc.createDocumentFragment(), n;
5391         while ((n = container.firstChild)) {
5392             frag.appendChild(n);
5393         }
5394         return frag;
5395     };
5396 }
5397
5398 /**
5399  * @class Roo.DomHelper
5400  * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.
5401  * For more information see <a href="http://web.archive.org/web/20071221063734/http://www.jackslocum.com/blog/2006/10/06/domhelper-create-elements-using-dom-html-fragments-or-templates/">this blog post with examples</a>.
5402  * @static
5403  */
5404 Roo.DomHelper = function(){
5405     var tempTableEl = null;
5406     var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
5407     var tableRe = /^table|tbody|tr|td$/i;
5408     var xmlns = {};
5409     // build as innerHTML where available
5410     /** @ignore */
5411     var createHtml = function(o){
5412         if(typeof o == 'string'){
5413             return o;
5414         }
5415         var b = "";
5416         if(!o.tag){
5417             o.tag = "div";
5418         }
5419         b += "<" + o.tag;
5420         for(var attr in o){
5421             if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") { continue; }
5422             if(attr == "style"){
5423                 var s = o["style"];
5424                 if(typeof s == "function"){
5425                     s = s.call();
5426                 }
5427                 if(typeof s == "string"){
5428                     b += ' style="' + s + '"';
5429                 }else if(typeof s == "object"){
5430                     b += ' style="';
5431                     for(var key in s){
5432                         if(typeof s[key] != "function"){
5433                             b += key + ":" + s[key] + ";";
5434                         }
5435                     }
5436                     b += '"';
5437                 }
5438             }else{
5439                 if(attr == "cls"){
5440                     b += ' class="' + o["cls"] + '"';
5441                 }else if(attr == "htmlFor"){
5442                     b += ' for="' + o["htmlFor"] + '"';
5443                 }else{
5444                     b += " " + attr + '="' + o[attr] + '"';
5445                 }
5446             }
5447         }
5448         if(emptyTags.test(o.tag)){
5449             b += "/>";
5450         }else{
5451             b += ">";
5452             var cn = o.children || o.cn;
5453             if(cn){
5454                 //http://bugs.kde.org/show_bug.cgi?id=71506
5455                 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
5456                     for(var i = 0, len = cn.length; i < len; i++) {
5457                         b += createHtml(cn[i], b);
5458                     }
5459                 }else{
5460                     b += createHtml(cn, b);
5461                 }
5462             }
5463             if(o.html){
5464                 b += o.html;
5465             }
5466             b += "</" + o.tag + ">";
5467         }
5468         return b;
5469     };
5470
5471     // build as dom
5472     /** @ignore */
5473     var createDom = function(o, parentNode){
5474          
5475         // defininition craeted..
5476         var ns = false;
5477         if (o.ns && o.ns != 'html') {
5478                
5479             if (o.xmlns && typeof(xmlns[o.ns]) == 'undefined') {
5480                 xmlns[o.ns] = o.xmlns;
5481                 ns = o.xmlns;
5482             }
5483             if (typeof(xmlns[o.ns]) == 'undefined') {
5484                 console.log("Trying to create namespace element " + o.ns + ", however no xmlns was sent to builder previously");
5485             }
5486             ns = xmlns[o.ns];
5487         }
5488         
5489         
5490         if (typeof(o) == 'string') {
5491             return parentNode.appendChild(document.createTextNode(o));
5492         }
5493         o.tag = o.tag || div;
5494         if (o.ns && Roo.isIE) {
5495             ns = false;
5496             o.tag = o.ns + ':' + o.tag;
5497             
5498         }
5499         var el = ns ? document.createElementNS( ns, o.tag||'div') :  document.createElement(o.tag||'div');
5500         var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
5501         for(var attr in o){
5502             
5503             if(attr == "tag" || attr == "ns" ||attr == "xmlns" ||attr == "children" || attr == "cn" || attr == "html" || 
5504                     attr == "style" || typeof o[attr] == "function") { continue; }
5505                     
5506             if(attr=="cls" && Roo.isIE){
5507                 el.className = o["cls"];
5508             }else{
5509                 if(useSet) { el.setAttribute(attr=="cls" ? 'class' : attr, o[attr]);}
5510                 else { 
5511                     el[attr] = o[attr];
5512                 }
5513             }
5514         }
5515         Roo.DomHelper.applyStyles(el, o.style);
5516         var cn = o.children || o.cn;
5517         if(cn){
5518             //http://bugs.kde.org/show_bug.cgi?id=71506
5519              if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
5520                 for(var i = 0, len = cn.length; i < len; i++) {
5521                     createDom(cn[i], el);
5522                 }
5523             }else{
5524                 createDom(cn, el);
5525             }
5526         }
5527         if(o.html){
5528             el.innerHTML = o.html;
5529         }
5530         if(parentNode){
5531            parentNode.appendChild(el);
5532         }
5533         return el;
5534     };
5535
5536     var ieTable = function(depth, s, h, e){
5537         tempTableEl.innerHTML = [s, h, e].join('');
5538         var i = -1, el = tempTableEl;
5539         while(++i < depth && el.firstChild){
5540             el = el.firstChild;
5541         }
5542         return el;
5543     };
5544
5545     // kill repeat to save bytes
5546     var ts = '<table>',
5547         te = '</table>',
5548         tbs = ts+'<tbody>',
5549         tbe = '</tbody>'+te,
5550         trs = tbs + '<tr>',
5551         tre = '</tr>'+tbe;
5552
5553     /**
5554      * @ignore
5555      * Nasty code for IE's broken table implementation
5556      */
5557     var insertIntoTable = function(tag, where, el, html){
5558         if(!tempTableEl){
5559             tempTableEl = document.createElement('div');
5560         }
5561         var node;
5562         var before = null;
5563         if(tag == 'td'){
5564             if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
5565                 return;
5566             }
5567             if(where == 'beforebegin'){
5568                 before = el;
5569                 el = el.parentNode;
5570             } else{
5571                 before = el.nextSibling;
5572                 el = el.parentNode;
5573             }
5574             node = ieTable(4, trs, html, tre);
5575         }
5576         else if(tag == 'tr'){
5577             if(where == 'beforebegin'){
5578                 before = el;
5579                 el = el.parentNode;
5580                 node = ieTable(3, tbs, html, tbe);
5581             } else if(where == 'afterend'){
5582                 before = el.nextSibling;
5583                 el = el.parentNode;
5584                 node = ieTable(3, tbs, html, tbe);
5585             } else{ // INTO a TR
5586                 if(where == 'afterbegin'){
5587                     before = el.firstChild;
5588                 }
5589                 node = ieTable(4, trs, html, tre);
5590             }
5591         } else if(tag == 'tbody'){
5592             if(where == 'beforebegin'){
5593                 before = el;
5594                 el = el.parentNode;
5595                 node = ieTable(2, ts, html, te);
5596             } else if(where == 'afterend'){
5597                 before = el.nextSibling;
5598                 el = el.parentNode;
5599                 node = ieTable(2, ts, html, te);
5600             } else{
5601                 if(where == 'afterbegin'){
5602                     before = el.firstChild;
5603                 }
5604                 node = ieTable(3, tbs, html, tbe);
5605             }
5606         } else{ // TABLE
5607             if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
5608                 return;
5609             }
5610             if(where == 'afterbegin'){
5611                 before = el.firstChild;
5612             }
5613             node = ieTable(2, ts, html, te);
5614         }
5615         el.insertBefore(node, before);
5616         return node;
5617     };
5618     
5619     // this is a bit like the react update code...
5620     // 
5621     
5622     var updateNode = function(from, to)
5623     {
5624         // should we handle non-standard elements?
5625         Roo.log(["UpdateNode" , from, to]);
5626         if (from.nodeType != to.nodeType) {
5627             Roo.log(["ReplaceChild - mismatch notType" , to, from ]);
5628             from.parentNode.replaceChild(to, from);
5629         }
5630         
5631         if (from.nodeType == 3) {
5632             // assume it's text?!
5633             if (from.data == to.data) {
5634                 return;
5635             }
5636             from.data = to.data;
5637             return;
5638         }
5639         if (!from.parentNode) {
5640             // not sure why this is happening?
5641             return;
5642         }
5643         // assume 'to' doesnt have '1/3 nodetypes!
5644         // not sure why, by from, parent node might not exist?
5645         if (from.nodeType !=1 || from.tagName != to.tagName) {
5646             Roo.log(["ReplaceChild" , from, to ]);
5647             
5648             from.parentNode.replaceChild(to, from);
5649             return;
5650         }
5651         // compare attributes
5652         var ar = Array.from(from.attributes);
5653         for(var i = 0; i< ar.length;i++) {
5654             if (to.hasAttribute(ar[i].name)) {
5655                 continue;
5656             }
5657             if (ar[i].name == 'id') { // always keep ids?
5658                continue;
5659             }
5660             //if (ar[i].name == 'style') {
5661             //   throw "style removed?";
5662             //}
5663             Roo.log("removeAttribute" + ar[i].name);
5664             from.removeAttribute(ar[i].name);
5665         }
5666         ar = to.attributes;
5667         for(var i = 0; i< ar.length;i++) {
5668             if (from.getAttribute(ar[i].name) == to.getAttribute(ar[i].name)) {
5669                 Roo.log("skipAttribute " + ar[i].name  + '=' + to.getAttribute(ar[i].name));
5670                 continue;
5671             }
5672             Roo.log("updateAttribute " + ar[i].name + '=>' + to.getAttribute(ar[i].name));
5673             from.setAttribute(ar[i].name, to.getAttribute(ar[i].name));
5674         }
5675         // children
5676         var far = Array.from(from.childNodes);
5677         var tar = Array.from(to.childNodes);
5678         // if the lengths are different.. then it's probably a editable content change, rather than
5679         // a change of the block definition..
5680         
5681         // this did notwork , as our rebuilt nodes did not include ID's so did not match at all.
5682          /*if (from.innerHTML == to.innerHTML) {
5683             return;
5684         }
5685         if (far.length != tar.length) {
5686             from.innerHTML = to.innerHTML;
5687             return;
5688         }
5689         */
5690         
5691         for(var i = 0; i < Math.max(tar.length, far.length); i++) {
5692             if (i >= far.length) {
5693                 from.appendChild(tar[i]);
5694                 Roo.log(["add", tar[i]]);
5695                 
5696             } else if ( i  >= tar.length) {
5697                 from.removeChild(far[i]);
5698                 Roo.log(["remove", far[i]]);
5699             } else {
5700                 
5701                 updateNode(far[i], tar[i]);
5702             }    
5703         }
5704         
5705         
5706         
5707         
5708     };
5709     
5710     
5711
5712     return {
5713         /** True to force the use of DOM instead of html fragments @type Boolean */
5714         useDom : false,
5715     
5716         /**
5717          * Returns the markup for the passed Element(s) config
5718          * @param {Object} o The Dom object spec (and children)
5719          * @return {String}
5720          */
5721         markup : function(o){
5722             return createHtml(o);
5723         },
5724     
5725         /**
5726          * Applies a style specification to an element
5727          * @param {String/HTMLElement} el The element to apply styles to
5728          * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
5729          * a function which returns such a specification.
5730          */
5731         applyStyles : function(el, styles){
5732             if(styles){
5733                el = Roo.fly(el);
5734                if(typeof styles == "string"){
5735                    var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
5736                    var matches;
5737                    while ((matches = re.exec(styles)) != null){
5738                        el.setStyle(matches[1], matches[2]);
5739                    }
5740                }else if (typeof styles == "object"){
5741                    for (var style in styles){
5742                       el.setStyle(style, styles[style]);
5743                    }
5744                }else if (typeof styles == "function"){
5745                     Roo.DomHelper.applyStyles(el, styles.call());
5746                }
5747             }
5748         },
5749     
5750         /**
5751          * Inserts an HTML fragment into the Dom
5752          * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
5753          * @param {HTMLElement} el The context element
5754          * @param {String} html The HTML fragmenet
5755          * @return {HTMLElement} The new node
5756          */
5757         insertHtml : function(where, el, html){
5758             where = where.toLowerCase();
5759             if(el.insertAdjacentHTML){
5760                 if(tableRe.test(el.tagName)){
5761                     var rs;
5762                     if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
5763                         return rs;
5764                     }
5765                 }
5766                 switch(where){
5767                     case "beforebegin":
5768                         el.insertAdjacentHTML('BeforeBegin', html);
5769                         return el.previousSibling;
5770                     case "afterbegin":
5771                         el.insertAdjacentHTML('AfterBegin', html);
5772                         return el.firstChild;
5773                     case "beforeend":
5774                         el.insertAdjacentHTML('BeforeEnd', html);
5775                         return el.lastChild;
5776                     case "afterend":
5777                         el.insertAdjacentHTML('AfterEnd', html);
5778                         return el.nextSibling;
5779                 }
5780                 throw 'Illegal insertion point -> "' + where + '"';
5781             }
5782             var range = el.ownerDocument.createRange();
5783             var frag;
5784             switch(where){
5785                  case "beforebegin":
5786                     range.setStartBefore(el);
5787                     frag = range.createContextualFragment(html);
5788                     el.parentNode.insertBefore(frag, el);
5789                     return el.previousSibling;
5790                  case "afterbegin":
5791                     if(el.firstChild){
5792                         range.setStartBefore(el.firstChild);
5793                         frag = range.createContextualFragment(html);
5794                         el.insertBefore(frag, el.firstChild);
5795                         return el.firstChild;
5796                     }else{
5797                         el.innerHTML = html;
5798                         return el.firstChild;
5799                     }
5800                 case "beforeend":
5801                     if(el.lastChild){
5802                         range.setStartAfter(el.lastChild);
5803                         frag = range.createContextualFragment(html);
5804                         el.appendChild(frag);
5805                         return el.lastChild;
5806                     }else{
5807                         el.innerHTML = html;
5808                         return el.lastChild;
5809                     }
5810                 case "afterend":
5811                     range.setStartAfter(el);
5812                     frag = range.createContextualFragment(html);
5813                     el.parentNode.insertBefore(frag, el.nextSibling);
5814                     return el.nextSibling;
5815                 }
5816                 throw 'Illegal insertion point -> "' + where + '"';
5817         },
5818     
5819         /**
5820          * Creates new Dom element(s) and inserts them before el
5821          * @param {String/HTMLElement/Element} el The context element
5822          * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5823          * @param {Boolean} returnElement (optional) true to return a Roo.Element
5824          * @return {HTMLElement/Roo.Element} The new node
5825          */
5826         insertBefore : function(el, o, returnElement){
5827             return this.doInsert(el, o, returnElement, "beforeBegin");
5828         },
5829     
5830         /**
5831          * Creates new Dom element(s) and inserts them after el
5832          * @param {String/HTMLElement/Element} el The context element
5833          * @param {Object} o The Dom object spec (and children)
5834          * @param {Boolean} returnElement (optional) true to return a Roo.Element
5835          * @return {HTMLElement/Roo.Element} The new node
5836          */
5837         insertAfter : function(el, o, returnElement){
5838             return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
5839         },
5840     
5841         /**
5842          * Creates new Dom element(s) and inserts them as the first child of el
5843          * @param {String/HTMLElement/Element} el The context element
5844          * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5845          * @param {Boolean} returnElement (optional) true to return a Roo.Element
5846          * @return {HTMLElement/Roo.Element} The new node
5847          */
5848         insertFirst : function(el, o, returnElement){
5849             return this.doInsert(el, o, returnElement, "afterBegin");
5850         },
5851     
5852         // private
5853         doInsert : function(el, o, returnElement, pos, sibling){
5854             el = Roo.getDom(el);
5855             var newNode;
5856             if(this.useDom || o.ns){
5857                 newNode = createDom(o, null);
5858                 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
5859             }else{
5860                 var html = createHtml(o);
5861                 newNode = this.insertHtml(pos, el, html);
5862             }
5863             return returnElement ? Roo.get(newNode, true) : newNode;
5864         },
5865     
5866         /**
5867          * Creates new Dom element(s) and appends them to el
5868          * @param {String/HTMLElement/Element} el The context element
5869          * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5870          * @param {Boolean} returnElement (optional) true to return a Roo.Element
5871          * @return {HTMLElement/Roo.Element} The new node
5872          */
5873         append : function(el, o, returnElement){
5874             el = Roo.getDom(el);
5875             var newNode;
5876             if(this.useDom || o.ns){
5877                 newNode = createDom(o, null);
5878                 el.appendChild(newNode);
5879             }else{
5880                 var html = createHtml(o);
5881                 newNode = this.insertHtml("beforeEnd", el, html);
5882             }
5883             return returnElement ? Roo.get(newNode, true) : newNode;
5884         },
5885     
5886         /**
5887          * Creates new Dom element(s) and overwrites the contents of el with them
5888          * @param {String/HTMLElement/Element} el The context element
5889          * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5890          * @param {Boolean} returnElement (optional) true to return a Roo.Element
5891          * @return {HTMLElement/Roo.Element} The new node
5892          */
5893         overwrite : function(el, o, returnElement)
5894         {
5895             el = Roo.getDom(el);
5896             if (o.ns) {
5897               
5898                 while (el.childNodes.length) {
5899                     el.removeChild(el.firstChild);
5900                 }
5901                 createDom(o, el);
5902             } else {
5903                 el.innerHTML = createHtml(o);   
5904             }
5905             
5906             return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
5907         },
5908     
5909         /**
5910          * Creates a new Roo.DomHelper.Template from the Dom object spec
5911          * @param {Object} o The Dom object spec (and children)
5912          * @return {Roo.DomHelper.Template} The new template
5913          */
5914         createTemplate : function(o){
5915             var html = createHtml(o);
5916             return new Roo.Template(html);
5917         },
5918          /**
5919          * Updates the first element with the spec from the o (replacing if necessary)
5920          * This iterates through the children, and updates attributes / children etc..
5921          * @param {String/HTMLElement/Element} el The context element
5922          * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5923          */
5924         
5925         update : function(el, o)
5926         {
5927             updateNode(Roo.getDom(el), createDom(o));
5928             
5929         }
5930         
5931         
5932     };
5933 }();
5934 /*
5935  * Based on:
5936  * Ext JS Library 1.1.1
5937  * Copyright(c) 2006-2007, Ext JS, LLC.
5938  *
5939  * Originally Released Under LGPL - original licence link has changed is not relivant.
5940  *
5941  * Fork - LGPL
5942  * <script type="text/javascript">
5943  */
5944  
5945 /**
5946 * @class Roo.Template
5947 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
5948 * For a list of available format functions, see {@link Roo.util.Format}.<br />
5949 * Usage:
5950 <pre><code>
5951 var t = new Roo.Template({
5952     html :  '&lt;div name="{id}"&gt;' + 
5953         '&lt;span class="{cls}"&gt;{name:trim} {someval:this.myformat}{value:ellipsis(10)}&lt;/span&gt;' +
5954         '&lt;/div&gt;',
5955     myformat: function (value, allValues) {
5956         return 'XX' + value;
5957     }
5958 });
5959 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
5960 </code></pre>
5961 * For more information see this blog post with examples:
5962 *  <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
5963      - Create Elements using DOM, HTML fragments and Templates</a>. 
5964 * @constructor
5965 * @param {Object} cfg - Configuration object.
5966 */
5967 Roo.Template = function(cfg){
5968     // BC!
5969     if(cfg instanceof Array){
5970         cfg = cfg.join("");
5971     }else if(arguments.length > 1){
5972         cfg = Array.prototype.join.call(arguments, "");
5973     }
5974     
5975     
5976     if (typeof(cfg) == 'object') {
5977         Roo.apply(this,cfg)
5978     } else {
5979         // bc
5980         this.html = cfg;
5981     }
5982     if (this.url) {
5983         this.load();
5984     }
5985     
5986 };
5987 Roo.Template.prototype = {
5988     
5989     /**
5990      * @cfg {Function} onLoad Called after the template has been loaded and complied (usually from a remove source)
5991      */
5992     onLoad : false,
5993     
5994     
5995     /**
5996      * @cfg {String} url  The Url to load the template from. beware if you are loading from a url, the data may not be ready if you use it instantly..
5997      *                    it should be fixed so that template is observable...
5998      */
5999     url : false,
6000     /**
6001      * @cfg {String} html  The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
6002      */
6003     html : '',
6004     
6005     
6006     compiled : false,
6007     loaded : false,
6008     /**
6009      * Returns an HTML fragment of this template with the specified values applied.
6010      * @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'})
6011      * @return {String} The HTML fragment
6012      */
6013     
6014    
6015     
6016     applyTemplate : function(values){
6017         //Roo.log(["applyTemplate", values]);
6018         try {
6019            
6020             if(this.compiled){
6021                 return this.compiled(values);
6022             }
6023             var useF = this.disableFormats !== true;
6024             var fm = Roo.util.Format, tpl = this;
6025             var fn = function(m, name, format, args){
6026                 if(format && useF){
6027                     if(format.substr(0, 5) == "this."){
6028                         return tpl.call(format.substr(5), values[name], values);
6029                     }else{
6030                         if(args){
6031                             // quoted values are required for strings in compiled templates, 
6032                             // but for non compiled we need to strip them
6033                             // quoted reversed for jsmin
6034                             var re = /^\s*['"](.*)["']\s*$/;
6035                             args = args.split(',');
6036                             for(var i = 0, len = args.length; i < len; i++){
6037                                 args[i] = args[i].replace(re, "$1");
6038                             }
6039                             args = [values[name]].concat(args);
6040                         }else{
6041                             args = [values[name]];
6042                         }
6043                         return fm[format].apply(fm, args);
6044                     }
6045                 }else{
6046                     return values[name] !== undefined ? values[name] : "";
6047                 }
6048             };
6049             return this.html.replace(this.re, fn);
6050         } catch (e) {
6051             Roo.log(e);
6052             throw e;
6053         }
6054          
6055     },
6056     
6057     loading : false,
6058       
6059     load : function ()
6060     {
6061          
6062         if (this.loading) {
6063             return;
6064         }
6065         var _t = this;
6066         
6067         this.loading = true;
6068         this.compiled = false;
6069         
6070         var cx = new Roo.data.Connection();
6071         cx.request({
6072             url : this.url,
6073             method : 'GET',
6074             success : function (response) {
6075                 _t.loading = false;
6076                 _t.url = false;
6077                 
6078                 _t.set(response.responseText,true);
6079                 _t.loaded = true;
6080                 if (_t.onLoad) {
6081                     _t.onLoad();
6082                 }
6083              },
6084             failure : function(response) {
6085                 Roo.log("Template failed to load from " + _t.url);
6086                 _t.loading = false;
6087             }
6088         });
6089     },
6090
6091     /**
6092      * Sets the HTML used as the template and optionally compiles it.
6093      * @param {String} html
6094      * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
6095      * @return {Roo.Template} this
6096      */
6097     set : function(html, compile){
6098         this.html = html;
6099         this.compiled = false;
6100         if(compile){
6101             this.compile();
6102         }
6103         return this;
6104     },
6105     
6106     /**
6107      * True to disable format functions (defaults to false)
6108      * @type Boolean
6109      */
6110     disableFormats : false,
6111     
6112     /**
6113     * The regular expression used to match template variables 
6114     * @type RegExp
6115     * @property 
6116     */
6117     re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
6118     
6119     /**
6120      * Compiles the template into an internal function, eliminating the RegEx overhead.
6121      * @return {Roo.Template} this
6122      */
6123     compile : function(){
6124         var fm = Roo.util.Format;
6125         var useF = this.disableFormats !== true;
6126         var sep = Roo.isGecko ? "+" : ",";
6127         var fn = function(m, name, format, args){
6128             if(format && useF){
6129                 args = args ? ',' + args : "";
6130                 if(format.substr(0, 5) != "this."){
6131                     format = "fm." + format + '(';
6132                 }else{
6133                     format = 'this.call("'+ format.substr(5) + '", ';
6134                     args = ", values";
6135                 }
6136             }else{
6137                 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
6138             }
6139             return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
6140         };
6141         var body;
6142         // branched to use + in gecko and [].join() in others
6143         if(Roo.isGecko){
6144             body = "this.compiled = function(values){ return '" +
6145                    this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
6146                     "';};";
6147         }else{
6148             body = ["this.compiled = function(values){ return ['"];
6149             body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
6150             body.push("'].join('');};");
6151             body = body.join('');
6152         }
6153         /**
6154          * eval:var:values
6155          * eval:var:fm
6156          */
6157         eval(body);
6158         return this;
6159     },
6160     
6161     // private function used to call members
6162     call : function(fnName, value, allValues){
6163         return this[fnName](value, allValues);
6164     },
6165     
6166     /**
6167      * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
6168      * @param {String/HTMLElement/Roo.Element} el The context element
6169      * @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'})
6170      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6171      * @return {HTMLElement/Roo.Element} The new node or Element
6172      */
6173     insertFirst: function(el, values, returnElement){
6174         return this.doInsert('afterBegin', el, values, returnElement);
6175     },
6176
6177     /**
6178      * Applies the supplied values to the template and inserts the new node(s) before el.
6179      * @param {String/HTMLElement/Roo.Element} el The context element
6180      * @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'})
6181      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6182      * @return {HTMLElement/Roo.Element} The new node or Element
6183      */
6184     insertBefore: function(el, values, returnElement){
6185         return this.doInsert('beforeBegin', el, values, returnElement);
6186     },
6187
6188     /**
6189      * Applies the supplied values to the template and inserts the new node(s) after el.
6190      * @param {String/HTMLElement/Roo.Element} el The context element
6191      * @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'})
6192      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6193      * @return {HTMLElement/Roo.Element} The new node or Element
6194      */
6195     insertAfter : function(el, values, returnElement){
6196         return this.doInsert('afterEnd', el, values, returnElement);
6197     },
6198     
6199     /**
6200      * Applies the supplied values to the template and appends the new node(s) to el.
6201      * @param {String/HTMLElement/Roo.Element} el The context element
6202      * @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'})
6203      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6204      * @return {HTMLElement/Roo.Element} The new node or Element
6205      */
6206     append : function(el, values, returnElement){
6207         return this.doInsert('beforeEnd', el, values, returnElement);
6208     },
6209
6210     doInsert : function(where, el, values, returnEl){
6211         el = Roo.getDom(el);
6212         var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
6213         return returnEl ? Roo.get(newNode, true) : newNode;
6214     },
6215
6216     /**
6217      * Applies the supplied values to the template and overwrites the content of el with the new node(s).
6218      * @param {String/HTMLElement/Roo.Element} el The context element
6219      * @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'})
6220      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6221      * @return {HTMLElement/Roo.Element} The new node or Element
6222      */
6223     overwrite : function(el, values, returnElement){
6224         el = Roo.getDom(el);
6225         el.innerHTML = this.applyTemplate(values);
6226         return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
6227     }
6228 };
6229 /**
6230  * Alias for {@link #applyTemplate}
6231  * @method
6232  */
6233 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
6234
6235 // backwards compat
6236 Roo.DomHelper.Template = Roo.Template;
6237
6238 /**
6239  * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
6240  * @param {String/HTMLElement} el A DOM element or its id
6241  * @returns {Roo.Template} The created template
6242  * @static
6243  */
6244 Roo.Template.from = function(el){
6245     el = Roo.getDom(el);
6246     return new Roo.Template(el.value || el.innerHTML);
6247 };/*
6248  * Based on:
6249  * Ext JS Library 1.1.1
6250  * Copyright(c) 2006-2007, Ext JS, LLC.
6251  *
6252  * Originally Released Under LGPL - original licence link has changed is not relivant.
6253  *
6254  * Fork - LGPL
6255  * <script type="text/javascript">
6256  */
6257  
6258
6259 /*
6260  * This is code is also distributed under MIT license for use
6261  * with jQuery and prototype JavaScript libraries.
6262  */
6263 /**
6264  * @class Roo.DomQuery
6265 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).
6266 <p>
6267 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>
6268
6269 <p>
6270 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.
6271 </p>
6272 <h4>Element Selectors:</h4>
6273 <ul class="list">
6274     <li> <b>*</b> any element</li>
6275     <li> <b>E</b> an element with the tag E</li>
6276     <li> <b>E F</b> All descendent elements of E that have the tag F</li>
6277     <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
6278     <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
6279     <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
6280 </ul>
6281 <h4>Attribute Selectors:</h4>
6282 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
6283 <ul class="list">
6284     <li> <b>E[foo]</b> has an attribute "foo"</li>
6285     <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
6286     <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
6287     <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
6288     <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
6289     <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
6290     <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
6291 </ul>
6292 <h4>Pseudo Classes:</h4>
6293 <ul class="list">
6294     <li> <b>E:first-child</b> E is the first child of its parent</li>
6295     <li> <b>E:last-child</b> E is the last child of its parent</li>
6296     <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>
6297     <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
6298     <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
6299     <li> <b>E:only-child</b> E is the only child of its parent</li>
6300     <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>
6301     <li> <b>E:first</b> the first E in the resultset</li>
6302     <li> <b>E:last</b> the last E in the resultset</li>
6303     <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
6304     <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
6305     <li> <b>E:even</b> shortcut for :nth-child(even)</li>
6306     <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
6307     <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
6308     <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
6309     <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
6310     <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
6311     <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
6312 </ul>
6313 <h4>CSS Value Selectors:</h4>
6314 <ul class="list">
6315     <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
6316     <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
6317     <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
6318     <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
6319     <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
6320     <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
6321 </ul>
6322  * @static
6323  */
6324 Roo.DomQuery = function(){
6325     var cache = {}, simpleCache = {}, valueCache = {};
6326     var nonSpace = /\S/;
6327     var trimRe = /^\s+|\s+$/g;
6328     var tplRe = /\{(\d+)\}/g;
6329     var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
6330     var tagTokenRe = /^(#)?([\w-\*]+)/;
6331     var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
6332
6333     function child(p, index){
6334         var i = 0;
6335         var n = p.firstChild;
6336         while(n){
6337             if(n.nodeType == 1){
6338                if(++i == index){
6339                    return n;
6340                }
6341             }
6342             n = n.nextSibling;
6343         }
6344         return null;
6345     };
6346
6347     function next(n){
6348         while((n = n.nextSibling) && n.nodeType != 1);
6349         return n;
6350     };
6351
6352     function prev(n){
6353         while((n = n.previousSibling) && n.nodeType != 1);
6354         return n;
6355     };
6356
6357     function children(d){
6358         var n = d.firstChild, ni = -1;
6359             while(n){
6360                 var nx = n.nextSibling;
6361                 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
6362                     d.removeChild(n);
6363                 }else{
6364                     n.nodeIndex = ++ni;
6365                 }
6366                 n = nx;
6367             }
6368             return this;
6369         };
6370
6371     function byClassName(c, a, v){
6372         if(!v){
6373             return c;
6374         }
6375         var r = [], ri = -1, cn;
6376         for(var i = 0, ci; ci = c[i]; i++){
6377             
6378             
6379             if((' '+
6380                 ( (ci instanceof SVGElement) ? ci.className.baseVal : ci.className)
6381                  +' ').indexOf(v) != -1){
6382                 r[++ri] = ci;
6383             }
6384         }
6385         return r;
6386     };
6387
6388     function attrValue(n, attr){
6389         if(!n.tagName && typeof n.length != "undefined"){
6390             n = n[0];
6391         }
6392         if(!n){
6393             return null;
6394         }
6395         if(attr == "for"){
6396             return n.htmlFor;
6397         }
6398         if(attr == "class" || attr == "className"){
6399             return (n instanceof SVGElement) ? n.className.baseVal : n.className;
6400         }
6401         return n.getAttribute(attr) || n[attr];
6402
6403     };
6404
6405     function getNodes(ns, mode, tagName){
6406         var result = [], ri = -1, cs;
6407         if(!ns){
6408             return result;
6409         }
6410         tagName = tagName || "*";
6411         if(typeof ns.getElementsByTagName != "undefined"){
6412             ns = [ns];
6413         }
6414         if(!mode){
6415             for(var i = 0, ni; ni = ns[i]; i++){
6416                 cs = ni.getElementsByTagName(tagName);
6417                 for(var j = 0, ci; ci = cs[j]; j++){
6418                     result[++ri] = ci;
6419                 }
6420             }
6421         }else if(mode == "/" || mode == ">"){
6422             var utag = tagName.toUpperCase();
6423             for(var i = 0, ni, cn; ni = ns[i]; i++){
6424                 cn = ni.children || ni.childNodes;
6425                 for(var j = 0, cj; cj = cn[j]; j++){
6426                     if(cj.nodeName == utag || cj.nodeName == tagName  || tagName == '*'){
6427                         result[++ri] = cj;
6428                     }
6429                 }
6430             }
6431         }else if(mode == "+"){
6432             var utag = tagName.toUpperCase();
6433             for(var i = 0, n; n = ns[i]; i++){
6434                 while((n = n.nextSibling) && n.nodeType != 1);
6435                 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
6436                     result[++ri] = n;
6437                 }
6438             }
6439         }else if(mode == "~"){
6440             for(var i = 0, n; n = ns[i]; i++){
6441                 while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
6442                 if(n){
6443                     result[++ri] = n;
6444                 }
6445             }
6446         }
6447         return result;
6448     };
6449
6450     function concat(a, b){
6451         if(b.slice){
6452             return a.concat(b);
6453         }
6454         for(var i = 0, l = b.length; i < l; i++){
6455             a[a.length] = b[i];
6456         }
6457         return a;
6458     }
6459
6460     function byTag(cs, tagName){
6461         if(cs.tagName || cs == document){
6462             cs = [cs];
6463         }
6464         if(!tagName){
6465             return cs;
6466         }
6467         var r = [], ri = -1;
6468         tagName = tagName.toLowerCase();
6469         for(var i = 0, ci; ci = cs[i]; i++){
6470             if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
6471                 r[++ri] = ci;
6472             }
6473         }
6474         return r;
6475     };
6476
6477     function byId(cs, attr, id){
6478         if(cs.tagName || cs == document){
6479             cs = [cs];
6480         }
6481         if(!id){
6482             return cs;
6483         }
6484         var r = [], ri = -1;
6485         for(var i = 0,ci; ci = cs[i]; i++){
6486             if(ci && ci.id == id){
6487                 r[++ri] = ci;
6488                 return r;
6489             }
6490         }
6491         return r;
6492     };
6493
6494     function byAttribute(cs, attr, value, op, custom){
6495         var r = [], ri = -1, st = custom=="{";
6496         var f = Roo.DomQuery.operators[op];
6497         for(var i = 0, ci; ci = cs[i]; i++){
6498             var a;
6499             if(st){
6500                 a = Roo.DomQuery.getStyle(ci, attr);
6501             }
6502             else if(attr == "class" || attr == "className"){
6503                 a = (ci instanceof SVGElement) ? ci.className.baseVal : ci.className;
6504             }else if(attr == "for"){
6505                 a = ci.htmlFor;
6506             }else if(attr == "href"){
6507                 a = ci.getAttribute("href", 2);
6508             }else{
6509                 a = ci.getAttribute(attr);
6510             }
6511             if((f && f(a, value)) || (!f && a)){
6512                 r[++ri] = ci;
6513             }
6514         }
6515         return r;
6516     };
6517
6518     function byPseudo(cs, name, value){
6519         return Roo.DomQuery.pseudos[name](cs, value);
6520     };
6521
6522     // This is for IE MSXML which does not support expandos.
6523     // IE runs the same speed using setAttribute, however FF slows way down
6524     // and Safari completely fails so they need to continue to use expandos.
6525     var isIE = window.ActiveXObject ? true : false;
6526
6527     // this eval is stop the compressor from
6528     // renaming the variable to something shorter
6529     
6530     /** eval:var:batch */
6531     var batch = 30803; 
6532
6533     var key = 30803;
6534
6535     function nodupIEXml(cs){
6536         var d = ++key;
6537         cs[0].setAttribute("_nodup", d);
6538         var r = [cs[0]];
6539         for(var i = 1, len = cs.length; i < len; i++){
6540             var c = cs[i];
6541             if(!c.getAttribute("_nodup") != d){
6542                 c.setAttribute("_nodup", d);
6543                 r[r.length] = c;
6544             }
6545         }
6546         for(var i = 0, len = cs.length; i < len; i++){
6547             cs[i].removeAttribute("_nodup");
6548         }
6549         return r;
6550     }
6551
6552     function nodup(cs){
6553         if(!cs){
6554             return [];
6555         }
6556         var len = cs.length, c, i, r = cs, cj, ri = -1;
6557         if(!len || typeof cs.nodeType != "undefined" || len == 1){
6558             return cs;
6559         }
6560         if(isIE && typeof cs[0].selectSingleNode != "undefined"){
6561             return nodupIEXml(cs);
6562         }
6563         var d = ++key;
6564         cs[0]._nodup = d;
6565         for(i = 1; c = cs[i]; i++){
6566             if(c._nodup != d){
6567                 c._nodup = d;
6568             }else{
6569                 r = [];
6570                 for(var j = 0; j < i; j++){
6571                     r[++ri] = cs[j];
6572                 }
6573                 for(j = i+1; cj = cs[j]; j++){
6574                     if(cj._nodup != d){
6575                         cj._nodup = d;
6576                         r[++ri] = cj;
6577                     }
6578                 }
6579                 return r;
6580             }
6581         }
6582         return r;
6583     }
6584
6585     function quickDiffIEXml(c1, c2){
6586         var d = ++key;
6587         for(var i = 0, len = c1.length; i < len; i++){
6588             c1[i].setAttribute("_qdiff", d);
6589         }
6590         var r = [];
6591         for(var i = 0, len = c2.length; i < len; i++){
6592             if(c2[i].getAttribute("_qdiff") != d){
6593                 r[r.length] = c2[i];
6594             }
6595         }
6596         for(var i = 0, len = c1.length; i < len; i++){
6597            c1[i].removeAttribute("_qdiff");
6598         }
6599         return r;
6600     }
6601
6602     function quickDiff(c1, c2){
6603         var len1 = c1.length;
6604         if(!len1){
6605             return c2;
6606         }
6607         if(isIE && c1[0].selectSingleNode){
6608             return quickDiffIEXml(c1, c2);
6609         }
6610         var d = ++key;
6611         for(var i = 0; i < len1; i++){
6612             c1[i]._qdiff = d;
6613         }
6614         var r = [];
6615         for(var i = 0, len = c2.length; i < len; i++){
6616             if(c2[i]._qdiff != d){
6617                 r[r.length] = c2[i];
6618             }
6619         }
6620         return r;
6621     }
6622
6623     function quickId(ns, mode, root, id){
6624         if(ns == root){
6625            var d = root.ownerDocument || root;
6626            return d.getElementById(id);
6627         }
6628         ns = getNodes(ns, mode, "*");
6629         return byId(ns, null, id);
6630     }
6631
6632     return {
6633         getStyle : function(el, name){
6634             return Roo.fly(el).getStyle(name);
6635         },
6636         /**
6637          * Compiles a selector/xpath query into a reusable function. The returned function
6638          * takes one parameter "root" (optional), which is the context node from where the query should start.
6639          * @param {String} selector The selector/xpath query
6640          * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
6641          * @return {Function}
6642          */
6643         compile : function(path, type){
6644             type = type || "select";
6645             
6646             var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
6647             var q = path, mode, lq;
6648             var tk = Roo.DomQuery.matchers;
6649             var tklen = tk.length;
6650             var mm;
6651
6652             // accept leading mode switch
6653             var lmode = q.match(modeRe);
6654             if(lmode && lmode[1]){
6655                 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
6656                 q = q.replace(lmode[1], "");
6657             }
6658             // strip leading slashes
6659             while(path.substr(0, 1)=="/"){
6660                 path = path.substr(1);
6661             }
6662
6663             while(q && lq != q){
6664                 lq = q;
6665                 var tm = q.match(tagTokenRe);
6666                 if(type == "select"){
6667                     if(tm){
6668                         if(tm[1] == "#"){
6669                             fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
6670                         }else{
6671                             fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
6672                         }
6673                         q = q.replace(tm[0], "");
6674                     }else if(q.substr(0, 1) != '@'){
6675                         fn[fn.length] = 'n = getNodes(n, mode, "*");';
6676                     }
6677                 }else{
6678                     if(tm){
6679                         if(tm[1] == "#"){
6680                             fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
6681                         }else{
6682                             fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
6683                         }
6684                         q = q.replace(tm[0], "");
6685                     }
6686                 }
6687                 while(!(mm = q.match(modeRe))){
6688                     var matched = false;
6689                     for(var j = 0; j < tklen; j++){
6690                         var t = tk[j];
6691                         var m = q.match(t.re);
6692                         if(m){
6693                             fn[fn.length] = t.select.replace(tplRe, function(x, i){
6694                                                     return m[i];
6695                                                 });
6696                             q = q.replace(m[0], "");
6697                             matched = true;
6698                             break;
6699                         }
6700                     }
6701                     // prevent infinite loop on bad selector
6702                     if(!matched){
6703                         throw 'Error parsing selector, parsing failed at "' + q + '"';
6704                     }
6705                 }
6706                 if(mm[1]){
6707                     fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
6708                     q = q.replace(mm[1], "");
6709                 }
6710             }
6711             fn[fn.length] = "return nodup(n);\n}";
6712             
6713              /** 
6714               * list of variables that need from compression as they are used by eval.
6715              *  eval:var:batch 
6716              *  eval:var:nodup
6717              *  eval:var:byTag
6718              *  eval:var:ById
6719              *  eval:var:getNodes
6720              *  eval:var:quickId
6721              *  eval:var:mode
6722              *  eval:var:root
6723              *  eval:var:n
6724              *  eval:var:byClassName
6725              *  eval:var:byPseudo
6726              *  eval:var:byAttribute
6727              *  eval:var:attrValue
6728              * 
6729              **/ 
6730             eval(fn.join(""));
6731             return f;
6732         },
6733
6734         /**
6735          * Selects a group of elements.
6736          * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
6737          * @param {Node} root (optional) The start of the query (defaults to document).
6738          * @return {Array}
6739          */
6740         select : function(path, root, type){
6741             if(!root || root == document){
6742                 root = document;
6743             }
6744             if(typeof root == "string"){
6745                 root = document.getElementById(root);
6746             }
6747             var paths = path.split(",");
6748             var results = [];
6749             for(var i = 0, len = paths.length; i < len; i++){
6750                 var p = paths[i].replace(trimRe, "");
6751                 if(!cache[p]){
6752                     cache[p] = Roo.DomQuery.compile(p);
6753                     if(!cache[p]){
6754                         throw p + " is not a valid selector";
6755                     }
6756                 }
6757                 var result = cache[p](root);
6758                 if(result && result != document){
6759                     results = results.concat(result);
6760                 }
6761             }
6762             if(paths.length > 1){
6763                 return nodup(results);
6764             }
6765             return results;
6766         },
6767
6768         /**
6769          * Selects a single element.
6770          * @param {String} selector The selector/xpath query
6771          * @param {Node} root (optional) The start of the query (defaults to document).
6772          * @return {Element}
6773          */
6774         selectNode : function(path, root){
6775             return Roo.DomQuery.select(path, root)[0];
6776         },
6777
6778         /**
6779          * Selects the value of a node, optionally replacing null with the defaultValue.
6780          * @param {String} selector The selector/xpath query
6781          * @param {Node} root (optional) The start of the query (defaults to document).
6782          * @param {String} defaultValue
6783          */
6784         selectValue : function(path, root, defaultValue){
6785             path = path.replace(trimRe, "");
6786             if(!valueCache[path]){
6787                 valueCache[path] = Roo.DomQuery.compile(path, "select");
6788             }
6789             var n = valueCache[path](root);
6790             n = n[0] ? n[0] : n;
6791             var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
6792             return ((v === null||v === undefined||v==='') ? defaultValue : v);
6793         },
6794
6795         /**
6796          * Selects the value of a node, parsing integers and floats.
6797          * @param {String} selector The selector/xpath query
6798          * @param {Node} root (optional) The start of the query (defaults to document).
6799          * @param {Number} defaultValue
6800          * @return {Number}
6801          */
6802         selectNumber : function(path, root, defaultValue){
6803             var v = Roo.DomQuery.selectValue(path, root, defaultValue || 0);
6804             return parseFloat(v);
6805         },
6806
6807         /**
6808          * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
6809          * @param {String/HTMLElement/Array} el An element id, element or array of elements
6810          * @param {String} selector The simple selector to test
6811          * @return {Boolean}
6812          */
6813         is : function(el, ss){
6814             if(typeof el == "string"){
6815                 el = document.getElementById(el);
6816             }
6817             var isArray = (el instanceof Array);
6818             var result = Roo.DomQuery.filter(isArray ? el : [el], ss);
6819             return isArray ? (result.length == el.length) : (result.length > 0);
6820         },
6821
6822         /**
6823          * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
6824          * @param {Array} el An array of elements to filter
6825          * @param {String} selector The simple selector to test
6826          * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
6827          * the selector instead of the ones that match
6828          * @return {Array}
6829          */
6830         filter : function(els, ss, nonMatches){
6831             ss = ss.replace(trimRe, "");
6832             if(!simpleCache[ss]){
6833                 simpleCache[ss] = Roo.DomQuery.compile(ss, "simple");
6834             }
6835             var result = simpleCache[ss](els);
6836             return nonMatches ? quickDiff(result, els) : result;
6837         },
6838
6839         /**
6840          * Collection of matching regular expressions and code snippets.
6841          */
6842         matchers : [{
6843                 re: /^\.([\w-]+)/,
6844                 select: 'n = byClassName(n, null, " {1} ");'
6845             }, {
6846                 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
6847                 select: 'n = byPseudo(n, "{1}", "{2}");'
6848             },{
6849                 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
6850                 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
6851             }, {
6852                 re: /^#([\w-]+)/,
6853                 select: 'n = byId(n, null, "{1}");'
6854             },{
6855                 re: /^@([\w-]+)/,
6856                 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
6857             }
6858         ],
6859
6860         /**
6861          * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
6862          * 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;.
6863          */
6864         operators : {
6865             "=" : function(a, v){
6866                 return a == v;
6867             },
6868             "!=" : function(a, v){
6869                 return a != v;
6870             },
6871             "^=" : function(a, v){
6872                 return a && a.substr(0, v.length) == v;
6873             },
6874             "$=" : function(a, v){
6875                 return a && a.substr(a.length-v.length) == v;
6876             },
6877             "*=" : function(a, v){
6878                 return a && a.indexOf(v) !== -1;
6879             },
6880             "%=" : function(a, v){
6881                 return (a % v) == 0;
6882             },
6883             "|=" : function(a, v){
6884                 return a && (a == v || a.substr(0, v.length+1) == v+'-');
6885             },
6886             "~=" : function(a, v){
6887                 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
6888             }
6889         },
6890
6891         /**
6892          * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
6893          * and the argument (if any) supplied in the selector.
6894          */
6895         pseudos : {
6896             "first-child" : function(c){
6897                 var r = [], ri = -1, n;
6898                 for(var i = 0, ci; ci = n = c[i]; i++){
6899                     while((n = n.previousSibling) && n.nodeType != 1);
6900                     if(!n){
6901                         r[++ri] = ci;
6902                     }
6903                 }
6904                 return r;
6905             },
6906
6907             "last-child" : function(c){
6908                 var r = [], ri = -1, n;
6909                 for(var i = 0, ci; ci = n = c[i]; i++){
6910                     while((n = n.nextSibling) && n.nodeType != 1);
6911                     if(!n){
6912                         r[++ri] = ci;
6913                     }
6914                 }
6915                 return r;
6916             },
6917
6918             "nth-child" : function(c, a) {
6919                 var r = [], ri = -1;
6920                 var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
6921                 var f = (m[1] || 1) - 0, l = m[2] - 0;
6922                 for(var i = 0, n; n = c[i]; i++){
6923                     var pn = n.parentNode;
6924                     if (batch != pn._batch) {
6925                         var j = 0;
6926                         for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
6927                             if(cn.nodeType == 1){
6928                                cn.nodeIndex = ++j;
6929                             }
6930                         }
6931                         pn._batch = batch;
6932                     }
6933                     if (f == 1) {
6934                         if (l == 0 || n.nodeIndex == l){
6935                             r[++ri] = n;
6936                         }
6937                     } else if ((n.nodeIndex + l) % f == 0){
6938                         r[++ri] = n;
6939                     }
6940                 }
6941
6942                 return r;
6943             },
6944
6945             "only-child" : function(c){
6946                 var r = [], ri = -1;;
6947                 for(var i = 0, ci; ci = c[i]; i++){
6948                     if(!prev(ci) && !next(ci)){
6949                         r[++ri] = ci;
6950                     }
6951                 }
6952                 return r;
6953             },
6954
6955             "empty" : function(c){
6956                 var r = [], ri = -1;
6957                 for(var i = 0, ci; ci = c[i]; i++){
6958                     var cns = ci.childNodes, j = 0, cn, empty = true;
6959                     while(cn = cns[j]){
6960                         ++j;
6961                         if(cn.nodeType == 1 || cn.nodeType == 3){
6962                             empty = false;
6963                             break;
6964                         }
6965                     }
6966                     if(empty){
6967                         r[++ri] = ci;
6968                     }
6969                 }
6970                 return r;
6971             },
6972
6973             "contains" : function(c, v){
6974                 var r = [], ri = -1;
6975                 for(var i = 0, ci; ci = c[i]; i++){
6976                     if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
6977                         r[++ri] = ci;
6978                     }
6979                 }
6980                 return r;
6981             },
6982
6983             "nodeValue" : function(c, v){
6984                 var r = [], ri = -1;
6985                 for(var i = 0, ci; ci = c[i]; i++){
6986                     if(ci.firstChild && ci.firstChild.nodeValue == v){
6987                         r[++ri] = ci;
6988                     }
6989                 }
6990                 return r;
6991             },
6992
6993             "checked" : function(c){
6994                 var r = [], ri = -1;
6995                 for(var i = 0, ci; ci = c[i]; i++){
6996                     if(ci.checked == true){
6997                         r[++ri] = ci;
6998                     }
6999                 }
7000                 return r;
7001             },
7002
7003             "not" : function(c, ss){
7004                 return Roo.DomQuery.filter(c, ss, true);
7005             },
7006
7007             "odd" : function(c){
7008                 return this["nth-child"](c, "odd");
7009             },
7010
7011             "even" : function(c){
7012                 return this["nth-child"](c, "even");
7013             },
7014
7015             "nth" : function(c, a){
7016                 return c[a-1] || [];
7017             },
7018
7019             "first" : function(c){
7020                 return c[0] || [];
7021             },
7022
7023             "last" : function(c){
7024                 return c[c.length-1] || [];
7025             },
7026
7027             "has" : function(c, ss){
7028                 var s = Roo.DomQuery.select;
7029                 var r = [], ri = -1;
7030                 for(var i = 0, ci; ci = c[i]; i++){
7031                     if(s(ss, ci).length > 0){
7032                         r[++ri] = ci;
7033                     }
7034                 }
7035                 return r;
7036             },
7037
7038             "next" : function(c, ss){
7039                 var is = Roo.DomQuery.is;
7040                 var r = [], ri = -1;
7041                 for(var i = 0, ci; ci = c[i]; i++){
7042                     var n = next(ci);
7043                     if(n && is(n, ss)){
7044                         r[++ri] = ci;
7045                     }
7046                 }
7047                 return r;
7048             },
7049
7050             "prev" : function(c, ss){
7051                 var is = Roo.DomQuery.is;
7052                 var r = [], ri = -1;
7053                 for(var i = 0, ci; ci = c[i]; i++){
7054                     var n = prev(ci);
7055                     if(n && is(n, ss)){
7056                         r[++ri] = ci;
7057                     }
7058                 }
7059                 return r;
7060             }
7061         }
7062     };
7063 }();
7064
7065 /**
7066  * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Roo.DomQuery#select}
7067  * @param {String} path The selector/xpath query
7068  * @param {Node} root (optional) The start of the query (defaults to document).
7069  * @return {Array}
7070  * @member Roo
7071  * @method query
7072  */
7073 Roo.query = Roo.DomQuery.select;
7074 /*
7075  * Based on:
7076  * Ext JS Library 1.1.1
7077  * Copyright(c) 2006-2007, Ext JS, LLC.
7078  *
7079  * Originally Released Under LGPL - original licence link has changed is not relivant.
7080  *
7081  * Fork - LGPL
7082  * <script type="text/javascript">
7083  */
7084
7085 /**
7086  * @class Roo.util.Observable
7087  * Base class that provides a common interface for publishing events. Subclasses are expected to
7088  * to have a property "events" with all the events defined.<br>
7089  * For example:
7090  * <pre><code>
7091  Employee = function(name){
7092     this.name = name;
7093     this.addEvents({
7094         "fired" : true,
7095         "quit" : true
7096     });
7097  }
7098  Roo.extend(Employee, Roo.util.Observable);
7099 </code></pre>
7100  * @param {Object} config properties to use (incuding events / listeners)
7101  */
7102
7103 Roo.util.Observable = function(cfg){
7104     
7105     cfg = cfg|| {};
7106     this.addEvents(cfg.events || {});
7107     if (cfg.events) {
7108         delete cfg.events; // make sure
7109     }
7110      
7111     Roo.apply(this, cfg);
7112     
7113     if(this.listeners){
7114         this.on(this.listeners);
7115         delete this.listeners;
7116     }
7117 };
7118 Roo.util.Observable.prototype = {
7119     /** 
7120  * @cfg {Object} listeners  list of events and functions to call for this object, 
7121  * For example :
7122  * <pre><code>
7123     listeners :  { 
7124        'click' : function(e) {
7125            ..... 
7126         } ,
7127         .... 
7128     } 
7129   </code></pre>
7130  */
7131     
7132     
7133     /**
7134      * Fires the specified event with the passed parameters (minus the event name).
7135      * @param {String} eventName
7136      * @param {Object...} args Variable number of parameters are passed to handlers
7137      * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
7138      */
7139     fireEvent : function(){
7140         var ce = this.events[arguments[0].toLowerCase()];
7141         if(typeof ce == "object"){
7142             return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
7143         }else{
7144             return true;
7145         }
7146     },
7147
7148     // private
7149     filterOptRe : /^(?:scope|delay|buffer|single)$/,
7150
7151     /**
7152      * Appends an event handler to this component
7153      * @param {String}   eventName The type of event to listen for
7154      * @param {Function} handler The method the event invokes
7155      * @param {Object}   scope (optional) The scope in which to execute the handler
7156      * function. The handler function's "this" context.
7157      * @param {Object}   options (optional) An object containing handler configuration
7158      * properties. This may contain any of the following properties:<ul>
7159      * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7160      * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7161      * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7162      * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7163      * by the specified number of milliseconds. If the event fires again within that time, the original
7164      * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7165      * </ul><br>
7166      * <p>
7167      * <b>Combining Options</b><br>
7168      * Using the options argument, it is possible to combine different types of listeners:<br>
7169      * <br>
7170      * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
7171                 <pre><code>
7172                 el.on('click', this.onClick, this, {
7173                         single: true,
7174                 delay: 100,
7175                 forumId: 4
7176                 });
7177                 </code></pre>
7178      * <p>
7179      * <b>Attaching multiple handlers in 1 call</b><br>
7180      * The method also allows for a single argument to be passed which is a config object containing properties
7181      * which specify multiple handlers.
7182      * <pre><code>
7183                 el.on({
7184                         'click': {
7185                         fn: this.onClick,
7186                         scope: this,
7187                         delay: 100
7188                 }, 
7189                 'mouseover': {
7190                         fn: this.onMouseOver,
7191                         scope: this
7192                 },
7193                 'mouseout': {
7194                         fn: this.onMouseOut,
7195                         scope: this
7196                 }
7197                 });
7198                 </code></pre>
7199      * <p>
7200      * Or a shorthand syntax which passes the same scope object to all handlers:
7201         <pre><code>
7202                 el.on({
7203                         'click': this.onClick,
7204                 'mouseover': this.onMouseOver,
7205                 'mouseout': this.onMouseOut,
7206                 scope: this
7207                 });
7208                 </code></pre>
7209      */
7210     addListener : function(eventName, fn, scope, o){
7211         if(typeof eventName == "object"){
7212             o = eventName;
7213             for(var e in o){
7214                 if(this.filterOptRe.test(e)){
7215                     continue;
7216                 }
7217                 if(typeof o[e] == "function"){
7218                     // shared options
7219                     this.addListener(e, o[e], o.scope,  o);
7220                 }else{
7221                     // individual options
7222                     this.addListener(e, o[e].fn, o[e].scope, o[e]);
7223                 }
7224             }
7225             return;
7226         }
7227         o = (!o || typeof o == "boolean") ? {} : o;
7228         eventName = eventName.toLowerCase();
7229         var ce = this.events[eventName] || true;
7230         if(typeof ce == "boolean"){
7231             ce = new Roo.util.Event(this, eventName);
7232             this.events[eventName] = ce;
7233         }
7234         ce.addListener(fn, scope, o);
7235     },
7236
7237     /**
7238      * Removes a listener
7239      * @param {String}   eventName     The type of event to listen for
7240      * @param {Function} handler        The handler to remove
7241      * @param {Object}   scope  (optional) The scope (this object) for the handler
7242      */
7243     removeListener : function(eventName, fn, scope){
7244         var ce = this.events[eventName.toLowerCase()];
7245         if(typeof ce == "object"){
7246             ce.removeListener(fn, scope);
7247         }
7248     },
7249
7250     /**
7251      * Removes all listeners for this object
7252      */
7253     purgeListeners : function(){
7254         for(var evt in this.events){
7255             if(typeof this.events[evt] == "object"){
7256                  this.events[evt].clearListeners();
7257             }
7258         }
7259     },
7260
7261     relayEvents : function(o, events){
7262         var createHandler = function(ename){
7263             return function(){
7264                  
7265                 return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
7266             };
7267         };
7268         for(var i = 0, len = events.length; i < len; i++){
7269             var ename = events[i];
7270             if(!this.events[ename]){
7271                 this.events[ename] = true;
7272             };
7273             o.on(ename, createHandler(ename), this);
7274         }
7275     },
7276
7277     /**
7278      * Used to define events on this Observable
7279      * @param {Object} object The object with the events defined
7280      */
7281     addEvents : function(o){
7282         if(!this.events){
7283             this.events = {};
7284         }
7285         Roo.applyIf(this.events, o);
7286     },
7287
7288     /**
7289      * Checks to see if this object has any listeners for a specified event
7290      * @param {String} eventName The name of the event to check for
7291      * @return {Boolean} True if the event is being listened for, else false
7292      */
7293     hasListener : function(eventName){
7294         var e = this.events[eventName];
7295         return typeof e == "object" && e.listeners.length > 0;
7296     }
7297 };
7298 /**
7299  * Appends an event handler to this element (shorthand for addListener)
7300  * @param {String}   eventName     The type of event to listen for
7301  * @param {Function} handler        The method the event invokes
7302  * @param {Object}   scope (optional) The scope in which to execute the handler
7303  * function. The handler function's "this" context.
7304  * @param {Object}   options  (optional)
7305  * @method
7306  */
7307 Roo.util.Observable.prototype.on = Roo.util.Observable.prototype.addListener;
7308 /**
7309  * Removes a listener (shorthand for removeListener)
7310  * @param {String}   eventName     The type of event to listen for
7311  * @param {Function} handler        The handler to remove
7312  * @param {Object}   scope  (optional) The scope (this object) for the handler
7313  * @method
7314  */
7315 Roo.util.Observable.prototype.un = Roo.util.Observable.prototype.removeListener;
7316
7317 /**
7318  * Starts capture on the specified Observable. All events will be passed
7319  * to the supplied function with the event name + standard signature of the event
7320  * <b>before</b> the event is fired. If the supplied function returns false,
7321  * the event will not fire.
7322  * @param {Observable} o The Observable to capture
7323  * @param {Function} fn The function to call
7324  * @param {Object} scope (optional) The scope (this object) for the fn
7325  * @static
7326  */
7327 Roo.util.Observable.capture = function(o, fn, scope){
7328     o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
7329 };
7330
7331 /**
7332  * Removes <b>all</b> added captures from the Observable.
7333  * @param {Observable} o The Observable to release
7334  * @static
7335  */
7336 Roo.util.Observable.releaseCapture = function(o){
7337     o.fireEvent = Roo.util.Observable.prototype.fireEvent;
7338 };
7339
7340 (function(){
7341
7342     var createBuffered = function(h, o, scope){
7343         var task = new Roo.util.DelayedTask();
7344         return function(){
7345             task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
7346         };
7347     };
7348
7349     var createSingle = function(h, e, fn, scope){
7350         return function(){
7351             e.removeListener(fn, scope);
7352             return h.apply(scope, arguments);
7353         };
7354     };
7355
7356     var createDelayed = function(h, o, scope){
7357         return function(){
7358             var args = Array.prototype.slice.call(arguments, 0);
7359             setTimeout(function(){
7360                 h.apply(scope, args);
7361             }, o.delay || 10);
7362         };
7363     };
7364
7365     Roo.util.Event = function(obj, name){
7366         this.name = name;
7367         this.obj = obj;
7368         this.listeners = [];
7369     };
7370
7371     Roo.util.Event.prototype = {
7372         addListener : function(fn, scope, options){
7373             var o = options || {};
7374             scope = scope || this.obj;
7375             if(!this.isListening(fn, scope)){
7376                 var l = {fn: fn, scope: scope, options: o};
7377                 var h = fn;
7378                 if(o.delay){
7379                     h = createDelayed(h, o, scope);
7380                 }
7381                 if(o.single){
7382                     h = createSingle(h, this, fn, scope);
7383                 }
7384                 if(o.buffer){
7385                     h = createBuffered(h, o, scope);
7386                 }
7387                 l.fireFn = h;
7388                 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
7389                     this.listeners.push(l);
7390                 }else{
7391                     this.listeners = this.listeners.slice(0);
7392                     this.listeners.push(l);
7393                 }
7394             }
7395         },
7396
7397         findListener : function(fn, scope){
7398             scope = scope || this.obj;
7399             var ls = this.listeners;
7400             for(var i = 0, len = ls.length; i < len; i++){
7401                 var l = ls[i];
7402                 if(l.fn == fn && l.scope == scope){
7403                     return i;
7404                 }
7405             }
7406             return -1;
7407         },
7408
7409         isListening : function(fn, scope){
7410             return this.findListener(fn, scope) != -1;
7411         },
7412
7413         removeListener : function(fn, scope){
7414             var index;
7415             if((index = this.findListener(fn, scope)) != -1){
7416                 if(!this.firing){
7417                     this.listeners.splice(index, 1);
7418                 }else{
7419                     this.listeners = this.listeners.slice(0);
7420                     this.listeners.splice(index, 1);
7421                 }
7422                 return true;
7423             }
7424             return false;
7425         },
7426
7427         clearListeners : function(){
7428             this.listeners = [];
7429         },
7430
7431         fire : function(){
7432             var ls = this.listeners, scope, len = ls.length;
7433             if(len > 0){
7434                 this.firing = true;
7435                 var args = Array.prototype.slice.call(arguments, 0);                
7436                 for(var i = 0; i < len; i++){
7437                     var l = ls[i];
7438                     if(l.fireFn.apply(l.scope||this.obj||window, args) === false){
7439                         this.firing = false;
7440                         return false;
7441                     }
7442                 }
7443                 this.firing = false;
7444             }
7445             return true;
7446         }
7447     };
7448 })();/*
7449  * RooJS Library 
7450  * Copyright(c) 2007-2017, Roo J Solutions Ltd
7451  *
7452  * Licence LGPL 
7453  *
7454  */
7455  
7456 /**
7457  * @class Roo.Document
7458  * @extends Roo.util.Observable
7459  * This is a convience class to wrap up the main document loading code.. , rather than adding Roo.onReady(......)
7460  * 
7461  * @param {Object} config the methods and properties of the 'base' class for the application.
7462  * 
7463  *  Generic Page handler - implement this to start your app..
7464  * 
7465  * eg.
7466  *  MyProject = new Roo.Document({
7467         events : {
7468             'load' : true // your events..
7469         },
7470         listeners : {
7471             'ready' : function() {
7472                 // fired on Roo.onReady()
7473             }
7474         }
7475  * 
7476  */
7477 Roo.Document = function(cfg) {
7478      
7479     this.addEvents({ 
7480         'ready' : true
7481     });
7482     Roo.util.Observable.call(this,cfg);
7483     
7484     var _this = this;
7485     
7486     Roo.onReady(function() {
7487         _this.fireEvent('ready');
7488     },null,false);
7489     
7490     
7491 }
7492
7493 Roo.extend(Roo.Document, Roo.util.Observable, {});/*
7494  * Based on:
7495  * Ext JS Library 1.1.1
7496  * Copyright(c) 2006-2007, Ext JS, LLC.
7497  *
7498  * Originally Released Under LGPL - original licence link has changed is not relivant.
7499  *
7500  * Fork - LGPL
7501  * <script type="text/javascript">
7502  */
7503
7504 /**
7505  * @class Roo.EventManager
7506  * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides 
7507  * several useful events directly.
7508  * See {@link Roo.EventObject} for more details on normalized event objects.
7509  * @static
7510  */
7511 Roo.EventManager = function(){
7512     var docReadyEvent, docReadyProcId, docReadyState = false;
7513     var resizeEvent, resizeTask, textEvent, textSize;
7514     var E = Roo.lib.Event;
7515     var D = Roo.lib.Dom;
7516
7517     
7518     
7519
7520     var fireDocReady = function(){
7521         if(!docReadyState){
7522             docReadyState = true;
7523             Roo.isReady = true;
7524             if(docReadyProcId){
7525                 clearInterval(docReadyProcId);
7526             }
7527             if(Roo.isGecko || Roo.isOpera) {
7528                 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
7529             }
7530             if(Roo.isIE){
7531                 var defer = document.getElementById("ie-deferred-loader");
7532                 if(defer){
7533                     defer.onreadystatechange = null;
7534                     defer.parentNode.removeChild(defer);
7535                 }
7536             }
7537             if(docReadyEvent){
7538                 docReadyEvent.fire();
7539                 docReadyEvent.clearListeners();
7540             }
7541         }
7542     };
7543     
7544     var initDocReady = function(){
7545         docReadyEvent = new Roo.util.Event();
7546         if(Roo.isGecko || Roo.isOpera) {
7547             document.addEventListener("DOMContentLoaded", fireDocReady, false);
7548         }else if(Roo.isIE){
7549             document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
7550             var defer = document.getElementById("ie-deferred-loader");
7551             defer.onreadystatechange = function(){
7552                 if(this.readyState == "complete"){
7553                     fireDocReady();
7554                 }
7555             };
7556         }else if(Roo.isSafari){ 
7557             docReadyProcId = setInterval(function(){
7558                 var rs = document.readyState;
7559                 if(rs == "complete") {
7560                     fireDocReady();     
7561                  }
7562             }, 10);
7563         }
7564         // no matter what, make sure it fires on load
7565         E.on(window, "load", fireDocReady);
7566     };
7567
7568     var createBuffered = function(h, o){
7569         var task = new Roo.util.DelayedTask(h);
7570         return function(e){
7571             // create new event object impl so new events don't wipe out properties
7572             e = new Roo.EventObjectImpl(e);
7573             task.delay(o.buffer, h, null, [e]);
7574         };
7575     };
7576
7577     var createSingle = function(h, el, ename, fn){
7578         return function(e){
7579             Roo.EventManager.removeListener(el, ename, fn);
7580             h(e);
7581         };
7582     };
7583
7584     var createDelayed = function(h, o){
7585         return function(e){
7586             // create new event object impl so new events don't wipe out properties
7587             e = new Roo.EventObjectImpl(e);
7588             setTimeout(function(){
7589                 h(e);
7590             }, o.delay || 10);
7591         };
7592     };
7593     var transitionEndVal = false;
7594     
7595     var transitionEnd = function()
7596     {
7597         if (transitionEndVal) {
7598             return transitionEndVal;
7599         }
7600         var el = document.createElement('div');
7601
7602         var transEndEventNames = {
7603             WebkitTransition : 'webkitTransitionEnd',
7604             MozTransition    : 'transitionend',
7605             OTransition      : 'oTransitionEnd otransitionend',
7606             transition       : 'transitionend'
7607         };
7608     
7609         for (var name in transEndEventNames) {
7610             if (el.style[name] !== undefined) {
7611                 transitionEndVal = transEndEventNames[name];
7612                 return  transitionEndVal ;
7613             }
7614         }
7615     }
7616     
7617   
7618
7619     var listen = function(element, ename, opt, fn, scope)
7620     {
7621         var o = (!opt || typeof opt == "boolean") ? {} : opt;
7622         fn = fn || o.fn; scope = scope || o.scope;
7623         var el = Roo.getDom(element);
7624         
7625         
7626         if(!el){
7627             throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
7628         }
7629         
7630         if (ename == 'transitionend') {
7631             ename = transitionEnd();
7632         }
7633         var h = function(e){
7634             e = Roo.EventObject.setEvent(e);
7635             var t;
7636             if(o.delegate){
7637                 t = e.getTarget(o.delegate, el);
7638                 if(!t){
7639                     return;
7640                 }
7641             }else{
7642                 t = e.target;
7643             }
7644             if(o.stopEvent === true){
7645                 e.stopEvent();
7646             }
7647             if(o.preventDefault === true){
7648                e.preventDefault();
7649             }
7650             if(o.stopPropagation === true){
7651                 e.stopPropagation();
7652             }
7653
7654             if(o.normalized === false){
7655                 e = e.browserEvent;
7656             }
7657
7658             fn.call(scope || el, e, t, o);
7659         };
7660         if(o.delay){
7661             h = createDelayed(h, o);
7662         }
7663         if(o.single){
7664             h = createSingle(h, el, ename, fn);
7665         }
7666         if(o.buffer){
7667             h = createBuffered(h, o);
7668         }
7669         
7670         fn._handlers = fn._handlers || [];
7671         
7672         
7673         fn._handlers.push([Roo.id(el), ename, h]);
7674         
7675         
7676          
7677         E.on(el, ename, h); // this adds the actuall listener to the object..
7678         
7679         
7680         if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
7681             el.addEventListener("DOMMouseScroll", h, false);
7682             E.on(window, 'unload', function(){
7683                 el.removeEventListener("DOMMouseScroll", h, false);
7684             });
7685         }
7686         if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7687             Roo.EventManager.stoppedMouseDownEvent.addListener(h);
7688         }
7689         return h;
7690     };
7691
7692     var stopListening = function(el, ename, fn){
7693         var id = Roo.id(el), hds = fn._handlers, hd = fn;
7694         if(hds){
7695             for(var i = 0, len = hds.length; i < len; i++){
7696                 var h = hds[i];
7697                 if(h[0] == id && h[1] == ename){
7698                     hd = h[2];
7699                     hds.splice(i, 1);
7700                     break;
7701                 }
7702             }
7703         }
7704         E.un(el, ename, hd);
7705         el = Roo.getDom(el);
7706         if(ename == "mousewheel" && el.addEventListener){
7707             el.removeEventListener("DOMMouseScroll", hd, false);
7708         }
7709         if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7710             Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
7711         }
7712     };
7713
7714     var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
7715     
7716     var pub = {
7717         
7718         
7719         /** 
7720          * Fix for doc tools
7721          * @scope Roo.EventManager
7722          */
7723         
7724         
7725         /** 
7726          * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
7727          * object with a Roo.EventObject
7728          * @param {Function} fn        The method the event invokes
7729          * @param {Object}   scope    An object that becomes the scope of the handler
7730          * @param {boolean}  override If true, the obj passed in becomes
7731          *                             the execution scope of the listener
7732          * @return {Function} The wrapped function
7733          * @deprecated
7734          */
7735         wrap : function(fn, scope, override){
7736             return function(e){
7737                 Roo.EventObject.setEvent(e);
7738                 fn.call(override ? scope || window : window, Roo.EventObject, scope);
7739             };
7740         },
7741         
7742         /**
7743      * Appends an event handler to an element (shorthand for addListener)
7744      * @param {String/HTMLElement}   element        The html element or id to assign the
7745      * @param {String}   eventName The type of event to listen for
7746      * @param {Function} handler The method the event invokes
7747      * @param {Object}   scope (optional) The scope in which to execute the handler
7748      * function. The handler function's "this" context.
7749      * @param {Object}   options (optional) An object containing handler configuration
7750      * properties. This may contain any of the following properties:<ul>
7751      * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7752      * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7753      * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7754      * <li>preventDefault {Boolean} True to prevent the default action</li>
7755      * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7756      * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7757      * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7758      * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7759      * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7760      * by the specified number of milliseconds. If the event fires again within that time, the original
7761      * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7762      * </ul><br>
7763      * <p>
7764      * <b>Combining Options</b><br>
7765      * Using the options argument, it is possible to combine different types of listeners:<br>
7766      * <br>
7767      * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7768      * Code:<pre><code>
7769 el.on('click', this.onClick, this, {
7770     single: true,
7771     delay: 100,
7772     stopEvent : true,
7773     forumId: 4
7774 });</code></pre>
7775      * <p>
7776      * <b>Attaching multiple handlers in 1 call</b><br>
7777       * The method also allows for a single argument to be passed which is a config object containing properties
7778      * which specify multiple handlers.
7779      * <p>
7780      * Code:<pre><code>
7781 el.on({
7782     'click' : {
7783         fn: this.onClick
7784         scope: this,
7785         delay: 100
7786     },
7787     'mouseover' : {
7788         fn: this.onMouseOver
7789         scope: this
7790     },
7791     'mouseout' : {
7792         fn: this.onMouseOut
7793         scope: this
7794     }
7795 });</code></pre>
7796      * <p>
7797      * Or a shorthand syntax:<br>
7798      * Code:<pre><code>
7799 el.on({
7800     'click' : this.onClick,
7801     'mouseover' : this.onMouseOver,
7802     'mouseout' : this.onMouseOut
7803     scope: this
7804 });</code></pre>
7805      */
7806         addListener : function(element, eventName, fn, scope, options){
7807             if(typeof eventName == "object"){
7808                 var o = eventName;
7809                 for(var e in o){
7810                     if(propRe.test(e)){
7811                         continue;
7812                     }
7813                     if(typeof o[e] == "function"){
7814                         // shared options
7815                         listen(element, e, o, o[e], o.scope);
7816                     }else{
7817                         // individual options
7818                         listen(element, e, o[e]);
7819                     }
7820                 }
7821                 return;
7822             }
7823             return listen(element, eventName, options, fn, scope);
7824         },
7825         
7826         /**
7827          * Removes an event handler
7828          *
7829          * @param {String/HTMLElement}   element        The id or html element to remove the 
7830          *                             event from
7831          * @param {String}   eventName     The type of event
7832          * @param {Function} fn
7833          * @return {Boolean} True if a listener was actually removed
7834          */
7835         removeListener : function(element, eventName, fn){
7836             return stopListening(element, eventName, fn);
7837         },
7838         
7839         /**
7840          * Fires when the document is ready (before onload and before images are loaded). Can be 
7841          * accessed shorthanded Roo.onReady().
7842          * @param {Function} fn        The method the event invokes
7843          * @param {Object}   scope    An  object that becomes the scope of the handler
7844          * @param {boolean}  options
7845          */
7846         onDocumentReady : function(fn, scope, options){
7847             if(docReadyState){ // if it already fired
7848                 docReadyEvent.addListener(fn, scope, options);
7849                 docReadyEvent.fire();
7850                 docReadyEvent.clearListeners();
7851                 return;
7852             }
7853             if(!docReadyEvent){
7854                 initDocReady();
7855             }
7856             docReadyEvent.addListener(fn, scope, options);
7857         },
7858         
7859         /**
7860          * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
7861          * @param {Function} fn        The method the event invokes
7862          * @param {Object}   scope    An object that becomes the scope of the handler
7863          * @param {boolean}  options
7864          */
7865         onWindowResize : function(fn, scope, options)
7866         {
7867             if(!resizeEvent){
7868                 resizeEvent = new Roo.util.Event();
7869                 resizeTask = new Roo.util.DelayedTask(function(){
7870                     resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7871                 });
7872                 E.on(window, "resize", function()
7873                 {
7874                     if (Roo.isIE) {
7875                         resizeTask.delay(50);
7876                     } else {
7877                         resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7878                     }
7879                 });
7880             }
7881             resizeEvent.addListener(fn, scope, options);
7882         },
7883
7884         /**
7885          * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
7886          * @param {Function} fn        The method the event invokes
7887          * @param {Object}   scope    An object that becomes the scope of the handler
7888          * @param {boolean}  options
7889          */
7890         onTextResize : function(fn, scope, options){
7891             if(!textEvent){
7892                 textEvent = new Roo.util.Event();
7893                 var textEl = new Roo.Element(document.createElement('div'));
7894                 textEl.dom.className = 'x-text-resize';
7895                 textEl.dom.innerHTML = 'X';
7896                 textEl.appendTo(document.body);
7897                 textSize = textEl.dom.offsetHeight;
7898                 setInterval(function(){
7899                     if(textEl.dom.offsetHeight != textSize){
7900                         textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
7901                     }
7902                 }, this.textResizeInterval);
7903             }
7904             textEvent.addListener(fn, scope, options);
7905         },
7906
7907         /**
7908          * Removes the passed window resize listener.
7909          * @param {Function} fn        The method the event invokes
7910          * @param {Object}   scope    The scope of handler
7911          */
7912         removeResizeListener : function(fn, scope){
7913             if(resizeEvent){
7914                 resizeEvent.removeListener(fn, scope);
7915             }
7916         },
7917
7918         // private
7919         fireResize : function(){
7920             if(resizeEvent){
7921                 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7922             }   
7923         },
7924         /**
7925          * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
7926          */
7927         ieDeferSrc : false,
7928         /**
7929          * The frequency, in milliseconds, to check for text resize events (defaults to 50)
7930          */
7931         textResizeInterval : 50
7932     };
7933     
7934     /**
7935      * Fix for doc tools
7936      * @scopeAlias pub=Roo.EventManager
7937      */
7938     
7939      /**
7940      * Appends an event handler to an element (shorthand for addListener)
7941      * @param {String/HTMLElement}   element        The html element or id to assign the
7942      * @param {String}   eventName The type of event to listen for
7943      * @param {Function} handler The method the event invokes
7944      * @param {Object}   scope (optional) The scope in which to execute the handler
7945      * function. The handler function's "this" context.
7946      * @param {Object}   options (optional) An object containing handler configuration
7947      * properties. This may contain any of the following properties:<ul>
7948      * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7949      * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7950      * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7951      * <li>preventDefault {Boolean} True to prevent the default action</li>
7952      * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7953      * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7954      * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7955      * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7956      * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7957      * by the specified number of milliseconds. If the event fires again within that time, the original
7958      * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7959      * </ul><br>
7960      * <p>
7961      * <b>Combining Options</b><br>
7962      * Using the options argument, it is possible to combine different types of listeners:<br>
7963      * <br>
7964      * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7965      * Code:<pre><code>
7966 el.on('click', this.onClick, this, {
7967     single: true,
7968     delay: 100,
7969     stopEvent : true,
7970     forumId: 4
7971 });</code></pre>
7972      * <p>
7973      * <b>Attaching multiple handlers in 1 call</b><br>
7974       * The method also allows for a single argument to be passed which is a config object containing properties
7975      * which specify multiple handlers.
7976      * <p>
7977      * Code:<pre><code>
7978 el.on({
7979     'click' : {
7980         fn: this.onClick
7981         scope: this,
7982         delay: 100
7983     },
7984     'mouseover' : {
7985         fn: this.onMouseOver
7986         scope: this
7987     },
7988     'mouseout' : {
7989         fn: this.onMouseOut
7990         scope: this
7991     }
7992 });</code></pre>
7993      * <p>
7994      * Or a shorthand syntax:<br>
7995      * Code:<pre><code>
7996 el.on({
7997     'click' : this.onClick,
7998     'mouseover' : this.onMouseOver,
7999     'mouseout' : this.onMouseOut
8000     scope: this
8001 });</code></pre>
8002      */
8003     pub.on = pub.addListener;
8004     pub.un = pub.removeListener;
8005
8006     pub.stoppedMouseDownEvent = new Roo.util.Event();
8007     return pub;
8008 }();
8009 /**
8010   * Fires when the document is ready (before onload and before images are loaded).  Shorthand of {@link Roo.EventManager#onDocumentReady}.
8011   * @param {Function} fn        The method the event invokes
8012   * @param {Object}   scope    An  object that becomes the scope of the handler
8013   * @param {boolean}  override If true, the obj passed in becomes
8014   *                             the execution scope of the listener
8015   * @member Roo
8016   * @method onReady
8017  */
8018 Roo.onReady = Roo.EventManager.onDocumentReady;
8019
8020 Roo.onReady(function(){
8021     var bd = Roo.get(document.body);
8022     if(!bd){ return; }
8023
8024     var cls = [
8025             Roo.isIE ? "roo-ie"
8026             : Roo.isIE11 ? "roo-ie11"
8027             : Roo.isEdge ? "roo-edge"
8028             : Roo.isGecko ? "roo-gecko"
8029             : Roo.isOpera ? "roo-opera"
8030             : Roo.isSafari ? "roo-safari" : ""];
8031
8032     if(Roo.isMac){
8033         cls.push("roo-mac");
8034     }
8035     if(Roo.isLinux){
8036         cls.push("roo-linux");
8037     }
8038     if(Roo.isIOS){
8039         cls.push("roo-ios");
8040     }
8041     if(Roo.isTouch){
8042         cls.push("roo-touch");
8043     }
8044     if(Roo.isBorderBox){
8045         cls.push('roo-border-box');
8046     }
8047     if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
8048         var p = bd.dom.parentNode;
8049         if(p){
8050             p.className += ' roo-strict';
8051         }
8052     }
8053     bd.addClass(cls.join(' '));
8054 });
8055
8056 /**
8057  * @class Roo.EventObject
8058  * EventObject exposes the Yahoo! UI Event functionality directly on the object
8059  * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code 
8060  * Example:
8061  * <pre><code>
8062  function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
8063     e.preventDefault();
8064     var target = e.getTarget();
8065     ...
8066  }
8067  var myDiv = Roo.get("myDiv");
8068  myDiv.on("click", handleClick);
8069  //or
8070  Roo.EventManager.on("myDiv", 'click', handleClick);
8071  Roo.EventManager.addListener("myDiv", 'click', handleClick);
8072  </code></pre>
8073  * @static
8074  */
8075 Roo.EventObject = function(){
8076     
8077     var E = Roo.lib.Event;
8078     
8079     // safari keypress events for special keys return bad keycodes
8080     var safariKeys = {
8081         63234 : 37, // left
8082         63235 : 39, // right
8083         63232 : 38, // up
8084         63233 : 40, // down
8085         63276 : 33, // page up
8086         63277 : 34, // page down
8087         63272 : 46, // delete
8088         63273 : 36, // home
8089         63275 : 35  // end
8090     };
8091
8092     // normalize button clicks
8093     var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
8094                 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
8095
8096     Roo.EventObjectImpl = function(e){
8097         if(e){
8098             this.setEvent(e.browserEvent || e);
8099         }
8100     };
8101     Roo.EventObjectImpl.prototype = {
8102         /**
8103          * Used to fix doc tools.
8104          * @scope Roo.EventObject.prototype
8105          */
8106             
8107
8108         
8109         
8110         /** The normal browser event */
8111         browserEvent : null,
8112         /** The button pressed in a mouse event */
8113         button : -1,
8114         /** True if the shift key was down during the event */
8115         shiftKey : false,
8116         /** True if the control key was down during the event */
8117         ctrlKey : false,
8118         /** True if the alt key was down during the event */
8119         altKey : false,
8120
8121         /** Key constant 
8122         * @type Number */
8123         BACKSPACE : 8,
8124         /** Key constant 
8125         * @type Number */
8126         TAB : 9,
8127         /** Key constant 
8128         * @type Number */
8129         RETURN : 13,
8130         /** Key constant 
8131         * @type Number */
8132         ENTER : 13,
8133         /** Key constant 
8134         * @type Number */
8135         SHIFT : 16,
8136         /** Key constant 
8137         * @type Number */
8138         CONTROL : 17,
8139         /** Key constant 
8140         * @type Number */
8141         ESC : 27,
8142         /** Key constant 
8143         * @type Number */
8144         SPACE : 32,
8145         /** Key constant 
8146         * @type Number */
8147         PAGEUP : 33,
8148         /** Key constant 
8149         * @type Number */
8150         PAGEDOWN : 34,
8151         /** Key constant 
8152         * @type Number */
8153         END : 35,
8154         /** Key constant 
8155         * @type Number */
8156         HOME : 36,
8157         /** Key constant 
8158         * @type Number */
8159         LEFT : 37,
8160         /** Key constant 
8161         * @type Number */
8162         UP : 38,
8163         /** Key constant 
8164         * @type Number */
8165         RIGHT : 39,
8166         /** Key constant 
8167         * @type Number */
8168         DOWN : 40,
8169         /** Key constant 
8170         * @type Number */
8171         DELETE : 46,
8172         /** Key constant 
8173         * @type Number */
8174         F5 : 116,
8175
8176            /** @private */
8177         setEvent : function(e){
8178             if(e == this || (e && e.browserEvent)){ // already wrapped
8179                 return e;
8180             }
8181             this.browserEvent = e;
8182             if(e){
8183                 // normalize buttons
8184                 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
8185                 if(e.type == 'click' && this.button == -1){
8186                     this.button = 0;
8187                 }
8188                 this.type = e.type;
8189                 this.shiftKey = e.shiftKey;
8190                 // mac metaKey behaves like ctrlKey
8191                 this.ctrlKey = e.ctrlKey || e.metaKey;
8192                 this.altKey = e.altKey;
8193                 // in getKey these will be normalized for the mac
8194                 this.keyCode = e.keyCode;
8195                 // keyup warnings on firefox.
8196                 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
8197                 // cache the target for the delayed and or buffered events
8198                 this.target = E.getTarget(e);
8199                 // same for XY
8200                 this.xy = E.getXY(e);
8201             }else{
8202                 this.button = -1;
8203                 this.shiftKey = false;
8204                 this.ctrlKey = false;
8205                 this.altKey = false;
8206                 this.keyCode = 0;
8207                 this.charCode =0;
8208                 this.target = null;
8209                 this.xy = [0, 0];
8210             }
8211             return this;
8212         },
8213
8214         /**
8215          * Stop the event (preventDefault and stopPropagation)
8216          */
8217         stopEvent : function(){
8218             if(this.browserEvent){
8219                 if(this.browserEvent.type == 'mousedown'){
8220                     Roo.EventManager.stoppedMouseDownEvent.fire(this);
8221                 }
8222                 E.stopEvent(this.browserEvent);
8223             }
8224         },
8225
8226         /**
8227          * Prevents the browsers default handling of the event.
8228          */
8229         preventDefault : function(){
8230             if(this.browserEvent){
8231                 E.preventDefault(this.browserEvent);
8232             }
8233         },
8234
8235         /** @private */
8236         isNavKeyPress : function(){
8237             var k = this.keyCode;
8238             k = Roo.isSafari ? (safariKeys[k] || k) : k;
8239             return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
8240         },
8241
8242         isSpecialKey : function(){
8243             var k = this.keyCode;
8244             return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13  || k == 40 || k == 27 ||
8245             (k == 16) || (k == 17) ||
8246             (k >= 18 && k <= 20) ||
8247             (k >= 33 && k <= 35) ||
8248             (k >= 36 && k <= 39) ||
8249             (k >= 44 && k <= 45);
8250         },
8251         /**
8252          * Cancels bubbling of the event.
8253          */
8254         stopPropagation : function(){
8255             if(this.browserEvent){
8256                 if(this.type == 'mousedown'){
8257                     Roo.EventManager.stoppedMouseDownEvent.fire(this);
8258                 }
8259                 E.stopPropagation(this.browserEvent);
8260             }
8261         },
8262
8263         /**
8264          * Gets the key code for the event.
8265          * @return {Number}
8266          */
8267         getCharCode : function(){
8268             return this.charCode || this.keyCode;
8269         },
8270
8271         /**
8272          * Returns a normalized keyCode for the event.
8273          * @return {Number} The key code
8274          */
8275         getKey : function(){
8276             var k = this.keyCode || this.charCode;
8277             return Roo.isSafari ? (safariKeys[k] || k) : k;
8278         },
8279
8280         /**
8281          * Gets the x coordinate of the event.
8282          * @return {Number}
8283          */
8284         getPageX : function(){
8285             return this.xy[0];
8286         },
8287
8288         /**
8289          * Gets the y coordinate of the event.
8290          * @return {Number}
8291          */
8292         getPageY : function(){
8293             return this.xy[1];
8294         },
8295
8296         /**
8297          * Gets the time of the event.
8298          * @return {Number}
8299          */
8300         getTime : function(){
8301             if(this.browserEvent){
8302                 return E.getTime(this.browserEvent);
8303             }
8304             return null;
8305         },
8306
8307         /**
8308          * Gets the page coordinates of the event.
8309          * @return {Array} The xy values like [x, y]
8310          */
8311         getXY : function(){
8312             return this.xy;
8313         },
8314
8315         /**
8316          * Gets the target for the event.
8317          * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
8318          * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8319                 search as a number or element (defaults to 10 || document.body)
8320          * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8321          * @return {HTMLelement}
8322          */
8323         getTarget : function(selector, maxDepth, returnEl){
8324             return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
8325         },
8326         /**
8327          * Gets the related target.
8328          * @return {HTMLElement}
8329          */
8330         getRelatedTarget : function(){
8331             if(this.browserEvent){
8332                 return E.getRelatedTarget(this.browserEvent);
8333             }
8334             return null;
8335         },
8336
8337         /**
8338          * Normalizes mouse wheel delta across browsers
8339          * @return {Number} The delta
8340          */
8341         getWheelDelta : function(){
8342             var e = this.browserEvent;
8343             var delta = 0;
8344             if(e.wheelDelta){ /* IE/Opera. */
8345                 delta = e.wheelDelta/120;
8346             }else if(e.detail){ /* Mozilla case. */
8347                 delta = -e.detail/3;
8348             }
8349             return delta;
8350         },
8351
8352         /**
8353          * Returns true if the control, meta, shift or alt key was pressed during this event.
8354          * @return {Boolean}
8355          */
8356         hasModifier : function(){
8357             return !!((this.ctrlKey || this.altKey) || this.shiftKey);
8358         },
8359
8360         /**
8361          * Returns true if the target of this event equals el or is a child of el
8362          * @param {String/HTMLElement/Element} el
8363          * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
8364          * @return {Boolean}
8365          */
8366         within : function(el, related){
8367             var t = this[related ? "getRelatedTarget" : "getTarget"]();
8368             return t && Roo.fly(el).contains(t);
8369         },
8370
8371         getPoint : function(){
8372             return new Roo.lib.Point(this.xy[0], this.xy[1]);
8373         }
8374     };
8375
8376     return new Roo.EventObjectImpl();
8377 }();
8378             
8379     /*
8380  * Based on:
8381  * Ext JS Library 1.1.1
8382  * Copyright(c) 2006-2007, Ext JS, LLC.
8383  *
8384  * Originally Released Under LGPL - original licence link has changed is not relivant.
8385  *
8386  * Fork - LGPL
8387  * <script type="text/javascript">
8388  */
8389
8390  
8391 // was in Composite Element!??!?!
8392  
8393 (function(){
8394     var D = Roo.lib.Dom;
8395     var E = Roo.lib.Event;
8396     var A = Roo.lib.Anim;
8397
8398     // local style camelizing for speed
8399     var propCache = {};
8400     var camelRe = /(-[a-z])/gi;
8401     var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
8402     var view = document.defaultView;
8403
8404 /**
8405  * @class Roo.Element
8406  * Represents an Element in the DOM.<br><br>
8407  * Usage:<br>
8408 <pre><code>
8409 var el = Roo.get("my-div");
8410
8411 // or with getEl
8412 var el = getEl("my-div");
8413
8414 // or with a DOM element
8415 var el = Roo.get(myDivElement);
8416 </code></pre>
8417  * Using Roo.get() or getEl() instead of calling the constructor directly ensures you get the same object
8418  * each call instead of constructing a new one.<br><br>
8419  * <b>Animations</b><br />
8420  * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
8421  * should either be a boolean (true) or an object literal with animation options. The animation options are:
8422 <pre>
8423 Option    Default   Description
8424 --------- --------  ---------------------------------------------
8425 duration  .35       The duration of the animation in seconds
8426 easing    easeOut   The YUI easing method
8427 callback  none      A function to execute when the anim completes
8428 scope     this      The scope (this) of the callback function
8429 </pre>
8430 * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
8431 * manipulate the animation. Here's an example:
8432 <pre><code>
8433 var el = Roo.get("my-div");
8434
8435 // no animation
8436 el.setWidth(100);
8437
8438 // default animation
8439 el.setWidth(100, true);
8440
8441 // animation with some options set
8442 el.setWidth(100, {
8443     duration: 1,
8444     callback: this.foo,
8445     scope: this
8446 });
8447
8448 // using the "anim" property to get the Anim object
8449 var opt = {
8450     duration: 1,
8451     callback: this.foo,
8452     scope: this
8453 };
8454 el.setWidth(100, opt);
8455 ...
8456 if(opt.anim.isAnimated()){
8457     opt.anim.stop();
8458 }
8459 </code></pre>
8460 * <b> Composite (Collections of) Elements</b><br />
8461  * For working with collections of Elements, see <a href="Roo.CompositeElement.html">Roo.CompositeElement</a>
8462  * @constructor Create a new Element directly.
8463  * @param {String/HTMLElement} element
8464  * @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).
8465  */
8466     Roo.Element = function(element, forceNew)
8467     {
8468         var dom = typeof element == "string" ?
8469                 document.getElementById(element) : element;
8470         
8471         this.listeners = {};
8472         
8473         if(!dom){ // invalid id/element
8474             return null;
8475         }
8476         var id = dom.id;
8477         if(forceNew !== true && id && Roo.Element.cache[id]){ // element object already exists
8478             return Roo.Element.cache[id];
8479         }
8480
8481         /**
8482          * The DOM element
8483          * @type HTMLElement
8484          */
8485         this.dom = dom;
8486
8487         /**
8488          * The DOM element ID
8489          * @type String
8490          */
8491         this.id = id || Roo.id(dom);
8492         
8493         return this; // assumed for cctor?
8494     };
8495
8496     var El = Roo.Element;
8497
8498     El.prototype = {
8499         /**
8500          * The element's default display mode  (defaults to "") 
8501          * @type String
8502          */
8503         originalDisplay : "",
8504
8505         
8506         // note this is overridden in BS version..
8507         visibilityMode : 1, 
8508         /**
8509          * The default unit to append to CSS values where a unit isn't provided (defaults to px).
8510          * @type String
8511          */
8512         defaultUnit : "px",
8513         
8514         /**
8515          * Sets the element's visibility mode. When setVisible() is called it
8516          * will use this to determine whether to set the visibility or the display property.
8517          * @param visMode Element.VISIBILITY or Element.DISPLAY
8518          * @return {Roo.Element} this
8519          */
8520         setVisibilityMode : function(visMode){
8521             this.visibilityMode = visMode;
8522             return this;
8523         },
8524         /**
8525          * Convenience method for setVisibilityMode(Element.DISPLAY)
8526          * @param {String} display (optional) What to set display to when visible
8527          * @return {Roo.Element} this
8528          */
8529         enableDisplayMode : function(display){
8530             this.setVisibilityMode(El.DISPLAY);
8531             if(typeof display != "undefined") { this.originalDisplay = display; }
8532             return this;
8533         },
8534
8535         /**
8536          * 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)
8537          * @param {String} selector The simple selector to test
8538          * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8539                 search as a number or element (defaults to 10 || document.body)
8540          * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8541          * @return {HTMLElement} The matching DOM node (or null if no match was found)
8542          */
8543         findParent : function(simpleSelector, maxDepth, returnEl){
8544             var p = this.dom, b = document.body, depth = 0, dq = Roo.DomQuery, stopEl;
8545             maxDepth = maxDepth || 50;
8546             if(typeof maxDepth != "number"){
8547                 stopEl = Roo.getDom(maxDepth);
8548                 maxDepth = 10;
8549             }
8550             while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
8551                 if(dq.is(p, simpleSelector)){
8552                     return returnEl ? Roo.get(p) : p;
8553                 }
8554                 depth++;
8555                 p = p.parentNode;
8556             }
8557             return null;
8558         },
8559
8560
8561         /**
8562          * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
8563          * @param {String} selector The simple selector to test
8564          * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8565                 search as a number or element (defaults to 10 || document.body)
8566          * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8567          * @return {HTMLElement} The matching DOM node (or null if no match was found)
8568          */
8569         findParentNode : function(simpleSelector, maxDepth, returnEl){
8570             var p = Roo.fly(this.dom.parentNode, '_internal');
8571             return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
8572         },
8573         
8574         /**
8575          * Looks at  the scrollable parent element
8576          */
8577         findScrollableParent : function()
8578         {
8579             var overflowRegex = /(auto|scroll)/;
8580             
8581             if(this.getStyle('position') === 'fixed'){
8582                 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8583             }
8584             
8585             var excludeStaticParent = this.getStyle('position') === "absolute";
8586             
8587             for (var parent = this; (parent = Roo.get(parent.dom.parentNode));){
8588                 
8589                 if (excludeStaticParent && parent.getStyle('position') === "static") {
8590                     continue;
8591                 }
8592                 
8593                 if (overflowRegex.test(parent.getStyle('overflow') + parent.getStyle('overflow-x') + parent.getStyle('overflow-y'))){
8594                     return parent;
8595                 }
8596                 
8597                 if(parent.dom.nodeName.toLowerCase() == 'body'){
8598                     return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8599                 }
8600             }
8601             
8602             return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8603         },
8604
8605         /**
8606          * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
8607          * This is a shortcut for findParentNode() that always returns an Roo.Element.
8608          * @param {String} selector The simple selector to test
8609          * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8610                 search as a number or element (defaults to 10 || document.body)
8611          * @return {Roo.Element} The matching DOM node (or null if no match was found)
8612          */
8613         up : function(simpleSelector, maxDepth){
8614             return this.findParentNode(simpleSelector, maxDepth, true);
8615         },
8616
8617
8618
8619         /**
8620          * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
8621          * @param {String} selector The simple selector to test
8622          * @return {Boolean} True if this element matches the selector, else false
8623          */
8624         is : function(simpleSelector){
8625             return Roo.DomQuery.is(this.dom, simpleSelector);
8626         },
8627
8628         /**
8629          * Perform animation on this element.
8630          * @param {Object} args The YUI animation control args
8631          * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35)
8632          * @param {Function} onComplete (optional) Function to call when animation completes
8633          * @param {String} easing (optional) Easing method to use (defaults to 'easeOut')
8634          * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
8635          * @return {Roo.Element} this
8636          */
8637         animate : function(args, duration, onComplete, easing, animType){
8638             this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
8639             return this;
8640         },
8641
8642         /*
8643          * @private Internal animation call
8644          */
8645         anim : function(args, opt, animType, defaultDur, defaultEase, cb){
8646             animType = animType || 'run';
8647             opt = opt || {};
8648             var anim = Roo.lib.Anim[animType](
8649                 this.dom, args,
8650                 (opt.duration || defaultDur) || .35,
8651                 (opt.easing || defaultEase) || 'easeOut',
8652                 function(){
8653                     Roo.callback(cb, this);
8654                     Roo.callback(opt.callback, opt.scope || this, [this, opt]);
8655                 },
8656                 this
8657             );
8658             opt.anim = anim;
8659             return anim;
8660         },
8661
8662         // private legacy anim prep
8663         preanim : function(a, i){
8664             return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
8665         },
8666
8667         /**
8668          * Removes worthless text nodes
8669          * @param {Boolean} forceReclean (optional) By default the element
8670          * keeps track if it has been cleaned already so
8671          * you can call this over and over. However, if you update the element and
8672          * need to force a reclean, you can pass true.
8673          */
8674         clean : function(forceReclean){
8675             if(this.isCleaned && forceReclean !== true){
8676                 return this;
8677             }
8678             var ns = /\S/;
8679             var d = this.dom, n = d.firstChild, ni = -1;
8680             while(n){
8681                 var nx = n.nextSibling;
8682                 if(n.nodeType == 3 && !ns.test(n.nodeValue)){
8683                     d.removeChild(n);
8684                 }else{
8685                     n.nodeIndex = ++ni;
8686                 }
8687                 n = nx;
8688             }
8689             this.isCleaned = true;
8690             return this;
8691         },
8692
8693         // private
8694         calcOffsetsTo : function(el){
8695             el = Roo.get(el);
8696             var d = el.dom;
8697             var restorePos = false;
8698             if(el.getStyle('position') == 'static'){
8699                 el.position('relative');
8700                 restorePos = true;
8701             }
8702             var x = 0, y =0;
8703             var op = this.dom;
8704             while(op && op != d && op.tagName != 'HTML'){
8705                 x+= op.offsetLeft;
8706                 y+= op.offsetTop;
8707                 op = op.offsetParent;
8708             }
8709             if(restorePos){
8710                 el.position('static');
8711             }
8712             return [x, y];
8713         },
8714
8715         /**
8716          * Scrolls this element into view within the passed container.
8717          * @param {String/HTMLElement/Element} container (optional) The container element to scroll (defaults to document.body)
8718          * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
8719          * @return {Roo.Element} this
8720          */
8721         scrollIntoView : function(container, hscroll){
8722             var c = Roo.getDom(container) || document.body;
8723             var el = this.dom;
8724
8725             var o = this.calcOffsetsTo(c),
8726                 l = o[0],
8727                 t = o[1],
8728                 b = t+el.offsetHeight,
8729                 r = l+el.offsetWidth;
8730
8731             var ch = c.clientHeight;
8732             var ct = parseInt(c.scrollTop, 10);
8733             var cl = parseInt(c.scrollLeft, 10);
8734             var cb = ct + ch;
8735             var cr = cl + c.clientWidth;
8736
8737             if(t < ct){
8738                 c.scrollTop = t;
8739             }else if(b > cb){
8740                 c.scrollTop = b-ch;
8741             }
8742
8743             if(hscroll !== false){
8744                 if(l < cl){
8745                     c.scrollLeft = l;
8746                 }else if(r > cr){
8747                     c.scrollLeft = r-c.clientWidth;
8748                 }
8749             }
8750             return this;
8751         },
8752
8753         // private
8754         scrollChildIntoView : function(child, hscroll){
8755             Roo.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
8756         },
8757
8758         /**
8759          * Measures the element's content height and updates height to match. Note: this function uses setTimeout so
8760          * the new height may not be available immediately.
8761          * @param {Boolean} animate (optional) Animate the transition (defaults to false)
8762          * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
8763          * @param {Function} onComplete (optional) Function to call when animation completes
8764          * @param {String} easing (optional) Easing method to use (defaults to easeOut)
8765          * @return {Roo.Element} this
8766          */
8767         autoHeight : function(animate, duration, onComplete, easing){
8768             var oldHeight = this.getHeight();
8769             this.clip();
8770             this.setHeight(1); // force clipping
8771             setTimeout(function(){
8772                 var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
8773                 if(!animate){
8774                     this.setHeight(height);
8775                     this.unclip();
8776                     if(typeof onComplete == "function"){
8777                         onComplete();
8778                     }
8779                 }else{
8780                     this.setHeight(oldHeight); // restore original height
8781                     this.setHeight(height, animate, duration, function(){
8782                         this.unclip();
8783                         if(typeof onComplete == "function") { onComplete(); }
8784                     }.createDelegate(this), easing);
8785                 }
8786             }.createDelegate(this), 0);
8787             return this;
8788         },
8789
8790         /**
8791          * Returns true if this element is an ancestor of the passed element
8792          * @param {HTMLElement/String} el The element to check
8793          * @return {Boolean} True if this element is an ancestor of el, else false
8794          */
8795         contains : function(el){
8796             if(!el){return false;}
8797             return D.isAncestor(this.dom, el.dom ? el.dom : el);
8798         },
8799
8800         /**
8801          * Checks whether the element is currently visible using both visibility and display properties.
8802          * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
8803          * @return {Boolean} True if the element is currently visible, else false
8804          */
8805         isVisible : function(deep) {
8806             var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
8807             if(deep !== true || !vis){
8808                 return vis;
8809             }
8810             var p = this.dom.parentNode;
8811             while(p && p.tagName.toLowerCase() != "body"){
8812                 if(!Roo.fly(p, '_isVisible').isVisible()){
8813                     return false;
8814                 }
8815                 p = p.parentNode;
8816             }
8817             return true;
8818         },
8819
8820         /**
8821          * Creates a {@link Roo.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
8822          * @param {String} selector The CSS selector
8823          * @param {Boolean} unique (optional) True to create a unique Roo.Element for each child (defaults to false, which creates a single shared flyweight object)
8824          * @return {CompositeElement/CompositeElementLite} The composite element
8825          */
8826         select : function(selector, unique){
8827             return El.select(selector, unique, this.dom);
8828         },
8829
8830         /**
8831          * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
8832          * @param {String} selector The CSS selector
8833          * @return {Array} An array of the matched nodes
8834          */
8835         query : function(selector, unique){
8836             return Roo.DomQuery.select(selector, this.dom);
8837         },
8838
8839         /**
8840          * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
8841          * @param {String} selector The CSS selector
8842          * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8843          * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8844          */
8845         child : function(selector, returnDom){
8846             var n = Roo.DomQuery.selectNode(selector, this.dom);
8847             return returnDom ? n : Roo.get(n);
8848         },
8849
8850         /**
8851          * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
8852          * @param {String} selector The CSS selector
8853          * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8854          * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8855          */
8856         down : function(selector, returnDom){
8857             var n = Roo.DomQuery.selectNode(" > " + selector, this.dom);
8858             return returnDom ? n : Roo.get(n);
8859         },
8860
8861         /**
8862          * Initializes a {@link Roo.dd.DD} drag drop object for this element.
8863          * @param {String} group The group the DD object is member of
8864          * @param {Object} config The DD config object
8865          * @param {Object} overrides An object containing methods to override/implement on the DD object
8866          * @return {Roo.dd.DD} The DD object
8867          */
8868         initDD : function(group, config, overrides){
8869             var dd = new Roo.dd.DD(Roo.id(this.dom), group, config);
8870             return Roo.apply(dd, overrides);
8871         },
8872
8873         /**
8874          * Initializes a {@link Roo.dd.DDProxy} object for this element.
8875          * @param {String} group The group the DDProxy object is member of
8876          * @param {Object} config The DDProxy config object
8877          * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
8878          * @return {Roo.dd.DDProxy} The DDProxy object
8879          */
8880         initDDProxy : function(group, config, overrides){
8881             var dd = new Roo.dd.DDProxy(Roo.id(this.dom), group, config);
8882             return Roo.apply(dd, overrides);
8883         },
8884
8885         /**
8886          * Initializes a {@link Roo.dd.DDTarget} object for this element.
8887          * @param {String} group The group the DDTarget object is member of
8888          * @param {Object} config The DDTarget config object
8889          * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
8890          * @return {Roo.dd.DDTarget} The DDTarget object
8891          */
8892         initDDTarget : function(group, config, overrides){
8893             var dd = new Roo.dd.DDTarget(Roo.id(this.dom), group, config);
8894             return Roo.apply(dd, overrides);
8895         },
8896
8897         /**
8898          * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
8899          * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
8900          * @param {Boolean} visible Whether the element is visible
8901          * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8902          * @return {Roo.Element} this
8903          */
8904          setVisible : function(visible, animate){
8905             if(!animate || !A){
8906                 if(this.visibilityMode == El.DISPLAY){
8907                     this.setDisplayed(visible);
8908                 }else{
8909                     this.fixDisplay();
8910                     this.dom.style.visibility = visible ? "visible" : "hidden";
8911                 }
8912             }else{
8913                 // closure for composites
8914                 var dom = this.dom;
8915                 var visMode = this.visibilityMode;
8916                 if(visible){
8917                     this.setOpacity(.01);
8918                     this.setVisible(true);
8919                 }
8920                 this.anim({opacity: { to: (visible?1:0) }},
8921                       this.preanim(arguments, 1),
8922                       null, .35, 'easeIn', function(){
8923                          if(!visible){
8924                              if(visMode == El.DISPLAY){
8925                                  dom.style.display = "none";
8926                              }else{
8927                                  dom.style.visibility = "hidden";
8928                              }
8929                              Roo.get(dom).setOpacity(1);
8930                          }
8931                      });
8932             }
8933             return this;
8934         },
8935
8936         /**
8937          * Returns true if display is not "none"
8938          * @return {Boolean}
8939          */
8940         isDisplayed : function() {
8941             return this.getStyle("display") != "none";
8942         },
8943
8944         /**
8945          * Toggles the element's visibility or display, depending on visibility mode.
8946          * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8947          * @return {Roo.Element} this
8948          */
8949         toggle : function(animate){
8950             this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
8951             return this;
8952         },
8953
8954         /**
8955          * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
8956          * @param {Boolean} value Boolean value to display the element using its default display, or a string to set the display directly
8957          * @return {Roo.Element} this
8958          */
8959         setDisplayed : function(value) {
8960             if(typeof value == "boolean"){
8961                value = value ? this.originalDisplay : "none";
8962             }
8963             this.setStyle("display", value);
8964             return this;
8965         },
8966
8967         /**
8968          * Tries to focus the element. Any exceptions are caught and ignored.
8969          * @return {Roo.Element} this
8970          */
8971         focus : function() {
8972             try{
8973                 this.dom.focus();
8974             }catch(e){}
8975             return this;
8976         },
8977
8978         /**
8979          * Tries to blur the element. Any exceptions are caught and ignored.
8980          * @return {Roo.Element} this
8981          */
8982         blur : function() {
8983             try{
8984                 this.dom.blur();
8985             }catch(e){}
8986             return this;
8987         },
8988
8989         /**
8990          * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
8991          * @param {String/Array} className The CSS class to add, or an array of classes
8992          * @return {Roo.Element} this
8993          */
8994         addClass : function(className){
8995             if(className instanceof Array){
8996                 for(var i = 0, len = className.length; i < len; i++) {
8997                     this.addClass(className[i]);
8998                 }
8999             }else{
9000                 if(className && !this.hasClass(className)){
9001                     if (this.dom instanceof SVGElement) {
9002                         this.dom.className.baseVal =this.dom.className.baseVal  + " " + className;
9003                     } else {
9004                         this.dom.className = this.dom.className + " " + className;
9005                     }
9006                 }
9007             }
9008             return this;
9009         },
9010
9011         /**
9012          * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
9013          * @param {String/Array} className The CSS class to add, or an array of classes
9014          * @return {Roo.Element} this
9015          */
9016         radioClass : function(className){
9017             var siblings = this.dom.parentNode.childNodes;
9018             for(var i = 0; i < siblings.length; i++) {
9019                 var s = siblings[i];
9020                 if(s.nodeType == 1){
9021                     Roo.get(s).removeClass(className);
9022                 }
9023             }
9024             this.addClass(className);
9025             return this;
9026         },
9027
9028         /**
9029          * Removes one or more CSS classes from the element.
9030          * @param {String/Array} className The CSS class to remove, or an array of classes
9031          * @return {Roo.Element} this
9032          */
9033         removeClass : function(className){
9034             
9035             var cn = this.dom instanceof SVGElement ? this.dom.className.baseVal : this.dom.className;
9036             if(!className || !cn){
9037                 return this;
9038             }
9039             if(className instanceof Array){
9040                 for(var i = 0, len = className.length; i < len; i++) {
9041                     this.removeClass(className[i]);
9042                 }
9043             }else{
9044                 if(this.hasClass(className)){
9045                     var re = this.classReCache[className];
9046                     if (!re) {
9047                        re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
9048                        this.classReCache[className] = re;
9049                     }
9050                     if (this.dom instanceof SVGElement) {
9051                         this.dom.className.baseVal = cn.replace(re, " ");
9052                     } else {
9053                         this.dom.className = cn.replace(re, " ");
9054                     }
9055                 }
9056             }
9057             return this;
9058         },
9059
9060         // private
9061         classReCache: {},
9062
9063         /**
9064          * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
9065          * @param {String} className The CSS class to toggle
9066          * @return {Roo.Element} this
9067          */
9068         toggleClass : function(className){
9069             if(this.hasClass(className)){
9070                 this.removeClass(className);
9071             }else{
9072                 this.addClass(className);
9073             }
9074             return this;
9075         },
9076
9077         /**
9078          * Checks if the specified CSS class exists on this element's DOM node.
9079          * @param {String} className The CSS class to check for
9080          * @return {Boolean} True if the class exists, else false
9081          */
9082         hasClass : function(className){
9083             if (this.dom instanceof SVGElement) {
9084                 return className && (' '+this.dom.className.baseVal +' ').indexOf(' '+className+' ') != -1; 
9085             } 
9086             return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
9087         },
9088
9089         /**
9090          * Replaces a CSS class on the element with another.  If the old name does not exist, the new name will simply be added.
9091          * @param {String} oldClassName The CSS class to replace
9092          * @param {String} newClassName The replacement CSS class
9093          * @return {Roo.Element} this
9094          */
9095         replaceClass : function(oldClassName, newClassName){
9096             this.removeClass(oldClassName);
9097             this.addClass(newClassName);
9098             return this;
9099         },
9100
9101         /**
9102          * Returns an object with properties matching the styles requested.
9103          * For example, el.getStyles('color', 'font-size', 'width') might return
9104          * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
9105          * @param {String} style1 A style name
9106          * @param {String} style2 A style name
9107          * @param {String} etc.
9108          * @return {Object} The style object
9109          */
9110         getStyles : function(){
9111             var a = arguments, len = a.length, r = {};
9112             for(var i = 0; i < len; i++){
9113                 r[a[i]] = this.getStyle(a[i]);
9114             }
9115             return r;
9116         },
9117
9118         /**
9119          * Normalizes currentStyle and computedStyle. This is not YUI getStyle, it is an optimised version.
9120          * @param {String} property The style property whose value is returned.
9121          * @return {String} The current value of the style property for this element.
9122          */
9123         getStyle : function(){
9124             return view && view.getComputedStyle ?
9125                 function(prop){
9126                     var el = this.dom, v, cs, camel;
9127                     if(prop == 'float'){
9128                         prop = "cssFloat";
9129                     }
9130                     if(el.style && (v = el.style[prop])){
9131                         return v;
9132                     }
9133                     if(cs = view.getComputedStyle(el, "")){
9134                         if(!(camel = propCache[prop])){
9135                             camel = propCache[prop] = prop.replace(camelRe, camelFn);
9136                         }
9137                         return cs[camel];
9138                     }
9139                     return null;
9140                 } :
9141                 function(prop){
9142                     var el = this.dom, v, cs, camel;
9143                     if(prop == 'opacity'){
9144                         if(typeof el.style.filter == 'string'){
9145                             var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
9146                             if(m){
9147                                 var fv = parseFloat(m[1]);
9148                                 if(!isNaN(fv)){
9149                                     return fv ? fv / 100 : 0;
9150                                 }
9151                             }
9152                         }
9153                         return 1;
9154                     }else if(prop == 'float'){
9155                         prop = "styleFloat";
9156                     }
9157                     if(!(camel = propCache[prop])){
9158                         camel = propCache[prop] = prop.replace(camelRe, camelFn);
9159                     }
9160                     if(v = el.style[camel]){
9161                         return v;
9162                     }
9163                     if(cs = el.currentStyle){
9164                         return cs[camel];
9165                     }
9166                     return null;
9167                 };
9168         }(),
9169
9170         /**
9171          * Wrapper for setting style properties, also takes single object parameter of multiple styles.
9172          * @param {String/Object} property The style property to be set, or an object of multiple styles.
9173          * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
9174          * @return {Roo.Element} this
9175          */
9176         setStyle : function(prop, value){
9177             if(typeof prop == "string"){
9178                 
9179                 if (prop == 'float') {
9180                     this.setStyle(Roo.isIE ? 'styleFloat'  : 'cssFloat', value);
9181                     return this;
9182                 }
9183                 
9184                 var camel;
9185                 if(!(camel = propCache[prop])){
9186                     camel = propCache[prop] = prop.replace(camelRe, camelFn);
9187                 }
9188                 
9189                 if(camel == 'opacity') {
9190                     this.setOpacity(value);
9191                 }else{
9192                     this.dom.style[camel] = value;
9193                 }
9194             }else{
9195                 for(var style in prop){
9196                     if(typeof prop[style] != "function"){
9197                        this.setStyle(style, prop[style]);
9198                     }
9199                 }
9200             }
9201             return this;
9202         },
9203
9204         /**
9205          * More flexible version of {@link #setStyle} for setting style properties.
9206          * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
9207          * a function which returns such a specification.
9208          * @return {Roo.Element} this
9209          */
9210         applyStyles : function(style){
9211             Roo.DomHelper.applyStyles(this.dom, style);
9212             return this;
9213         },
9214
9215         /**
9216           * 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).
9217           * @return {Number} The X position of the element
9218           */
9219         getX : function(){
9220             return D.getX(this.dom);
9221         },
9222
9223         /**
9224           * 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).
9225           * @return {Number} The Y position of the element
9226           */
9227         getY : function(){
9228             return D.getY(this.dom);
9229         },
9230
9231         /**
9232           * 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).
9233           * @return {Array} The XY position of the element
9234           */
9235         getXY : function(){
9236             return D.getXY(this.dom);
9237         },
9238
9239         /**
9240          * 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).
9241          * @param {Number} The X position of the element
9242          * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9243          * @return {Roo.Element} this
9244          */
9245         setX : function(x, animate){
9246             if(!animate || !A){
9247                 D.setX(this.dom, x);
9248             }else{
9249                 this.setXY([x, this.getY()], this.preanim(arguments, 1));
9250             }
9251             return this;
9252         },
9253
9254         /**
9255          * 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).
9256          * @param {Number} The Y position of the element
9257          * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9258          * @return {Roo.Element} this
9259          */
9260         setY : function(y, animate){
9261             if(!animate || !A){
9262                 D.setY(this.dom, y);
9263             }else{
9264                 this.setXY([this.getX(), y], this.preanim(arguments, 1));
9265             }
9266             return this;
9267         },
9268
9269         /**
9270          * Sets the element's left position directly using CSS style (instead of {@link #setX}).
9271          * @param {String} left The left CSS property value
9272          * @return {Roo.Element} this
9273          */
9274         setLeft : function(left){
9275             this.setStyle("left", this.addUnits(left));
9276             return this;
9277         },
9278
9279         /**
9280          * Sets the element's top position directly using CSS style (instead of {@link #setY}).
9281          * @param {String} top The top CSS property value
9282          * @return {Roo.Element} this
9283          */
9284         setTop : function(top){
9285             this.setStyle("top", this.addUnits(top));
9286             return this;
9287         },
9288
9289         /**
9290          * Sets the element's CSS right style.
9291          * @param {String} right The right CSS property value
9292          * @return {Roo.Element} this
9293          */
9294         setRight : function(right){
9295             this.setStyle("right", this.addUnits(right));
9296             return this;
9297         },
9298
9299         /**
9300          * Sets the element's CSS bottom style.
9301          * @param {String} bottom The bottom CSS property value
9302          * @return {Roo.Element} this
9303          */
9304         setBottom : function(bottom){
9305             this.setStyle("bottom", this.addUnits(bottom));
9306             return this;
9307         },
9308
9309         /**
9310          * Sets the position of the element in page coordinates, regardless of how the element is positioned.
9311          * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
9312          * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
9313          * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9314          * @return {Roo.Element} this
9315          */
9316         setXY : function(pos, animate){
9317             if(!animate || !A){
9318                 D.setXY(this.dom, pos);
9319             }else{
9320                 this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
9321             }
9322             return this;
9323         },
9324
9325         /**
9326          * Sets the position of the element in page coordinates, regardless of how the element is positioned.
9327          * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
9328          * @param {Number} x X value for new position (coordinates are page-based)
9329          * @param {Number} y Y value for new position (coordinates are page-based)
9330          * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9331          * @return {Roo.Element} this
9332          */
9333         setLocation : function(x, y, animate){
9334             this.setXY([x, y], this.preanim(arguments, 2));
9335             return this;
9336         },
9337
9338         /**
9339          * Sets the position of the element in page coordinates, regardless of how the element is positioned.
9340          * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
9341          * @param {Number} x X value for new position (coordinates are page-based)
9342          * @param {Number} y Y value for new position (coordinates are page-based)
9343          * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9344          * @return {Roo.Element} this
9345          */
9346         moveTo : function(x, y, animate){
9347             this.setXY([x, y], this.preanim(arguments, 2));
9348             return this;
9349         },
9350
9351         /**
9352          * Returns the region of the given element.
9353          * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
9354          * @return {Region} A Roo.lib.Region containing "top, left, bottom, right" member data.
9355          */
9356         getRegion : function(){
9357             return D.getRegion(this.dom);
9358         },
9359
9360         /**
9361          * Returns the offset height of the element
9362          * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
9363          * @return {Number} The element's height
9364          */
9365         getHeight : function(contentHeight){
9366             var h = this.dom.offsetHeight || 0;
9367             return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
9368         },
9369
9370         /**
9371          * Returns the offset width of the element
9372          * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
9373          * @return {Number} The element's width
9374          */
9375         getWidth : function(contentWidth){
9376             var w = this.dom.offsetWidth || 0;
9377             return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
9378         },
9379
9380         /**
9381          * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
9382          * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
9383          * if a height has not been set using CSS.
9384          * @return {Number}
9385          */
9386         getComputedHeight : function(){
9387             var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
9388             if(!h){
9389                 h = parseInt(this.getStyle('height'), 10) || 0;
9390                 if(!this.isBorderBox()){
9391                     h += this.getFrameWidth('tb');
9392                 }
9393             }
9394             return h;
9395         },
9396
9397         /**
9398          * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
9399          * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
9400          * if a width has not been set using CSS.
9401          * @return {Number}
9402          */
9403         getComputedWidth : function(){
9404             var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
9405             if(!w){
9406                 w = parseInt(this.getStyle('width'), 10) || 0;
9407                 if(!this.isBorderBox()){
9408                     w += this.getFrameWidth('lr');
9409                 }
9410             }
9411             return w;
9412         },
9413
9414         /**
9415          * Returns the size of the element.
9416          * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
9417          * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
9418          */
9419         getSize : function(contentSize){
9420             return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
9421         },
9422
9423         /**
9424          * Returns the width and height of the viewport.
9425          * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)}
9426          */
9427         getViewSize : function(){
9428             var d = this.dom, doc = document, aw = 0, ah = 0;
9429             if(d == doc || d == doc.body){
9430                 return {width : D.getViewWidth(), height: D.getViewHeight()};
9431             }else{
9432                 return {
9433                     width : d.clientWidth,
9434                     height: d.clientHeight
9435                 };
9436             }
9437         },
9438
9439         /**
9440          * Returns the value of the "value" attribute
9441          * @param {Boolean} asNumber true to parse the value as a number
9442          * @return {String/Number}
9443          */
9444         getValue : function(asNumber){
9445             return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
9446         },
9447
9448         // private
9449         adjustWidth : function(width){
9450             if(typeof width == "number"){
9451                 if(this.autoBoxAdjust && !this.isBorderBox()){
9452                    width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
9453                 }
9454                 if(width < 0){
9455                     width = 0;
9456                 }
9457             }
9458             return width;
9459         },
9460
9461         // private
9462         adjustHeight : function(height){
9463             if(typeof height == "number"){
9464                if(this.autoBoxAdjust && !this.isBorderBox()){
9465                    height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
9466                }
9467                if(height < 0){
9468                    height = 0;
9469                }
9470             }
9471             return height;
9472         },
9473
9474         /**
9475          * Set the width of the element
9476          * @param {Number} width The new width
9477          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9478          * @return {Roo.Element} this
9479          */
9480         setWidth : function(width, animate){
9481             width = this.adjustWidth(width);
9482             if(!animate || !A){
9483                 this.dom.style.width = this.addUnits(width);
9484             }else{
9485                 this.anim({width: {to: width}}, this.preanim(arguments, 1));
9486             }
9487             return this;
9488         },
9489
9490         /**
9491          * Set the height of the element
9492          * @param {Number} height The new height
9493          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9494          * @return {Roo.Element} this
9495          */
9496          setHeight : function(height, animate){
9497             height = this.adjustHeight(height);
9498             if(!animate || !A){
9499                 this.dom.style.height = this.addUnits(height);
9500             }else{
9501                 this.anim({height: {to: height}}, this.preanim(arguments, 1));
9502             }
9503             return this;
9504         },
9505
9506         /**
9507          * Set the size of the element. If animation is true, both width an height will be animated concurrently.
9508          * @param {Number} width The new width
9509          * @param {Number} height The new height
9510          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9511          * @return {Roo.Element} this
9512          */
9513          setSize : function(width, height, animate){
9514             if(typeof width == "object"){ // in case of object from getSize()
9515                 height = width.height; width = width.width;
9516             }
9517             width = this.adjustWidth(width); height = this.adjustHeight(height);
9518             if(!animate || !A){
9519                 this.dom.style.width = this.addUnits(width);
9520                 this.dom.style.height = this.addUnits(height);
9521             }else{
9522                 this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
9523             }
9524             return this;
9525         },
9526
9527         /**
9528          * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
9529          * @param {Number} x X value for new position (coordinates are page-based)
9530          * @param {Number} y Y value for new position (coordinates are page-based)
9531          * @param {Number} width The new width
9532          * @param {Number} height The new height
9533          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9534          * @return {Roo.Element} this
9535          */
9536         setBounds : function(x, y, width, height, animate){
9537             if(!animate || !A){
9538                 this.setSize(width, height);
9539                 this.setLocation(x, y);
9540             }else{
9541                 width = this.adjustWidth(width); height = this.adjustHeight(height);
9542                 this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
9543                               this.preanim(arguments, 4), 'motion');
9544             }
9545             return this;
9546         },
9547
9548         /**
9549          * 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.
9550          * @param {Roo.lib.Region} region The region to fill
9551          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9552          * @return {Roo.Element} this
9553          */
9554         setRegion : function(region, animate){
9555             this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
9556             return this;
9557         },
9558
9559         /**
9560          * Appends an event handler
9561          *
9562          * @param {String}   eventName     The type of event to append
9563          * @param {Function} fn        The method the event invokes
9564          * @param {Object} scope       (optional) The scope (this object) of the fn
9565          * @param {Object}   options   (optional)An object with standard {@link Roo.EventManager#addListener} options
9566          */
9567         addListener : function(eventName, fn, scope, options)
9568         {
9569             if (eventName == 'dblclick') { // doublclick (touchstart) - faked on touch.
9570                 this.addListener('touchstart', this.onTapHandler, this);
9571             }
9572             
9573             // we need to handle a special case where dom element is a svg element.
9574             // in this case we do not actua
9575             if (!this.dom) {
9576                 return;
9577             }
9578             
9579             if (this.dom instanceof SVGElement && !(this.dom instanceof SVGSVGElement)) {
9580                 if (typeof(this.listeners[eventName]) == 'undefined') {
9581                     this.listeners[eventName] =  new Roo.util.Event(this, eventName);
9582                 }
9583                 this.listeners[eventName].addListener(fn, scope, options);
9584                 return;
9585             }
9586             
9587                 
9588             Roo.EventManager.on(this.dom,  eventName, fn, scope || this, options);
9589             
9590             
9591         },
9592         tapedTwice : false,
9593         onTapHandler : function(event)
9594         {
9595             if(!this.tapedTwice) {
9596                 this.tapedTwice = true;
9597                 var s = this;
9598                 setTimeout( function() {
9599                     s.tapedTwice = false;
9600                 }, 300 );
9601                 return;
9602             }
9603             event.preventDefault();
9604             var revent = new MouseEvent('dblclick',  {
9605                 view: window,
9606                 bubbles: true,
9607                 cancelable: true
9608             });
9609              
9610             this.dom.dispatchEvent(revent);
9611             //action on double tap goes below
9612              
9613         }, 
9614  
9615         /**
9616          * Removes an event handler from this element
9617          * @param {String} eventName the type of event to remove
9618          * @param {Function} fn the method the event invokes
9619          * @param {Function} scope (needed for svg fake listeners)
9620          * @return {Roo.Element} this
9621          */
9622         removeListener : function(eventName, fn, scope){
9623             Roo.EventManager.removeListener(this.dom,  eventName, fn);
9624             if (typeof(this.listeners) == 'undefined'  || typeof(this.listeners[eventName]) == 'undefined') {
9625                 return this;
9626             }
9627             this.listeners[eventName].removeListener(fn, scope);
9628             return this;
9629         },
9630
9631         /**
9632          * Removes all previous added listeners from this element
9633          * @return {Roo.Element} this
9634          */
9635         removeAllListeners : function(){
9636             E.purgeElement(this.dom);
9637             this.listeners = {};
9638             return this;
9639         },
9640
9641         relayEvent : function(eventName, observable){
9642             this.on(eventName, function(e){
9643                 observable.fireEvent(eventName, e);
9644             });
9645         },
9646
9647         
9648         /**
9649          * Set the opacity of the element
9650          * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
9651          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9652          * @return {Roo.Element} this
9653          */
9654          setOpacity : function(opacity, animate){
9655             if(!animate || !A){
9656                 var s = this.dom.style;
9657                 if(Roo.isIE){
9658                     s.zoom = 1;
9659                     s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
9660                                (opacity == 1 ? "" : "alpha(opacity=" + opacity * 100 + ")");
9661                 }else{
9662                     s.opacity = opacity;
9663                 }
9664             }else{
9665                 this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
9666             }
9667             return this;
9668         },
9669
9670         /**
9671          * Gets the left X coordinate
9672          * @param {Boolean} local True to get the local css position instead of page coordinate
9673          * @return {Number}
9674          */
9675         getLeft : function(local){
9676             if(!local){
9677                 return this.getX();
9678             }else{
9679                 return parseInt(this.getStyle("left"), 10) || 0;
9680             }
9681         },
9682
9683         /**
9684          * Gets the right X coordinate of the element (element X position + element width)
9685          * @param {Boolean} local True to get the local css position instead of page coordinate
9686          * @return {Number}
9687          */
9688         getRight : function(local){
9689             if(!local){
9690                 return this.getX() + this.getWidth();
9691             }else{
9692                 return (this.getLeft(true) + this.getWidth()) || 0;
9693             }
9694         },
9695
9696         /**
9697          * Gets the top Y coordinate
9698          * @param {Boolean} local True to get the local css position instead of page coordinate
9699          * @return {Number}
9700          */
9701         getTop : function(local) {
9702             if(!local){
9703                 return this.getY();
9704             }else{
9705                 return parseInt(this.getStyle("top"), 10) || 0;
9706             }
9707         },
9708
9709         /**
9710          * Gets the bottom Y coordinate of the element (element Y position + element height)
9711          * @param {Boolean} local True to get the local css position instead of page coordinate
9712          * @return {Number}
9713          */
9714         getBottom : function(local){
9715             if(!local){
9716                 return this.getY() + this.getHeight();
9717             }else{
9718                 return (this.getTop(true) + this.getHeight()) || 0;
9719             }
9720         },
9721
9722         /**
9723         * Initializes positioning on this element. If a desired position is not passed, it will make the
9724         * the element positioned relative IF it is not already positioned.
9725         * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
9726         * @param {Number} zIndex (optional) The zIndex to apply
9727         * @param {Number} x (optional) Set the page X position
9728         * @param {Number} y (optional) Set the page Y position
9729         */
9730         position : function(pos, zIndex, x, y){
9731             if(!pos){
9732                if(this.getStyle('position') == 'static'){
9733                    this.setStyle('position', 'relative');
9734                }
9735             }else{
9736                 this.setStyle("position", pos);
9737             }
9738             if(zIndex){
9739                 this.setStyle("z-index", zIndex);
9740             }
9741             if(x !== undefined && y !== undefined){
9742                 this.setXY([x, y]);
9743             }else if(x !== undefined){
9744                 this.setX(x);
9745             }else if(y !== undefined){
9746                 this.setY(y);
9747             }
9748         },
9749
9750         /**
9751         * Clear positioning back to the default when the document was loaded
9752         * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
9753         * @return {Roo.Element} this
9754          */
9755         clearPositioning : function(value){
9756             value = value ||'';
9757             this.setStyle({
9758                 "left": value,
9759                 "right": value,
9760                 "top": value,
9761                 "bottom": value,
9762                 "z-index": "",
9763                 "position" : "static"
9764             });
9765             return this;
9766         },
9767
9768         /**
9769         * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
9770         * snapshot before performing an update and then restoring the element.
9771         * @return {Object}
9772         */
9773         getPositioning : function(){
9774             var l = this.getStyle("left");
9775             var t = this.getStyle("top");
9776             return {
9777                 "position" : this.getStyle("position"),
9778                 "left" : l,
9779                 "right" : l ? "" : this.getStyle("right"),
9780                 "top" : t,
9781                 "bottom" : t ? "" : this.getStyle("bottom"),
9782                 "z-index" : this.getStyle("z-index")
9783             };
9784         },
9785
9786         /**
9787          * Gets the width of the border(s) for the specified side(s)
9788          * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9789          * passing lr would get the border (l)eft width + the border (r)ight width.
9790          * @return {Number} The width of the sides passed added together
9791          */
9792         getBorderWidth : function(side){
9793             return this.addStyles(side, El.borders);
9794         },
9795
9796         /**
9797          * Gets the width of the padding(s) for the specified side(s)
9798          * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9799          * passing lr would get the padding (l)eft + the padding (r)ight.
9800          * @return {Number} The padding of the sides passed added together
9801          */
9802         getPadding : function(side){
9803             return this.addStyles(side, El.paddings);
9804         },
9805
9806         /**
9807         * Set positioning with an object returned by getPositioning().
9808         * @param {Object} posCfg
9809         * @return {Roo.Element} this
9810          */
9811         setPositioning : function(pc){
9812             this.applyStyles(pc);
9813             if(pc.right == "auto"){
9814                 this.dom.style.right = "";
9815             }
9816             if(pc.bottom == "auto"){
9817                 this.dom.style.bottom = "";
9818             }
9819             return this;
9820         },
9821
9822         // private
9823         fixDisplay : function(){
9824             if(this.getStyle("display") == "none"){
9825                 this.setStyle("visibility", "hidden");
9826                 this.setStyle("display", this.originalDisplay); // first try reverting to default
9827                 if(this.getStyle("display") == "none"){ // if that fails, default to block
9828                     this.setStyle("display", "block");
9829                 }
9830             }
9831         },
9832
9833         /**
9834          * Quick set left and top adding default units
9835          * @param {String} left The left CSS property value
9836          * @param {String} top The top CSS property value
9837          * @return {Roo.Element} this
9838          */
9839          setLeftTop : function(left, top){
9840             this.dom.style.left = this.addUnits(left);
9841             this.dom.style.top = this.addUnits(top);
9842             return this;
9843         },
9844
9845         /**
9846          * Move this element relative to its current position.
9847          * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
9848          * @param {Number} distance How far to move the element in pixels
9849          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9850          * @return {Roo.Element} this
9851          */
9852          move : function(direction, distance, animate){
9853             var xy = this.getXY();
9854             direction = direction.toLowerCase();
9855             switch(direction){
9856                 case "l":
9857                 case "left":
9858                     this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
9859                     break;
9860                case "r":
9861                case "right":
9862                     this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
9863                     break;
9864                case "t":
9865                case "top":
9866                case "up":
9867                     this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
9868                     break;
9869                case "b":
9870                case "bottom":
9871                case "down":
9872                     this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
9873                     break;
9874             }
9875             return this;
9876         },
9877
9878         /**
9879          *  Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
9880          * @return {Roo.Element} this
9881          */
9882         clip : function(){
9883             if(!this.isClipped){
9884                this.isClipped = true;
9885                this.originalClip = {
9886                    "o": this.getStyle("overflow"),
9887                    "x": this.getStyle("overflow-x"),
9888                    "y": this.getStyle("overflow-y")
9889                };
9890                this.setStyle("overflow", "hidden");
9891                this.setStyle("overflow-x", "hidden");
9892                this.setStyle("overflow-y", "hidden");
9893             }
9894             return this;
9895         },
9896
9897         /**
9898          *  Return clipping (overflow) to original clipping before clip() was called
9899          * @return {Roo.Element} this
9900          */
9901         unclip : function(){
9902             if(this.isClipped){
9903                 this.isClipped = false;
9904                 var o = this.originalClip;
9905                 if(o.o){this.setStyle("overflow", o.o);}
9906                 if(o.x){this.setStyle("overflow-x", o.x);}
9907                 if(o.y){this.setStyle("overflow-y", o.y);}
9908             }
9909             return this;
9910         },
9911
9912
9913         /**
9914          * Gets the x,y coordinates specified by the anchor position on the element.
9915          * @param {String} anchor (optional) The specified anchor position (defaults to "c").  See {@link #alignTo} for details on supported anchor positions.
9916          * @param {Object} size (optional) An object containing the size to use for calculating anchor position
9917          *                       {width: (target width), height: (target height)} (defaults to the element's current size)
9918          * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead of page coordinates
9919          * @return {Array} [x, y] An array containing the element's x and y coordinates
9920          */
9921         getAnchorXY : function(anchor, local, s){
9922             //Passing a different size is useful for pre-calculating anchors,
9923             //especially for anchored animations that change the el size.
9924
9925             var w, h, vp = false;
9926             if(!s){
9927                 var d = this.dom;
9928                 if(d == document.body || d == document){
9929                     vp = true;
9930                     w = D.getViewWidth(); h = D.getViewHeight();
9931                 }else{
9932                     w = this.getWidth(); h = this.getHeight();
9933                 }
9934             }else{
9935                 w = s.width;  h = s.height;
9936             }
9937             var x = 0, y = 0, r = Math.round;
9938             switch((anchor || "tl").toLowerCase()){
9939                 case "c":
9940                     x = r(w*.5);
9941                     y = r(h*.5);
9942                 break;
9943                 case "t":
9944                     x = r(w*.5);
9945                     y = 0;
9946                 break;
9947                 case "l":
9948                     x = 0;
9949                     y = r(h*.5);
9950                 break;
9951                 case "r":
9952                     x = w;
9953                     y = r(h*.5);
9954                 break;
9955                 case "b":
9956                     x = r(w*.5);
9957                     y = h;
9958                 break;
9959                 case "tl":
9960                     x = 0;
9961                     y = 0;
9962                 break;
9963                 case "bl":
9964                     x = 0;
9965                     y = h;
9966                 break;
9967                 case "br":
9968                     x = w;
9969                     y = h;
9970                 break;
9971                 case "tr":
9972                     x = w;
9973                     y = 0;
9974                 break;
9975             }
9976             if(local === true){
9977                 return [x, y];
9978             }
9979             if(vp){
9980                 var sc = this.getScroll();
9981                 return [x + sc.left, y + sc.top];
9982             }
9983             //Add the element's offset xy
9984             var o = this.getXY();
9985             return [x+o[0], y+o[1]];
9986         },
9987
9988         /**
9989          * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
9990          * supported position values.
9991          * @param {String/HTMLElement/Roo.Element} element The element to align to.
9992          * @param {String} position The position to align to.
9993          * @param {Array} offsets (optional) Offset the positioning by [x, y]
9994          * @return {Array} [x, y]
9995          */
9996         getAlignToXY : function(el, p, o)
9997         {
9998             el = Roo.get(el);
9999             var d = this.dom;
10000             if(!el.dom){
10001                 throw "Element.alignTo with an element that doesn't exist";
10002             }
10003             var c = false; //constrain to viewport
10004             var p1 = "", p2 = "";
10005             o = o || [0,0];
10006
10007             if(!p){
10008                 p = "tl-bl";
10009             }else if(p == "?"){
10010                 p = "tl-bl?";
10011             }else if(p.indexOf("-") == -1){
10012                 p = "tl-" + p;
10013             }
10014             p = p.toLowerCase();
10015             var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
10016             if(!m){
10017                throw "Element.alignTo with an invalid alignment " + p;
10018             }
10019             p1 = m[1]; p2 = m[2]; c = !!m[3];
10020
10021             //Subtract the aligned el's internal xy from the target's offset xy
10022             //plus custom offset to get the aligned el's new offset xy
10023             var a1 = this.getAnchorXY(p1, true);
10024             var a2 = el.getAnchorXY(p2, false);
10025             var x = a2[0] - a1[0] + o[0];
10026             var y = a2[1] - a1[1] + o[1];
10027             if(c){
10028                 //constrain the aligned el to viewport if necessary
10029                 var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
10030                 // 5px of margin for ie
10031                 var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5;
10032
10033                 //If we are at a viewport boundary and the aligned el is anchored on a target border that is
10034                 //perpendicular to the vp border, allow the aligned el to slide on that border,
10035                 //otherwise swap the aligned el to the opposite border of the target.
10036                 var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
10037                var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
10038                var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t")  );
10039                var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
10040
10041                var doc = document;
10042                var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
10043                var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
10044
10045                if((x+w) > dw + scrollX){
10046                     x = swapX ? r.left-w : dw+scrollX-w;
10047                 }
10048                if(x < scrollX){
10049                    x = swapX ? r.right : scrollX;
10050                }
10051                if((y+h) > dh + scrollY){
10052                     y = swapY ? r.top-h : dh+scrollY-h;
10053                 }
10054                if (y < scrollY){
10055                    y = swapY ? r.bottom : scrollY;
10056                }
10057             }
10058             return [x,y];
10059         },
10060
10061         // private
10062         getConstrainToXY : function(){
10063             var os = {top:0, left:0, bottom:0, right: 0};
10064
10065             return function(el, local, offsets, proposedXY){
10066                 el = Roo.get(el);
10067                 offsets = offsets ? Roo.applyIf(offsets, os) : os;
10068
10069                 var vw, vh, vx = 0, vy = 0;
10070                 if(el.dom == document.body || el.dom == document){
10071                     vw = Roo.lib.Dom.getViewWidth();
10072                     vh = Roo.lib.Dom.getViewHeight();
10073                 }else{
10074                     vw = el.dom.clientWidth;
10075                     vh = el.dom.clientHeight;
10076                     if(!local){
10077                         var vxy = el.getXY();
10078                         vx = vxy[0];
10079                         vy = vxy[1];
10080                     }
10081                 }
10082
10083                 var s = el.getScroll();
10084
10085                 vx += offsets.left + s.left;
10086                 vy += offsets.top + s.top;
10087
10088                 vw -= offsets.right;
10089                 vh -= offsets.bottom;
10090
10091                 var vr = vx+vw;
10092                 var vb = vy+vh;
10093
10094                 var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
10095                 var x = xy[0], y = xy[1];
10096                 var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
10097
10098                 // only move it if it needs it
10099                 var moved = false;
10100
10101                 // first validate right/bottom
10102                 if((x + w) > vr){
10103                     x = vr - w;
10104                     moved = true;
10105                 }
10106                 if((y + h) > vb){
10107                     y = vb - h;
10108                     moved = true;
10109                 }
10110                 // then make sure top/left isn't negative
10111                 if(x < vx){
10112                     x = vx;
10113                     moved = true;
10114                 }
10115                 if(y < vy){
10116                     y = vy;
10117                     moved = true;
10118                 }
10119                 return moved ? [x, y] : false;
10120             };
10121         }(),
10122
10123         // private
10124         adjustForConstraints : function(xy, parent, offsets){
10125             return this.getConstrainToXY(parent || document, false, offsets, xy) ||  xy;
10126         },
10127
10128         /**
10129          * Aligns this element with another element relative to the specified anchor points. If the other element is the
10130          * document it aligns it to the viewport.
10131          * The position parameter is optional, and can be specified in any one of the following formats:
10132          * <ul>
10133          *   <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
10134          *   <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
10135          *       The element being aligned will position its top-left corner (tl) to that point.  <i>This method has been
10136          *       deprecated in favor of the newer two anchor syntax below</i>.</li>
10137          *   <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
10138          *       element's anchor point, and the second value is used as the target's anchor point.</li>
10139          * </ul>
10140          * In addition to the anchor points, the position parameter also supports the "?" character.  If "?" is passed at the end of
10141          * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
10142          * the viewport if necessary.  Note that the element being aligned might be swapped to align to a different position than
10143          * that specified in order to enforce the viewport constraints.
10144          * Following are all of the supported anchor positions:
10145     <pre>
10146     Value  Description
10147     -----  -----------------------------
10148     tl     The top left corner (default)
10149     t      The center of the top edge
10150     tr     The top right corner
10151     l      The center of the left edge
10152     c      In the center of the element
10153     r      The center of the right edge
10154     bl     The bottom left corner
10155     b      The center of the bottom edge
10156     br     The bottom right corner
10157     </pre>
10158     Example Usage:
10159     <pre><code>
10160     // align el to other-el using the default positioning ("tl-bl", non-constrained)
10161     el.alignTo("other-el");
10162
10163     // align the top left corner of el with the top right corner of other-el (constrained to viewport)
10164     el.alignTo("other-el", "tr?");
10165
10166     // align the bottom right corner of el with the center left edge of other-el
10167     el.alignTo("other-el", "br-l?");
10168
10169     // align the center of el with the bottom left corner of other-el and
10170     // adjust the x position by -6 pixels (and the y position by 0)
10171     el.alignTo("other-el", "c-bl", [-6, 0]);
10172     </code></pre>
10173          * @param {String/HTMLElement/Roo.Element} element The element to align to.
10174          * @param {String} position The position to align to.
10175          * @param {Array} offsets (optional) Offset the positioning by [x, y]
10176          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10177          * @return {Roo.Element} this
10178          */
10179         alignTo : function(element, position, offsets, animate){
10180             var xy = this.getAlignToXY(element, position, offsets);
10181             this.setXY(xy, this.preanim(arguments, 3));
10182             return this;
10183         },
10184
10185         /**
10186          * Anchors an element to another element and realigns it when the window is resized.
10187          * @param {String/HTMLElement/Roo.Element} element The element to align to.
10188          * @param {String} position The position to align to.
10189          * @param {Array} offsets (optional) Offset the positioning by [x, y]
10190          * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
10191          * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
10192          * is a number, it is used as the buffer delay (defaults to 50ms).
10193          * @param {Function} callback The function to call after the animation finishes
10194          * @return {Roo.Element} this
10195          */
10196         anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
10197             var action = function(){
10198                 this.alignTo(el, alignment, offsets, animate);
10199                 Roo.callback(callback, this);
10200             };
10201             Roo.EventManager.onWindowResize(action, this);
10202             var tm = typeof monitorScroll;
10203             if(tm != 'undefined'){
10204                 Roo.EventManager.on(window, 'scroll', action, this,
10205                     {buffer: tm == 'number' ? monitorScroll : 50});
10206             }
10207             action.call(this); // align immediately
10208             return this;
10209         },
10210         /**
10211          * Clears any opacity settings from this element. Required in some cases for IE.
10212          * @return {Roo.Element} this
10213          */
10214         clearOpacity : function(){
10215             if (window.ActiveXObject) {
10216                 if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
10217                     this.dom.style.filter = "";
10218                 }
10219             } else {
10220                 this.dom.style.opacity = "";
10221                 this.dom.style["-moz-opacity"] = "";
10222                 this.dom.style["-khtml-opacity"] = "";
10223             }
10224             return this;
10225         },
10226
10227         /**
10228          * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
10229          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10230          * @return {Roo.Element} this
10231          */
10232         hide : function(animate){
10233             this.setVisible(false, this.preanim(arguments, 0));
10234             return this;
10235         },
10236
10237         /**
10238         * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
10239         * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10240          * @return {Roo.Element} this
10241          */
10242         show : function(animate){
10243             this.setVisible(true, this.preanim(arguments, 0));
10244             return this;
10245         },
10246
10247         /**
10248          * @private Test if size has a unit, otherwise appends the default
10249          */
10250         addUnits : function(size){
10251             return Roo.Element.addUnits(size, this.defaultUnit);
10252         },
10253
10254         /**
10255          * Temporarily enables offsets (width,height,x,y) for an element with display:none, use endMeasure() when done.
10256          * @return {Roo.Element} this
10257          */
10258         beginMeasure : function(){
10259             var el = this.dom;
10260             if(el.offsetWidth || el.offsetHeight){
10261                 return this; // offsets work already
10262             }
10263             var changed = [];
10264             var p = this.dom, b = document.body; // start with this element
10265             while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){
10266                 var pe = Roo.get(p);
10267                 if(pe.getStyle('display') == 'none'){
10268                     changed.push({el: p, visibility: pe.getStyle("visibility")});
10269                     p.style.visibility = "hidden";
10270                     p.style.display = "block";
10271                 }
10272                 p = p.parentNode;
10273             }
10274             this._measureChanged = changed;
10275             return this;
10276
10277         },
10278
10279         /**
10280          * Restores displays to before beginMeasure was called
10281          * @return {Roo.Element} this
10282          */
10283         endMeasure : function(){
10284             var changed = this._measureChanged;
10285             if(changed){
10286                 for(var i = 0, len = changed.length; i < len; i++) {
10287                     var r = changed[i];
10288                     r.el.style.visibility = r.visibility;
10289                     r.el.style.display = "none";
10290                 }
10291                 this._measureChanged = null;
10292             }
10293             return this;
10294         },
10295
10296         /**
10297         * Update the innerHTML of this element, optionally searching for and processing scripts
10298         * @param {String} html The new HTML
10299         * @param {Boolean} loadScripts (optional) true to look for and process scripts
10300         * @param {Function} callback For async script loading you can be noticed when the update completes
10301         * @return {Roo.Element} this
10302          */
10303         update : function(html, loadScripts, callback){
10304             if(typeof html == "undefined"){
10305                 html = "";
10306             }
10307             if(loadScripts !== true){
10308                 this.dom.innerHTML = html;
10309                 if(typeof callback == "function"){
10310                     callback();
10311                 }
10312                 return this;
10313             }
10314             var id = Roo.id();
10315             var dom = this.dom;
10316
10317             html += '<span id="' + id + '"></span>';
10318
10319             E.onAvailable(id, function(){
10320                 var hd = document.getElementsByTagName("head")[0];
10321                 var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
10322                 var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
10323                 var typeRe = /\stype=([\'\"])(.*?)\1/i;
10324
10325                 var match;
10326                 while(match = re.exec(html)){
10327                     var attrs = match[1];
10328                     var srcMatch = attrs ? attrs.match(srcRe) : false;
10329                     if(srcMatch && srcMatch[2]){
10330                        var s = document.createElement("script");
10331                        s.src = srcMatch[2];
10332                        var typeMatch = attrs.match(typeRe);
10333                        if(typeMatch && typeMatch[2]){
10334                            s.type = typeMatch[2];
10335                        }
10336                        hd.appendChild(s);
10337                     }else if(match[2] && match[2].length > 0){
10338                         if(window.execScript) {
10339                            window.execScript(match[2]);
10340                         } else {
10341                             /**
10342                              * eval:var:id
10343                              * eval:var:dom
10344                              * eval:var:html
10345                              * 
10346                              */
10347                            window.eval(match[2]);
10348                         }
10349                     }
10350                 }
10351                 var el = document.getElementById(id);
10352                 if(el){el.parentNode.removeChild(el);}
10353                 if(typeof callback == "function"){
10354                     callback();
10355                 }
10356             });
10357             dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
10358             return this;
10359         },
10360
10361         /**
10362          * Direct access to the UpdateManager update() method (takes the same parameters).
10363          * @param {String/Function} url The url for this request or a function to call to get the url
10364          * @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}
10365          * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
10366          * @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.
10367          * @return {Roo.Element} this
10368          */
10369         load : function(){
10370             var um = this.getUpdateManager();
10371             um.update.apply(um, arguments);
10372             return this;
10373         },
10374
10375         /**
10376         * Gets this element's UpdateManager
10377         * @return {Roo.UpdateManager} The UpdateManager
10378         */
10379         getUpdateManager : function(){
10380             if(!this.updateManager){
10381                 this.updateManager = new Roo.UpdateManager(this);
10382             }
10383             return this.updateManager;
10384         },
10385
10386         /**
10387          * Disables text selection for this element (normalized across browsers)
10388          * @return {Roo.Element} this
10389          */
10390         unselectable : function(){
10391             this.dom.unselectable = "on";
10392             this.swallowEvent("selectstart", true);
10393             this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
10394             this.addClass("x-unselectable");
10395             return this;
10396         },
10397
10398         /**
10399         * Calculates the x, y to center this element on the screen
10400         * @return {Array} The x, y values [x, y]
10401         */
10402         getCenterXY : function(){
10403             return this.getAlignToXY(document, 'c-c');
10404         },
10405
10406         /**
10407         * Centers the Element in either the viewport, or another Element.
10408         * @param {String/HTMLElement/Roo.Element} centerIn (optional) The element in which to center the element.
10409         */
10410         center : function(centerIn){
10411             this.alignTo(centerIn || document, 'c-c');
10412             return this;
10413         },
10414
10415         /**
10416          * Tests various css rules/browsers to determine if this element uses a border box
10417          * @return {Boolean}
10418          */
10419         isBorderBox : function(){
10420             return noBoxAdjust[this.dom.tagName.toLowerCase()] || Roo.isBorderBox;
10421         },
10422
10423         /**
10424          * Return a box {x, y, width, height} that can be used to set another elements
10425          * size/location to match this element.
10426          * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
10427          * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
10428          * @return {Object} box An object in the format {x, y, width, height}
10429          */
10430         getBox : function(contentBox, local){
10431             var xy;
10432             if(!local){
10433                 xy = this.getXY();
10434             }else{
10435                 var left = parseInt(this.getStyle("left"), 10) || 0;
10436                 var top = parseInt(this.getStyle("top"), 10) || 0;
10437                 xy = [left, top];
10438             }
10439             var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
10440             if(!contentBox){
10441                 bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
10442             }else{
10443                 var l = this.getBorderWidth("l")+this.getPadding("l");
10444                 var r = this.getBorderWidth("r")+this.getPadding("r");
10445                 var t = this.getBorderWidth("t")+this.getPadding("t");
10446                 var b = this.getBorderWidth("b")+this.getPadding("b");
10447                 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)};
10448             }
10449             bx.right = bx.x + bx.width;
10450             bx.bottom = bx.y + bx.height;
10451             return bx;
10452         },
10453
10454         /**
10455          * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
10456          for more information about the sides.
10457          * @param {String} sides
10458          * @return {Number}
10459          */
10460         getFrameWidth : function(sides, onlyContentBox){
10461             return onlyContentBox && Roo.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
10462         },
10463
10464         /**
10465          * 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.
10466          * @param {Object} box The box to fill {x, y, width, height}
10467          * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
10468          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10469          * @return {Roo.Element} this
10470          */
10471         setBox : function(box, adjust, animate){
10472             var w = box.width, h = box.height;
10473             if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
10474                w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
10475                h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
10476             }
10477             this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
10478             return this;
10479         },
10480
10481         /**
10482          * Forces the browser to repaint this element
10483          * @return {Roo.Element} this
10484          */
10485          repaint : function(){
10486             var dom = this.dom;
10487             this.addClass("x-repaint");
10488             setTimeout(function(){
10489                 Roo.get(dom).removeClass("x-repaint");
10490             }, 1);
10491             return this;
10492         },
10493
10494         /**
10495          * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
10496          * then it returns the calculated width of the sides (see getPadding)
10497          * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
10498          * @return {Object/Number}
10499          */
10500         getMargins : function(side){
10501             if(!side){
10502                 return {
10503                     top: parseInt(this.getStyle("margin-top"), 10) || 0,
10504                     left: parseInt(this.getStyle("margin-left"), 10) || 0,
10505                     bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
10506                     right: parseInt(this.getStyle("margin-right"), 10) || 0
10507                 };
10508             }else{
10509                 return this.addStyles(side, El.margins);
10510              }
10511         },
10512
10513         // private
10514         addStyles : function(sides, styles){
10515             var val = 0, v, w;
10516             for(var i = 0, len = sides.length; i < len; i++){
10517                 v = this.getStyle(styles[sides.charAt(i)]);
10518                 if(v){
10519                      w = parseInt(v, 10);
10520                      if(w){ val += w; }
10521                 }
10522             }
10523             return val;
10524         },
10525
10526         /**
10527          * Creates a proxy element of this element
10528          * @param {String/Object} config The class name of the proxy element or a DomHelper config object
10529          * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
10530          * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
10531          * @return {Roo.Element} The new proxy element
10532          */
10533         createProxy : function(config, renderTo, matchBox){
10534             if(renderTo){
10535                 renderTo = Roo.getDom(renderTo);
10536             }else{
10537                 renderTo = document.body;
10538             }
10539             config = typeof config == "object" ?
10540                 config : {tag : "div", cls: config};
10541             var proxy = Roo.DomHelper.append(renderTo, config, true);
10542             if(matchBox){
10543                proxy.setBox(this.getBox());
10544             }
10545             return proxy;
10546         },
10547
10548         /**
10549          * Puts a mask over this element to disable user interaction. Requires core.css.
10550          * This method can only be applied to elements which accept child nodes.
10551          * @param {String} msg (optional) A message to display in the mask
10552          * @param {String} msgCls (optional) A css class to apply to the msg element - use no-spinner to hide the spinner on bootstrap
10553          * @return {Element} The mask  element
10554          */
10555         mask : function(msg, msgCls)
10556         {
10557             if(this.getStyle("position") == "static" && this.dom.tagName !== 'BODY'){
10558                 this.setStyle("position", "relative");
10559             }
10560             if(!this._mask){
10561                 this._mask = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask"}, true);
10562             }
10563             
10564             this.addClass("x-masked");
10565             this._mask.setDisplayed(true);
10566             
10567             // we wander
10568             var z = 0;
10569             var dom = this.dom;
10570             while (dom && dom.style) {
10571                 if (!isNaN(parseInt(dom.style.zIndex))) {
10572                     z = Math.max(z, parseInt(dom.style.zIndex));
10573                 }
10574                 dom = dom.parentNode;
10575             }
10576             // if we are masking the body - then it hides everything..
10577             if (this.dom == document.body) {
10578                 z = 1000000;
10579                 this._mask.setWidth(Roo.lib.Dom.getDocumentWidth());
10580                 this._mask.setHeight(Roo.lib.Dom.getDocumentHeight());
10581             }
10582            
10583             if(typeof msg == 'string'){
10584                 if(!this._maskMsg){
10585                     this._maskMsg = Roo.DomHelper.append(this.dom, {
10586                         cls: "roo-el-mask-msg", 
10587                         cn: [
10588                             {
10589                                 tag: 'i',
10590                                 cls: 'fa fa-spinner fa-spin'
10591                             },
10592                             {
10593                                 tag: 'div'
10594                             }   
10595                         ]
10596                     }, true);
10597                 }
10598                 var mm = this._maskMsg;
10599                 mm.dom.className = msgCls ? "roo-el-mask-msg " + msgCls : "roo-el-mask-msg";
10600                 if (mm.dom.lastChild) { // weird IE issue?
10601                     mm.dom.lastChild.innerHTML = msg;
10602                 }
10603                 mm.setDisplayed(true);
10604                 mm.center(this);
10605                 mm.setStyle('z-index', z + 102);
10606             }
10607             if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
10608                 this._mask.setHeight(this.getHeight());
10609             }
10610             this._mask.setStyle('z-index', z + 100);
10611             
10612             return this._mask;
10613         },
10614
10615         /**
10616          * Removes a previously applied mask. If removeEl is true the mask overlay is destroyed, otherwise
10617          * it is cached for reuse.
10618          */
10619         unmask : function(removeEl){
10620             if(this._mask){
10621                 if(removeEl === true){
10622                     this._mask.remove();
10623                     delete this._mask;
10624                     if(this._maskMsg){
10625                         this._maskMsg.remove();
10626                         delete this._maskMsg;
10627                     }
10628                 }else{
10629                     this._mask.setDisplayed(false);
10630                     if(this._maskMsg){
10631                         this._maskMsg.setDisplayed(false);
10632                     }
10633                 }
10634             }
10635             this.removeClass("x-masked");
10636         },
10637
10638         /**
10639          * Returns true if this element is masked
10640          * @return {Boolean}
10641          */
10642         isMasked : function(){
10643             return this._mask && this._mask.isVisible();
10644         },
10645
10646         /**
10647          * Creates an iframe shim for this element to keep selects and other windowed objects from
10648          * showing through.
10649          * @return {Roo.Element} The new shim element
10650          */
10651         createShim : function(){
10652             var el = document.createElement('iframe');
10653             el.frameBorder = 'no';
10654             el.className = 'roo-shim';
10655             if(Roo.isIE && Roo.isSecure){
10656                 el.src = Roo.SSL_SECURE_URL;
10657             }
10658             var shim = Roo.get(this.dom.parentNode.insertBefore(el, this.dom));
10659             shim.autoBoxAdjust = false;
10660             return shim;
10661         },
10662
10663         /**
10664          * Removes this element from the DOM and deletes it from the cache
10665          */
10666         remove : function(){
10667             if(this.dom.parentNode){
10668                 this.dom.parentNode.removeChild(this.dom);
10669             }
10670             delete El.cache[this.dom.id];
10671         },
10672
10673         /**
10674          * Sets up event handlers to add and remove a css class when the mouse is over this element
10675          * @param {String} className
10676          * @param {Boolean} preventFlicker (optional) If set to true, it prevents flickering by filtering
10677          * mouseout events for children elements
10678          * @return {Roo.Element} this
10679          */
10680         addClassOnOver : function(className, preventFlicker){
10681             this.on("mouseover", function(){
10682                 Roo.fly(this, '_internal').addClass(className);
10683             }, this.dom);
10684             var removeFn = function(e){
10685                 if(preventFlicker !== true || !e.within(this, true)){
10686                     Roo.fly(this, '_internal').removeClass(className);
10687                 }
10688             };
10689             this.on("mouseout", removeFn, this.dom);
10690             return this;
10691         },
10692
10693         /**
10694          * Sets up event handlers to add and remove a css class when this element has the focus
10695          * @param {String} className
10696          * @return {Roo.Element} this
10697          */
10698         addClassOnFocus : function(className){
10699             this.on("focus", function(){
10700                 Roo.fly(this, '_internal').addClass(className);
10701             }, this.dom);
10702             this.on("blur", function(){
10703                 Roo.fly(this, '_internal').removeClass(className);
10704             }, this.dom);
10705             return this;
10706         },
10707         /**
10708          * 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)
10709          * @param {String} className
10710          * @return {Roo.Element} this
10711          */
10712         addClassOnClick : function(className){
10713             var dom = this.dom;
10714             this.on("mousedown", function(){
10715                 Roo.fly(dom, '_internal').addClass(className);
10716                 var d = Roo.get(document);
10717                 var fn = function(){
10718                     Roo.fly(dom, '_internal').removeClass(className);
10719                     d.removeListener("mouseup", fn);
10720                 };
10721                 d.on("mouseup", fn);
10722             });
10723             return this;
10724         },
10725
10726         /**
10727          * Stops the specified event from bubbling and optionally prevents the default action
10728          * @param {String} eventName
10729          * @param {Boolean} preventDefault (optional) true to prevent the default action too
10730          * @return {Roo.Element} this
10731          */
10732         swallowEvent : function(eventName, preventDefault){
10733             var fn = function(e){
10734                 e.stopPropagation();
10735                 if(preventDefault){
10736                     e.preventDefault();
10737                 }
10738             };
10739             if(eventName instanceof Array){
10740                 for(var i = 0, len = eventName.length; i < len; i++){
10741                      this.on(eventName[i], fn);
10742                 }
10743                 return this;
10744             }
10745             this.on(eventName, fn);
10746             return this;
10747         },
10748
10749         /**
10750          * @private
10751          */
10752         fitToParentDelegate : Roo.emptyFn, // keep a reference to the fitToParent delegate
10753
10754         /**
10755          * Sizes this element to its parent element's dimensions performing
10756          * neccessary box adjustments.
10757          * @param {Boolean} monitorResize (optional) If true maintains the fit when the browser window is resized.
10758          * @param {String/HTMLElment/Element} targetParent (optional) The target parent, default to the parentNode.
10759          * @return {Roo.Element} this
10760          */
10761         fitToParent : function(monitorResize, targetParent) {
10762           Roo.EventManager.removeResizeListener(this.fitToParentDelegate); // always remove previous fitToParent delegate from onWindowResize
10763           this.fitToParentDelegate = Roo.emptyFn; // remove reference to previous delegate
10764           if (monitorResize === true && !this.dom.parentNode) { // check if this Element still exists
10765             return this;
10766           }
10767           var p = Roo.get(targetParent || this.dom.parentNode);
10768           this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb'));
10769           if (monitorResize === true) {
10770             this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]);
10771             Roo.EventManager.onWindowResize(this.fitToParentDelegate);
10772           }
10773           return this;
10774         },
10775
10776         /**
10777          * Gets the next sibling, skipping text nodes
10778          * @return {HTMLElement} The next sibling or null
10779          */
10780         getNextSibling : function(){
10781             var n = this.dom.nextSibling;
10782             while(n && n.nodeType != 1){
10783                 n = n.nextSibling;
10784             }
10785             return n;
10786         },
10787
10788         /**
10789          * Gets the previous sibling, skipping text nodes
10790          * @return {HTMLElement} The previous sibling or null
10791          */
10792         getPrevSibling : function(){
10793             var n = this.dom.previousSibling;
10794             while(n && n.nodeType != 1){
10795                 n = n.previousSibling;
10796             }
10797             return n;
10798         },
10799
10800
10801         /**
10802          * Appends the passed element(s) to this element
10803          * @param {String/HTMLElement/Array/Element/CompositeElement} el
10804          * @return {Roo.Element} this
10805          */
10806         appendChild: function(el){
10807             el = Roo.get(el);
10808             el.appendTo(this);
10809             return this;
10810         },
10811
10812         /**
10813          * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
10814          * @param {Object} config DomHelper element config object.  If no tag is specified (e.g., {tag:'input'}) then a div will be
10815          * automatically generated with the specified attributes.
10816          * @param {HTMLElement} insertBefore (optional) a child element of this element
10817          * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
10818          * @return {Roo.Element} The new child element
10819          */
10820         createChild: function(config, insertBefore, returnDom){
10821             config = config || {tag:'div'};
10822             if(insertBefore){
10823                 return Roo.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
10824             }
10825             return Roo.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config,  returnDom !== true);
10826         },
10827
10828         /**
10829          * Appends this element to the passed element
10830          * @param {String/HTMLElement/Element} el The new parent element
10831          * @return {Roo.Element} this
10832          */
10833         appendTo: function(el){
10834             el = Roo.getDom(el);
10835             el.appendChild(this.dom);
10836             return this;
10837         },
10838
10839         /**
10840          * Inserts this element before the passed element in the DOM
10841          * @param {String/HTMLElement/Element} el The element to insert before
10842          * @return {Roo.Element} this
10843          */
10844         insertBefore: function(el){
10845             el = Roo.getDom(el);
10846             el.parentNode.insertBefore(this.dom, el);
10847             return this;
10848         },
10849
10850         /**
10851          * Inserts this element after the passed element in the DOM
10852          * @param {String/HTMLElement/Element} el The element to insert after
10853          * @return {Roo.Element} this
10854          */
10855         insertAfter: function(el){
10856             el = Roo.getDom(el);
10857             el.parentNode.insertBefore(this.dom, el.nextSibling);
10858             return this;
10859         },
10860
10861         /**
10862          * Inserts (or creates) an element (or DomHelper config) as the first child of the this element
10863          * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10864          * @return {Roo.Element} The new child
10865          */
10866         insertFirst: function(el, returnDom){
10867             el = el || {};
10868             if(typeof el == 'object' && !el.nodeType){ // dh config
10869                 return this.createChild(el, this.dom.firstChild, returnDom);
10870             }else{
10871                 el = Roo.getDom(el);
10872                 this.dom.insertBefore(el, this.dom.firstChild);
10873                 return !returnDom ? Roo.get(el) : el;
10874             }
10875         },
10876
10877         /**
10878          * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
10879          * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10880          * @param {String} where (optional) 'before' or 'after' defaults to before
10881          * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10882          * @return {Roo.Element} the inserted Element
10883          */
10884         insertSibling: function(el, where, returnDom){
10885             where = where ? where.toLowerCase() : 'before';
10886             el = el || {};
10887             var rt, refNode = where == 'before' ? this.dom : this.dom.nextSibling;
10888
10889             if(typeof el == 'object' && !el.nodeType){ // dh config
10890                 if(where == 'after' && !this.dom.nextSibling){
10891                     rt = Roo.DomHelper.append(this.dom.parentNode, el, !returnDom);
10892                 }else{
10893                     rt = Roo.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
10894                 }
10895
10896             }else{
10897                 rt = this.dom.parentNode.insertBefore(Roo.getDom(el),
10898                             where == 'before' ? this.dom : this.dom.nextSibling);
10899                 if(!returnDom){
10900                     rt = Roo.get(rt);
10901                 }
10902             }
10903             return rt;
10904         },
10905
10906         /**
10907          * Creates and wraps this element with another element
10908          * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
10909          * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10910          * @return {HTMLElement/Element} The newly created wrapper element
10911          */
10912         wrap: function(config, returnDom){
10913             if(!config){
10914                 config = {tag: "div"};
10915             }
10916             var newEl = Roo.DomHelper.insertBefore(this.dom, config, !returnDom);
10917             newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
10918             return newEl;
10919         },
10920
10921         /**
10922          * Replaces the passed element with this element
10923          * @param {String/HTMLElement/Element} el The element to replace
10924          * @return {Roo.Element} this
10925          */
10926         replace: function(el){
10927             el = Roo.get(el);
10928             this.insertBefore(el);
10929             el.remove();
10930             return this;
10931         },
10932
10933         /**
10934          * Inserts an html fragment into this element
10935          * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
10936          * @param {String} html The HTML fragment
10937          * @param {Boolean} returnEl True to return an Roo.Element
10938          * @return {HTMLElement/Roo.Element} The inserted node (or nearest related if more than 1 inserted)
10939          */
10940         insertHtml : function(where, html, returnEl){
10941             var el = Roo.DomHelper.insertHtml(where, this.dom, html);
10942             return returnEl ? Roo.get(el) : el;
10943         },
10944
10945         /**
10946          * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
10947          * @param {Object} o The object with the attributes
10948          * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
10949          * @return {Roo.Element} this
10950          */
10951         set : function(o, useSet){
10952             var el = this.dom;
10953             useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
10954             for(var attr in o){
10955                 if(attr == "style" || typeof o[attr] == "function")  { continue; }
10956                 if(attr=="cls"){
10957                     el.className = o["cls"];
10958                 }else{
10959                     if(useSet) {
10960                         el.setAttribute(attr, o[attr]);
10961                     } else {
10962                         el[attr] = o[attr];
10963                     }
10964                 }
10965             }
10966             if(o.style){
10967                 Roo.DomHelper.applyStyles(el, o.style);
10968             }
10969             return this;
10970         },
10971
10972         /**
10973          * Convenience method for constructing a KeyMap
10974          * @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:
10975          *                                  {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
10976          * @param {Function} fn The function to call
10977          * @param {Object} scope (optional) The scope of the function
10978          * @return {Roo.KeyMap} The KeyMap created
10979          */
10980         addKeyListener : function(key, fn, scope){
10981             var config;
10982             if(typeof key != "object" || key instanceof Array){
10983                 config = {
10984                     key: key,
10985                     fn: fn,
10986                     scope: scope
10987                 };
10988             }else{
10989                 config = {
10990                     key : key.key,
10991                     shift : key.shift,
10992                     ctrl : key.ctrl,
10993                     alt : key.alt,
10994                     fn: fn,
10995                     scope: scope
10996                 };
10997             }
10998             return new Roo.KeyMap(this, config);
10999         },
11000
11001         /**
11002          * Creates a KeyMap for this element
11003          * @param {Object} config The KeyMap config. See {@link Roo.KeyMap} for more details
11004          * @return {Roo.KeyMap} The KeyMap created
11005          */
11006         addKeyMap : function(config){
11007             return new Roo.KeyMap(this, config);
11008         },
11009
11010         /**
11011          * Returns true if this element is scrollable.
11012          * @return {Boolean}
11013          */
11014          isScrollable : function(){
11015             var dom = this.dom;
11016             return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
11017         },
11018
11019         /**
11020          * 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().
11021          * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
11022          * @param {Number} value The new scroll value
11023          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
11024          * @return {Element} this
11025          */
11026
11027         scrollTo : function(side, value, animate){
11028             var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
11029             if(!animate || !A){
11030                 this.dom[prop] = value;
11031             }else{
11032                 var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
11033                 this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
11034             }
11035             return this;
11036         },
11037
11038         /**
11039          * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
11040          * within this element's scrollable range.
11041          * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
11042          * @param {Number} distance How far to scroll the element in pixels
11043          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
11044          * @return {Boolean} Returns true if a scroll was triggered or false if the element
11045          * was scrolled as far as it could go.
11046          */
11047          scroll : function(direction, distance, animate){
11048              if(!this.isScrollable()){
11049                  return;
11050              }
11051              var el = this.dom;
11052              var l = el.scrollLeft, t = el.scrollTop;
11053              var w = el.scrollWidth, h = el.scrollHeight;
11054              var cw = el.clientWidth, ch = el.clientHeight;
11055              direction = direction.toLowerCase();
11056              var scrolled = false;
11057              var a = this.preanim(arguments, 2);
11058              switch(direction){
11059                  case "l":
11060                  case "left":
11061                      if(w - l > cw){
11062                          var v = Math.min(l + distance, w-cw);
11063                          this.scrollTo("left", v, a);
11064                          scrolled = true;
11065                      }
11066                      break;
11067                 case "r":
11068                 case "right":
11069                      if(l > 0){
11070                          var v = Math.max(l - distance, 0);
11071                          this.scrollTo("left", v, a);
11072                          scrolled = true;
11073                      }
11074                      break;
11075                 case "t":
11076                 case "top":
11077                 case "up":
11078                      if(t > 0){
11079                          var v = Math.max(t - distance, 0);
11080                          this.scrollTo("top", v, a);
11081                          scrolled = true;
11082                      }
11083                      break;
11084                 case "b":
11085                 case "bottom":
11086                 case "down":
11087                      if(h - t > ch){
11088                          var v = Math.min(t + distance, h-ch);
11089                          this.scrollTo("top", v, a);
11090                          scrolled = true;
11091                      }
11092                      break;
11093              }
11094              return scrolled;
11095         },
11096
11097         /**
11098          * Translates the passed page coordinates into left/top css values for this element
11099          * @param {Number/Array} x The page x or an array containing [x, y]
11100          * @param {Number} y The page y
11101          * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
11102          */
11103         translatePoints : function(x, y){
11104             if(typeof x == 'object' || x instanceof Array){
11105                 y = x[1]; x = x[0];
11106             }
11107             var p = this.getStyle('position');
11108             var o = this.getXY();
11109
11110             var l = parseInt(this.getStyle('left'), 10);
11111             var t = parseInt(this.getStyle('top'), 10);
11112
11113             if(isNaN(l)){
11114                 l = (p == "relative") ? 0 : this.dom.offsetLeft;
11115             }
11116             if(isNaN(t)){
11117                 t = (p == "relative") ? 0 : this.dom.offsetTop;
11118             }
11119
11120             return {left: (x - o[0] + l), top: (y - o[1] + t)};
11121         },
11122
11123         /**
11124          * Returns the current scroll position of the element.
11125          * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
11126          */
11127         getScroll : function(){
11128             var d = this.dom, doc = document;
11129             if(d == doc || d == doc.body){
11130                 var l = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
11131                 var t = window.pageYOffset || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
11132                 return {left: l, top: t};
11133             }else{
11134                 return {left: d.scrollLeft, top: d.scrollTop};
11135             }
11136         },
11137
11138         /**
11139          * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
11140          * are convert to standard 6 digit hex color.
11141          * @param {String} attr The css attribute
11142          * @param {String} defaultValue The default value to use when a valid color isn't found
11143          * @param {String} prefix (optional) defaults to #. Use an empty string when working with
11144          * YUI color anims.
11145          */
11146         getColor : function(attr, defaultValue, prefix){
11147             var v = this.getStyle(attr);
11148             if(!v || v == "transparent" || v == "inherit") {
11149                 return defaultValue;
11150             }
11151             var color = typeof prefix == "undefined" ? "#" : prefix;
11152             if(v.substr(0, 4) == "rgb("){
11153                 var rvs = v.slice(4, v.length -1).split(",");
11154                 for(var i = 0; i < 3; i++){
11155                     var h = parseInt(rvs[i]).toString(16);
11156                     if(h < 16){
11157                         h = "0" + h;
11158                     }
11159                     color += h;
11160                 }
11161             } else {
11162                 if(v.substr(0, 1) == "#"){
11163                     if(v.length == 4) {
11164                         for(var i = 1; i < 4; i++){
11165                             var c = v.charAt(i);
11166                             color +=  c + c;
11167                         }
11168                     }else if(v.length == 7){
11169                         color += v.substr(1);
11170                     }
11171                 }
11172             }
11173             return(color.length > 5 ? color.toLowerCase() : defaultValue);
11174         },
11175
11176         /**
11177          * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
11178          * gradient background, rounded corners and a 4-way shadow.
11179          * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
11180          * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
11181          * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
11182          * @return {Roo.Element} this
11183          */
11184         boxWrap : function(cls){
11185             cls = cls || 'x-box';
11186             var el = Roo.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
11187             el.child('.'+cls+'-mc').dom.appendChild(this.dom);
11188             return el;
11189         },
11190
11191         /**
11192          * Returns the value of a namespaced attribute from the element's underlying DOM node.
11193          * @param {String} namespace The namespace in which to look for the attribute
11194          * @param {String} name The attribute name
11195          * @return {String} The attribute value
11196          */
11197         getAttributeNS : Roo.isIE ? function(ns, name){
11198             var d = this.dom;
11199             var type = typeof d[ns+":"+name];
11200             if(type != 'undefined' && type != 'unknown'){
11201                 return d[ns+":"+name];
11202             }
11203             return d[name];
11204         } : function(ns, name){
11205             var d = this.dom;
11206             return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
11207         },
11208         
11209         
11210         /**
11211          * Sets or Returns the value the dom attribute value
11212          * @param {String|Object} name The attribute name (or object to set multiple attributes)
11213          * @param {String} value (optional) The value to set the attribute to
11214          * @return {String} The attribute value
11215          */
11216         attr : function(name){
11217             if (arguments.length > 1) {
11218                 this.dom.setAttribute(name, arguments[1]);
11219                 return arguments[1];
11220             }
11221             if (typeof(name) == 'object') {
11222                 for(var i in name) {
11223                     this.attr(i, name[i]);
11224                 }
11225                 return name;
11226             }
11227             
11228             
11229             if (!this.dom.hasAttribute(name)) {
11230                 return undefined;
11231             }
11232             return this.dom.getAttribute(name);
11233         }
11234         
11235         
11236         
11237     };
11238
11239     var ep = El.prototype;
11240
11241     /**
11242      * Appends an event handler (Shorthand for addListener)
11243      * @param {String}   eventName     The type of event to append
11244      * @param {Function} fn        The method the event invokes
11245      * @param {Object} scope       (optional) The scope (this object) of the fn
11246      * @param {Object}   options   (optional)An object with standard {@link Roo.EventManager#addListener} options
11247      * @method
11248      */
11249     ep.on = ep.addListener;
11250         // backwards compat
11251     ep.mon = ep.addListener;
11252
11253     /**
11254      * Removes an event handler from this element (shorthand for removeListener)
11255      * @param {String} eventName the type of event to remove
11256      * @param {Function} fn the method the event invokes
11257      * @return {Roo.Element} this
11258      * @method
11259      */
11260     ep.un = ep.removeListener;
11261
11262     /**
11263      * true to automatically adjust width and height settings for box-model issues (default to true)
11264      */
11265     ep.autoBoxAdjust = true;
11266
11267     // private
11268     El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
11269
11270     // private
11271     El.addUnits = function(v, defaultUnit){
11272         if(v === "" || v == "auto"){
11273             return v;
11274         }
11275         if(v === undefined){
11276             return '';
11277         }
11278         if(typeof v == "number" || !El.unitPattern.test(v)){
11279             return v + (defaultUnit || 'px');
11280         }
11281         return v;
11282     };
11283
11284     // special markup used throughout Roo when box wrapping elements
11285     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>';
11286     /**
11287      * Visibility mode constant - Use visibility to hide element
11288      * @static
11289      * @type Number
11290      */
11291     El.VISIBILITY = 1;
11292     /**
11293      * Visibility mode constant - Use display to hide element
11294      * @static
11295      * @type Number
11296      */
11297     El.DISPLAY = 2;
11298
11299     El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
11300     El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
11301     El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
11302
11303
11304
11305     /**
11306      * @private
11307      */
11308     El.cache = {};
11309
11310     var docEl;
11311
11312     /**
11313      * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
11314      * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
11315      * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
11316      * @return {Element} The Element object
11317      * @static
11318      */
11319     El.get = function(el){
11320         var ex, elm, id;
11321         if(!el){ return null; }
11322         if(typeof el == "string"){ // element id
11323             if(!(elm = document.getElementById(el))){
11324                 return null;
11325             }
11326             if(ex = El.cache[el]){
11327                 ex.dom = elm;
11328             }else{
11329                 ex = El.cache[el] = new El(elm);
11330             }
11331             return ex;
11332         }else if(el.tagName){ // dom element
11333             if(!(id = el.id)){
11334                 id = Roo.id(el);
11335             }
11336             if(ex = El.cache[id]){
11337                 ex.dom = el;
11338             }else{
11339                 ex = El.cache[id] = new El(el);
11340             }
11341             return ex;
11342         }else if(el instanceof El){
11343             if(el != docEl){
11344                 el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
11345                                                               // catch case where it hasn't been appended
11346                 El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
11347             }
11348             return el;
11349         }else if(el.isComposite){
11350             return el;
11351         }else if(el instanceof Array){
11352             return El.select(el);
11353         }else if(el == document){
11354             // create a bogus element object representing the document object
11355             if(!docEl){
11356                 var f = function(){};
11357                 f.prototype = El.prototype;
11358                 docEl = new f();
11359                 docEl.dom = document;
11360             }
11361             return docEl;
11362         }
11363         return null;
11364     };
11365
11366     // private
11367     El.uncache = function(el){
11368         for(var i = 0, a = arguments, len = a.length; i < len; i++) {
11369             if(a[i]){
11370                 delete El.cache[a[i].id || a[i]];
11371             }
11372         }
11373     };
11374
11375     // private
11376     // Garbage collection - uncache elements/purge listeners on orphaned elements
11377     // so we don't hold a reference and cause the browser to retain them
11378     El.garbageCollect = function(){
11379         if(!Roo.enableGarbageCollector){
11380             clearInterval(El.collectorThread);
11381             return;
11382         }
11383         for(var eid in El.cache){
11384             var el = El.cache[eid], d = el.dom;
11385             // -------------------------------------------------------
11386             // Determining what is garbage:
11387             // -------------------------------------------------------
11388             // !d
11389             // dom node is null, definitely garbage
11390             // -------------------------------------------------------
11391             // !d.parentNode
11392             // no parentNode == direct orphan, definitely garbage
11393             // -------------------------------------------------------
11394             // !d.offsetParent && !document.getElementById(eid)
11395             // display none elements have no offsetParent so we will
11396             // also try to look it up by it's id. However, check
11397             // offsetParent first so we don't do unneeded lookups.
11398             // This enables collection of elements that are not orphans
11399             // directly, but somewhere up the line they have an orphan
11400             // parent.
11401             // -------------------------------------------------------
11402             if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
11403                 delete El.cache[eid];
11404                 if(d && Roo.enableListenerCollection){
11405                     E.purgeElement(d);
11406                 }
11407             }
11408         }
11409     }
11410     El.collectorThreadId = setInterval(El.garbageCollect, 30000);
11411
11412
11413     // dom is optional
11414     El.Flyweight = function(dom){
11415         this.dom = dom;
11416     };
11417     El.Flyweight.prototype = El.prototype;
11418
11419     El._flyweights = {};
11420     /**
11421      * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
11422      * the dom node can be overwritten by other code.
11423      * @param {String/HTMLElement} el The dom node or id
11424      * @param {String} named (optional) Allows for creation of named reusable flyweights to
11425      *                                  prevent conflicts (e.g. internally Roo uses "_internal")
11426      * @static
11427      * @return {Element} The shared Element object
11428      */
11429     El.fly = function(el, named){
11430         named = named || '_global';
11431         el = Roo.getDom(el);
11432         if(!el){
11433             return null;
11434         }
11435         if(!El._flyweights[named]){
11436             El._flyweights[named] = new El.Flyweight();
11437         }
11438         El._flyweights[named].dom = el;
11439         return El._flyweights[named];
11440     };
11441
11442     /**
11443      * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
11444      * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
11445      * Shorthand of {@link Roo.Element#get}
11446      * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
11447      * @return {Element} The Element object
11448      * @member Roo
11449      * @method get
11450      */
11451     Roo.get = El.get;
11452     /**
11453      * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
11454      * the dom node can be overwritten by other code.
11455      * Shorthand of {@link Roo.Element#fly}
11456      * @param {String/HTMLElement} el The dom node or id
11457      * @param {String} named (optional) Allows for creation of named reusable flyweights to
11458      *                                  prevent conflicts (e.g. internally Roo uses "_internal")
11459      * @static
11460      * @return {Element} The shared Element object
11461      * @member Roo
11462      * @method fly
11463      */
11464     Roo.fly = El.fly;
11465
11466     // speedy lookup for elements never to box adjust
11467     var noBoxAdjust = Roo.isStrict ? {
11468         select:1
11469     } : {
11470         input:1, select:1, textarea:1
11471     };
11472     if(Roo.isIE || Roo.isGecko){
11473         noBoxAdjust['button'] = 1;
11474     }
11475
11476
11477     Roo.EventManager.on(window, 'unload', function(){
11478         delete El.cache;
11479         delete El._flyweights;
11480     });
11481 })();
11482
11483
11484
11485
11486 if(Roo.DomQuery){
11487     Roo.Element.selectorFunction = Roo.DomQuery.select;
11488 }
11489
11490 Roo.Element.select = function(selector, unique, root){
11491     var els;
11492     if(typeof selector == "string"){
11493         els = Roo.Element.selectorFunction(selector, root);
11494     }else if(selector.length !== undefined){
11495         els = selector;
11496     }else{
11497         throw "Invalid selector";
11498     }
11499     if(unique === true){
11500         return new Roo.CompositeElement(els);
11501     }else{
11502         return new Roo.CompositeElementLite(els);
11503     }
11504 };
11505 /**
11506  * Selects elements based on the passed CSS selector to enable working on them as 1.
11507  * @param {String/Array} selector The CSS selector or an array of elements
11508  * @param {Boolean} unique (optional) true to create a unique Roo.Element for each element (defaults to a shared flyweight object)
11509  * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
11510  * @return {CompositeElementLite/CompositeElement}
11511  * @member Roo
11512  * @method select
11513  */
11514 Roo.select = Roo.Element.select;
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529 /*
11530  * Based on:
11531  * Ext JS Library 1.1.1
11532  * Copyright(c) 2006-2007, Ext JS, LLC.
11533  *
11534  * Originally Released Under LGPL - original licence link has changed is not relivant.
11535  *
11536  * Fork - LGPL
11537  * <script type="text/javascript">
11538  */
11539
11540
11541
11542 //Notifies Element that fx methods are available
11543 Roo.enableFx = true;
11544
11545 /**
11546  * @class Roo.Fx
11547  * <p>A class to provide basic animation and visual effects support.  <b>Note:</b> This class is automatically applied
11548  * to the {@link Roo.Element} interface when included, so all effects calls should be performed via Element.
11549  * Conversely, since the effects are not actually defined in Element, Roo.Fx <b>must</b> be included in order for the 
11550  * Element effects to work.</p><br/>
11551  *
11552  * <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
11553  * they return the Element object itself as the method return value, it is not always possible to mix the two in a single
11554  * method chain.  The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
11555  * Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately.  For this reason,
11556  * while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
11557  * expected results and should be done with care.</p><br/>
11558  *
11559  * <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
11560  * that will serve as either the start or end point of the animation.  Following are all of the supported anchor positions:</p>
11561 <pre>
11562 Value  Description
11563 -----  -----------------------------
11564 tl     The top left corner
11565 t      The center of the top edge
11566 tr     The top right corner
11567 l      The center of the left edge
11568 r      The center of the right edge
11569 bl     The bottom left corner
11570 b      The center of the bottom edge
11571 br     The bottom right corner
11572 </pre>
11573  * <b>Although some Fx methods accept specific custom config parameters, the ones shown in the Config Options section
11574  * below are common options that can be passed to any Fx method.</b>
11575  * @cfg {Function} callback A function called when the effect is finished
11576  * @cfg {Object} scope The scope of the effect function
11577  * @cfg {String} easing A valid Easing value for the effect
11578  * @cfg {String} afterCls A css class to apply after the effect
11579  * @cfg {Number} duration The length of time (in seconds) that the effect should last
11580  * @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
11581  * @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to 
11582  * effects that end with the element being visually hidden, ignored otherwise)
11583  * @cfg {String/Object/Function} afterStyle A style specification string, e.g. "width:100px", or an object in the form {width:"100px"}, or
11584  * a function which returns such a specification that will be applied to the Element after the effect finishes
11585  * @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
11586  * @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
11587  * @cfg {Boolean} stopFx Whether subsequent effects should be stopped and removed after the current effect finishes
11588  */
11589 Roo.Fx = {
11590         /**
11591          * Slides the element into view.  An anchor point can be optionally passed to set the point of
11592          * origin for the slide effect.  This function automatically handles wrapping the element with
11593          * a fixed-size container if needed.  See the Fx class overview for valid anchor point options.
11594          * Usage:
11595          *<pre><code>
11596 // default: slide the element in from the top
11597 el.slideIn();
11598
11599 // custom: slide the element in from the right with a 2-second duration
11600 el.slideIn('r', { duration: 2 });
11601
11602 // common config options shown with default values
11603 el.slideIn('t', {
11604     easing: 'easeOut',
11605     duration: .5
11606 });
11607 </code></pre>
11608          * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11609          * @param {Object} options (optional) Object literal with any of the Fx config options
11610          * @return {Roo.Element} The Element
11611          */
11612     slideIn : function(anchor, o){
11613         var el = this.getFxEl();
11614         o = o || {};
11615
11616         el.queueFx(o, function(){
11617
11618             anchor = anchor || "t";
11619
11620             // fix display to visibility
11621             this.fixDisplay();
11622
11623             // restore values after effect
11624             var r = this.getFxRestore();
11625             var b = this.getBox();
11626             // fixed size for slide
11627             this.setSize(b);
11628
11629             // wrap if needed
11630             var wrap = this.fxWrap(r.pos, o, "hidden");
11631
11632             var st = this.dom.style;
11633             st.visibility = "visible";
11634             st.position = "absolute";
11635
11636             // clear out temp styles after slide and unwrap
11637             var after = function(){
11638                 el.fxUnwrap(wrap, r.pos, o);
11639                 st.width = r.width;
11640                 st.height = r.height;
11641                 el.afterFx(o);
11642             };
11643             // time to calc the positions
11644             var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
11645
11646             switch(anchor.toLowerCase()){
11647                 case "t":
11648                     wrap.setSize(b.width, 0);
11649                     st.left = st.bottom = "0";
11650                     a = {height: bh};
11651                 break;
11652                 case "l":
11653                     wrap.setSize(0, b.height);
11654                     st.right = st.top = "0";
11655                     a = {width: bw};
11656                 break;
11657                 case "r":
11658                     wrap.setSize(0, b.height);
11659                     wrap.setX(b.right);
11660                     st.left = st.top = "0";
11661                     a = {width: bw, points: pt};
11662                 break;
11663                 case "b":
11664                     wrap.setSize(b.width, 0);
11665                     wrap.setY(b.bottom);
11666                     st.left = st.top = "0";
11667                     a = {height: bh, points: pt};
11668                 break;
11669                 case "tl":
11670                     wrap.setSize(0, 0);
11671                     st.right = st.bottom = "0";
11672                     a = {width: bw, height: bh};
11673                 break;
11674                 case "bl":
11675                     wrap.setSize(0, 0);
11676                     wrap.setY(b.y+b.height);
11677                     st.right = st.top = "0";
11678                     a = {width: bw, height: bh, points: pt};
11679                 break;
11680                 case "br":
11681                     wrap.setSize(0, 0);
11682                     wrap.setXY([b.right, b.bottom]);
11683                     st.left = st.top = "0";
11684                     a = {width: bw, height: bh, points: pt};
11685                 break;
11686                 case "tr":
11687                     wrap.setSize(0, 0);
11688                     wrap.setX(b.x+b.width);
11689                     st.left = st.bottom = "0";
11690                     a = {width: bw, height: bh, points: pt};
11691                 break;
11692             }
11693             this.dom.style.visibility = "visible";
11694             wrap.show();
11695
11696             arguments.callee.anim = wrap.fxanim(a,
11697                 o,
11698                 'motion',
11699                 .5,
11700                 'easeOut', after);
11701         });
11702         return this;
11703     },
11704     
11705         /**
11706          * Slides the element out of view.  An anchor point can be optionally passed to set the end point
11707          * for the slide effect.  When the effect is completed, the element will be hidden (visibility = 
11708          * 'hidden') but block elements will still take up space in the document.  The element must be removed
11709          * from the DOM using the 'remove' config option if desired.  This function automatically handles 
11710          * wrapping the element with a fixed-size container if needed.  See the Fx class overview for valid anchor point options.
11711          * Usage:
11712          *<pre><code>
11713 // default: slide the element out to the top
11714 el.slideOut();
11715
11716 // custom: slide the element out to the right with a 2-second duration
11717 el.slideOut('r', { duration: 2 });
11718
11719 // common config options shown with default values
11720 el.slideOut('t', {
11721     easing: 'easeOut',
11722     duration: .5,
11723     remove: false,
11724     useDisplay: false
11725 });
11726 </code></pre>
11727          * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11728          * @param {Object} options (optional) Object literal with any of the Fx config options
11729          * @return {Roo.Element} The Element
11730          */
11731     slideOut : function(anchor, o){
11732         var el = this.getFxEl();
11733         o = o || {};
11734
11735         el.queueFx(o, function(){
11736
11737             anchor = anchor || "t";
11738
11739             // restore values after effect
11740             var r = this.getFxRestore();
11741             
11742             var b = this.getBox();
11743             // fixed size for slide
11744             this.setSize(b);
11745
11746             // wrap if needed
11747             var wrap = this.fxWrap(r.pos, o, "visible");
11748
11749             var st = this.dom.style;
11750             st.visibility = "visible";
11751             st.position = "absolute";
11752
11753             wrap.setSize(b);
11754
11755             var after = function(){
11756                 if(o.useDisplay){
11757                     el.setDisplayed(false);
11758                 }else{
11759                     el.hide();
11760                 }
11761
11762                 el.fxUnwrap(wrap, r.pos, o);
11763
11764                 st.width = r.width;
11765                 st.height = r.height;
11766
11767                 el.afterFx(o);
11768             };
11769
11770             var a, zero = {to: 0};
11771             switch(anchor.toLowerCase()){
11772                 case "t":
11773                     st.left = st.bottom = "0";
11774                     a = {height: zero};
11775                 break;
11776                 case "l":
11777                     st.right = st.top = "0";
11778                     a = {width: zero};
11779                 break;
11780                 case "r":
11781                     st.left = st.top = "0";
11782                     a = {width: zero, points: {to:[b.right, b.y]}};
11783                 break;
11784                 case "b":
11785                     st.left = st.top = "0";
11786                     a = {height: zero, points: {to:[b.x, b.bottom]}};
11787                 break;
11788                 case "tl":
11789                     st.right = st.bottom = "0";
11790                     a = {width: zero, height: zero};
11791                 break;
11792                 case "bl":
11793                     st.right = st.top = "0";
11794                     a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
11795                 break;
11796                 case "br":
11797                     st.left = st.top = "0";
11798                     a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
11799                 break;
11800                 case "tr":
11801                     st.left = st.bottom = "0";
11802                     a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
11803                 break;
11804             }
11805
11806             arguments.callee.anim = wrap.fxanim(a,
11807                 o,
11808                 'motion',
11809                 .5,
11810                 "easeOut", after);
11811         });
11812         return this;
11813     },
11814
11815         /**
11816          * Fades the element out while slowly expanding it in all directions.  When the effect is completed, the 
11817          * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document. 
11818          * The element must be removed from the DOM using the 'remove' config option if desired.
11819          * Usage:
11820          *<pre><code>
11821 // default
11822 el.puff();
11823
11824 // common config options shown with default values
11825 el.puff({
11826     easing: 'easeOut',
11827     duration: .5,
11828     remove: false,
11829     useDisplay: false
11830 });
11831 </code></pre>
11832          * @param {Object} options (optional) Object literal with any of the Fx config options
11833          * @return {Roo.Element} The Element
11834          */
11835     puff : function(o){
11836         var el = this.getFxEl();
11837         o = o || {};
11838
11839         el.queueFx(o, function(){
11840             this.clearOpacity();
11841             this.show();
11842
11843             // restore values after effect
11844             var r = this.getFxRestore();
11845             var st = this.dom.style;
11846
11847             var after = function(){
11848                 if(o.useDisplay){
11849                     el.setDisplayed(false);
11850                 }else{
11851                     el.hide();
11852                 }
11853
11854                 el.clearOpacity();
11855
11856                 el.setPositioning(r.pos);
11857                 st.width = r.width;
11858                 st.height = r.height;
11859                 st.fontSize = '';
11860                 el.afterFx(o);
11861             };
11862
11863             var width = this.getWidth();
11864             var height = this.getHeight();
11865
11866             arguments.callee.anim = this.fxanim({
11867                     width : {to: this.adjustWidth(width * 2)},
11868                     height : {to: this.adjustHeight(height * 2)},
11869                     points : {by: [-(width * .5), -(height * .5)]},
11870                     opacity : {to: 0},
11871                     fontSize: {to:200, unit: "%"}
11872                 },
11873                 o,
11874                 'motion',
11875                 .5,
11876                 "easeOut", after);
11877         });
11878         return this;
11879     },
11880
11881         /**
11882          * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
11883          * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still 
11884          * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
11885          * Usage:
11886          *<pre><code>
11887 // default
11888 el.switchOff();
11889
11890 // all config options shown with default values
11891 el.switchOff({
11892     easing: 'easeIn',
11893     duration: .3,
11894     remove: false,
11895     useDisplay: false
11896 });
11897 </code></pre>
11898          * @param {Object} options (optional) Object literal with any of the Fx config options
11899          * @return {Roo.Element} The Element
11900          */
11901     switchOff : function(o){
11902         var el = this.getFxEl();
11903         o = o || {};
11904
11905         el.queueFx(o, function(){
11906             this.clearOpacity();
11907             this.clip();
11908
11909             // restore values after effect
11910             var r = this.getFxRestore();
11911             var st = this.dom.style;
11912
11913             var after = function(){
11914                 if(o.useDisplay){
11915                     el.setDisplayed(false);
11916                 }else{
11917                     el.hide();
11918                 }
11919
11920                 el.clearOpacity();
11921                 el.setPositioning(r.pos);
11922                 st.width = r.width;
11923                 st.height = r.height;
11924
11925                 el.afterFx(o);
11926             };
11927
11928             this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
11929                 this.clearOpacity();
11930                 (function(){
11931                     this.fxanim({
11932                         height:{to:1},
11933                         points:{by:[0, this.getHeight() * .5]}
11934                     }, o, 'motion', 0.3, 'easeIn', after);
11935                 }).defer(100, this);
11936             });
11937         });
11938         return this;
11939     },
11940
11941     /**
11942      * Highlights the Element by setting a color (applies to the background-color by default, but can be
11943      * changed using the "attr" config option) and then fading back to the original color. If no original
11944      * color is available, you should provide the "endColor" config option which will be cleared after the animation.
11945      * Usage:
11946 <pre><code>
11947 // default: highlight background to yellow
11948 el.highlight();
11949
11950 // custom: highlight foreground text to blue for 2 seconds
11951 el.highlight("0000ff", { attr: 'color', duration: 2 });
11952
11953 // common config options shown with default values
11954 el.highlight("ffff9c", {
11955     attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
11956     endColor: (current color) or "ffffff",
11957     easing: 'easeIn',
11958     duration: 1
11959 });
11960 </code></pre>
11961      * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
11962      * @param {Object} options (optional) Object literal with any of the Fx config options
11963      * @return {Roo.Element} The Element
11964      */ 
11965     highlight : function(color, o){
11966         var el = this.getFxEl();
11967         o = o || {};
11968
11969         el.queueFx(o, function(){
11970             color = color || "ffff9c";
11971             attr = o.attr || "backgroundColor";
11972
11973             this.clearOpacity();
11974             this.show();
11975
11976             var origColor = this.getColor(attr);
11977             var restoreColor = this.dom.style[attr];
11978             endColor = (o.endColor || origColor) || "ffffff";
11979
11980             var after = function(){
11981                 el.dom.style[attr] = restoreColor;
11982                 el.afterFx(o);
11983             };
11984
11985             var a = {};
11986             a[attr] = {from: color, to: endColor};
11987             arguments.callee.anim = this.fxanim(a,
11988                 o,
11989                 'color',
11990                 1,
11991                 'easeIn', after);
11992         });
11993         return this;
11994     },
11995
11996    /**
11997     * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
11998     * Usage:
11999 <pre><code>
12000 // default: a single light blue ripple
12001 el.frame();
12002
12003 // custom: 3 red ripples lasting 3 seconds total
12004 el.frame("ff0000", 3, { duration: 3 });
12005
12006 // common config options shown with default values
12007 el.frame("C3DAF9", 1, {
12008     duration: 1 //duration of entire animation (not each individual ripple)
12009     // Note: Easing is not configurable and will be ignored if included
12010 });
12011 </code></pre>
12012     * @param {String} color (optional) The color of the border.  Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
12013     * @param {Number} count (optional) The number of ripples to display (defaults to 1)
12014     * @param {Object} options (optional) Object literal with any of the Fx config options
12015     * @return {Roo.Element} The Element
12016     */
12017     frame : function(color, count, o){
12018         var el = this.getFxEl();
12019         o = o || {};
12020
12021         el.queueFx(o, function(){
12022             color = color || "#C3DAF9";
12023             if(color.length == 6){
12024                 color = "#" + color;
12025             }
12026             count = count || 1;
12027             duration = o.duration || 1;
12028             this.show();
12029
12030             var b = this.getBox();
12031             var animFn = function(){
12032                 var proxy = this.createProxy({
12033
12034                      style:{
12035                         visbility:"hidden",
12036                         position:"absolute",
12037                         "z-index":"35000", // yee haw
12038                         border:"0px solid " + color
12039                      }
12040                   });
12041                 var scale = Roo.isBorderBox ? 2 : 1;
12042                 proxy.animate({
12043                     top:{from:b.y, to:b.y - 20},
12044                     left:{from:b.x, to:b.x - 20},
12045                     borderWidth:{from:0, to:10},
12046                     opacity:{from:1, to:0},
12047                     height:{from:b.height, to:(b.height + (20*scale))},
12048                     width:{from:b.width, to:(b.width + (20*scale))}
12049                 }, duration, function(){
12050                     proxy.remove();
12051                 });
12052                 if(--count > 0){
12053                      animFn.defer((duration/2)*1000, this);
12054                 }else{
12055                     el.afterFx(o);
12056                 }
12057             };
12058             animFn.call(this);
12059         });
12060         return this;
12061     },
12062
12063    /**
12064     * Creates a pause before any subsequent queued effects begin.  If there are
12065     * no effects queued after the pause it will have no effect.
12066     * Usage:
12067 <pre><code>
12068 el.pause(1);
12069 </code></pre>
12070     * @param {Number} seconds The length of time to pause (in seconds)
12071     * @return {Roo.Element} The Element
12072     */
12073     pause : function(seconds){
12074         var el = this.getFxEl();
12075         var o = {};
12076
12077         el.queueFx(o, function(){
12078             setTimeout(function(){
12079                 el.afterFx(o);
12080             }, seconds * 1000);
12081         });
12082         return this;
12083     },
12084
12085    /**
12086     * Fade an element in (from transparent to opaque).  The ending opacity can be specified
12087     * using the "endOpacity" config option.
12088     * Usage:
12089 <pre><code>
12090 // default: fade in from opacity 0 to 100%
12091 el.fadeIn();
12092
12093 // custom: fade in from opacity 0 to 75% over 2 seconds
12094 el.fadeIn({ endOpacity: .75, duration: 2});
12095
12096 // common config options shown with default values
12097 el.fadeIn({
12098     endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
12099     easing: 'easeOut',
12100     duration: .5
12101 });
12102 </code></pre>
12103     * @param {Object} options (optional) Object literal with any of the Fx config options
12104     * @return {Roo.Element} The Element
12105     */
12106     fadeIn : function(o){
12107         var el = this.getFxEl();
12108         o = o || {};
12109         el.queueFx(o, function(){
12110             this.setOpacity(0);
12111             this.fixDisplay();
12112             this.dom.style.visibility = 'visible';
12113             var to = o.endOpacity || 1;
12114             arguments.callee.anim = this.fxanim({opacity:{to:to}},
12115                 o, null, .5, "easeOut", function(){
12116                 if(to == 1){
12117                     this.clearOpacity();
12118                 }
12119                 el.afterFx(o);
12120             });
12121         });
12122         return this;
12123     },
12124
12125    /**
12126     * Fade an element out (from opaque to transparent).  The ending opacity can be specified
12127     * using the "endOpacity" config option.
12128     * Usage:
12129 <pre><code>
12130 // default: fade out from the element's current opacity to 0
12131 el.fadeOut();
12132
12133 // custom: fade out from the element's current opacity to 25% over 2 seconds
12134 el.fadeOut({ endOpacity: .25, duration: 2});
12135
12136 // common config options shown with default values
12137 el.fadeOut({
12138     endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
12139     easing: 'easeOut',
12140     duration: .5
12141     remove: false,
12142     useDisplay: false
12143 });
12144 </code></pre>
12145     * @param {Object} options (optional) Object literal with any of the Fx config options
12146     * @return {Roo.Element} The Element
12147     */
12148     fadeOut : function(o){
12149         var el = this.getFxEl();
12150         o = o || {};
12151         el.queueFx(o, function(){
12152             arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}},
12153                 o, null, .5, "easeOut", function(){
12154                 if(this.visibilityMode == Roo.Element.DISPLAY || o.useDisplay){
12155                      this.dom.style.display = "none";
12156                 }else{
12157                      this.dom.style.visibility = "hidden";
12158                 }
12159                 this.clearOpacity();
12160                 el.afterFx(o);
12161             });
12162         });
12163         return this;
12164     },
12165
12166    /**
12167     * Animates the transition of an element's dimensions from a starting height/width
12168     * to an ending height/width.
12169     * Usage:
12170 <pre><code>
12171 // change height and width to 100x100 pixels
12172 el.scale(100, 100);
12173
12174 // common config options shown with default values.  The height and width will default to
12175 // the element's existing values if passed as null.
12176 el.scale(
12177     [element's width],
12178     [element's height], {
12179     easing: 'easeOut',
12180     duration: .35
12181 });
12182 </code></pre>
12183     * @param {Number} width  The new width (pass undefined to keep the original width)
12184     * @param {Number} height  The new height (pass undefined to keep the original height)
12185     * @param {Object} options (optional) Object literal with any of the Fx config options
12186     * @return {Roo.Element} The Element
12187     */
12188     scale : function(w, h, o){
12189         this.shift(Roo.apply({}, o, {
12190             width: w,
12191             height: h
12192         }));
12193         return this;
12194     },
12195
12196    /**
12197     * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
12198     * Any of these properties not specified in the config object will not be changed.  This effect 
12199     * requires that at least one new dimension, position or opacity setting must be passed in on
12200     * the config object in order for the function to have any effect.
12201     * Usage:
12202 <pre><code>
12203 // slide the element horizontally to x position 200 while changing the height and opacity
12204 el.shift({ x: 200, height: 50, opacity: .8 });
12205
12206 // common config options shown with default values.
12207 el.shift({
12208     width: [element's width],
12209     height: [element's height],
12210     x: [element's x position],
12211     y: [element's y position],
12212     opacity: [element's opacity],
12213     easing: 'easeOut',
12214     duration: .35
12215 });
12216 </code></pre>
12217     * @param {Object} options  Object literal with any of the Fx config options
12218     * @return {Roo.Element} The Element
12219     */
12220     shift : function(o){
12221         var el = this.getFxEl();
12222         o = o || {};
12223         el.queueFx(o, function(){
12224             var a = {}, w = o.width, h = o.height, x = o.x, y = o.y,  op = o.opacity;
12225             if(w !== undefined){
12226                 a.width = {to: this.adjustWidth(w)};
12227             }
12228             if(h !== undefined){
12229                 a.height = {to: this.adjustHeight(h)};
12230             }
12231             if(x !== undefined || y !== undefined){
12232                 a.points = {to: [
12233                     x !== undefined ? x : this.getX(),
12234                     y !== undefined ? y : this.getY()
12235                 ]};
12236             }
12237             if(op !== undefined){
12238                 a.opacity = {to: op};
12239             }
12240             if(o.xy !== undefined){
12241                 a.points = {to: o.xy};
12242             }
12243             arguments.callee.anim = this.fxanim(a,
12244                 o, 'motion', .35, "easeOut", function(){
12245                 el.afterFx(o);
12246             });
12247         });
12248         return this;
12249     },
12250
12251         /**
12252          * Slides the element while fading it out of view.  An anchor point can be optionally passed to set the 
12253          * ending point of the effect.
12254          * Usage:
12255          *<pre><code>
12256 // default: slide the element downward while fading out
12257 el.ghost();
12258
12259 // custom: slide the element out to the right with a 2-second duration
12260 el.ghost('r', { duration: 2 });
12261
12262 // common config options shown with default values
12263 el.ghost('b', {
12264     easing: 'easeOut',
12265     duration: .5
12266     remove: false,
12267     useDisplay: false
12268 });
12269 </code></pre>
12270          * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
12271          * @param {Object} options (optional) Object literal with any of the Fx config options
12272          * @return {Roo.Element} The Element
12273          */
12274     ghost : function(anchor, o){
12275         var el = this.getFxEl();
12276         o = o || {};
12277
12278         el.queueFx(o, function(){
12279             anchor = anchor || "b";
12280
12281             // restore values after effect
12282             var r = this.getFxRestore();
12283             var w = this.getWidth(),
12284                 h = this.getHeight();
12285
12286             var st = this.dom.style;
12287
12288             var after = function(){
12289                 if(o.useDisplay){
12290                     el.setDisplayed(false);
12291                 }else{
12292                     el.hide();
12293                 }
12294
12295                 el.clearOpacity();
12296                 el.setPositioning(r.pos);
12297                 st.width = r.width;
12298                 st.height = r.height;
12299
12300                 el.afterFx(o);
12301             };
12302
12303             var a = {opacity: {to: 0}, points: {}}, pt = a.points;
12304             switch(anchor.toLowerCase()){
12305                 case "t":
12306                     pt.by = [0, -h];
12307                 break;
12308                 case "l":
12309                     pt.by = [-w, 0];
12310                 break;
12311                 case "r":
12312                     pt.by = [w, 0];
12313                 break;
12314                 case "b":
12315                     pt.by = [0, h];
12316                 break;
12317                 case "tl":
12318                     pt.by = [-w, -h];
12319                 break;
12320                 case "bl":
12321                     pt.by = [-w, h];
12322                 break;
12323                 case "br":
12324                     pt.by = [w, h];
12325                 break;
12326                 case "tr":
12327                     pt.by = [w, -h];
12328                 break;
12329             }
12330
12331             arguments.callee.anim = this.fxanim(a,
12332                 o,
12333                 'motion',
12334                 .5,
12335                 "easeOut", after);
12336         });
12337         return this;
12338     },
12339
12340         /**
12341          * Ensures that all effects queued after syncFx is called on the element are
12342          * run concurrently.  This is the opposite of {@link #sequenceFx}.
12343          * @return {Roo.Element} The Element
12344          */
12345     syncFx : function(){
12346         this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
12347             block : false,
12348             concurrent : true,
12349             stopFx : false
12350         });
12351         return this;
12352     },
12353
12354         /**
12355          * Ensures that all effects queued after sequenceFx is called on the element are
12356          * run in sequence.  This is the opposite of {@link #syncFx}.
12357          * @return {Roo.Element} The Element
12358          */
12359     sequenceFx : function(){
12360         this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
12361             block : false,
12362             concurrent : false,
12363             stopFx : false
12364         });
12365         return this;
12366     },
12367
12368         /* @private */
12369     nextFx : function(){
12370         var ef = this.fxQueue[0];
12371         if(ef){
12372             ef.call(this);
12373         }
12374     },
12375
12376         /**
12377          * Returns true if the element has any effects actively running or queued, else returns false.
12378          * @return {Boolean} True if element has active effects, else false
12379          */
12380     hasActiveFx : function(){
12381         return this.fxQueue && this.fxQueue[0];
12382     },
12383
12384         /**
12385          * Stops any running effects and clears the element's internal effects queue if it contains
12386          * any additional effects that haven't started yet.
12387          * @return {Roo.Element} The Element
12388          */
12389     stopFx : function(){
12390         if(this.hasActiveFx()){
12391             var cur = this.fxQueue[0];
12392             if(cur && cur.anim && cur.anim.isAnimated()){
12393                 this.fxQueue = [cur]; // clear out others
12394                 cur.anim.stop(true);
12395             }
12396         }
12397         return this;
12398     },
12399
12400         /* @private */
12401     beforeFx : function(o){
12402         if(this.hasActiveFx() && !o.concurrent){
12403            if(o.stopFx){
12404                this.stopFx();
12405                return true;
12406            }
12407            return false;
12408         }
12409         return true;
12410     },
12411
12412         /**
12413          * Returns true if the element is currently blocking so that no other effect can be queued
12414          * until this effect is finished, else returns false if blocking is not set.  This is commonly
12415          * used to ensure that an effect initiated by a user action runs to completion prior to the
12416          * same effect being restarted (e.g., firing only one effect even if the user clicks several times).
12417          * @return {Boolean} True if blocking, else false
12418          */
12419     hasFxBlock : function(){
12420         var q = this.fxQueue;
12421         return q && q[0] && q[0].block;
12422     },
12423
12424         /* @private */
12425     queueFx : function(o, fn){
12426         if(!this.fxQueue){
12427             this.fxQueue = [];
12428         }
12429         if(!this.hasFxBlock()){
12430             Roo.applyIf(o, this.fxDefaults);
12431             if(!o.concurrent){
12432                 var run = this.beforeFx(o);
12433                 fn.block = o.block;
12434                 this.fxQueue.push(fn);
12435                 if(run){
12436                     this.nextFx();
12437                 }
12438             }else{
12439                 fn.call(this);
12440             }
12441         }
12442         return this;
12443     },
12444
12445         /* @private */
12446     fxWrap : function(pos, o, vis){
12447         var wrap;
12448         if(!o.wrap || !(wrap = Roo.get(o.wrap))){
12449             var wrapXY;
12450             if(o.fixPosition){
12451                 wrapXY = this.getXY();
12452             }
12453             var div = document.createElement("div");
12454             div.style.visibility = vis;
12455             wrap = Roo.get(this.dom.parentNode.insertBefore(div, this.dom));
12456             wrap.setPositioning(pos);
12457             if(wrap.getStyle("position") == "static"){
12458                 wrap.position("relative");
12459             }
12460             this.clearPositioning('auto');
12461             wrap.clip();
12462             wrap.dom.appendChild(this.dom);
12463             if(wrapXY){
12464                 wrap.setXY(wrapXY);
12465             }
12466         }
12467         return wrap;
12468     },
12469
12470         /* @private */
12471     fxUnwrap : function(wrap, pos, o){
12472         this.clearPositioning();
12473         this.setPositioning(pos);
12474         if(!o.wrap){
12475             wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
12476             wrap.remove();
12477         }
12478     },
12479
12480         /* @private */
12481     getFxRestore : function(){
12482         var st = this.dom.style;
12483         return {pos: this.getPositioning(), width: st.width, height : st.height};
12484     },
12485
12486         /* @private */
12487     afterFx : function(o){
12488         if(o.afterStyle){
12489             this.applyStyles(o.afterStyle);
12490         }
12491         if(o.afterCls){
12492             this.addClass(o.afterCls);
12493         }
12494         if(o.remove === true){
12495             this.remove();
12496         }
12497         Roo.callback(o.callback, o.scope, [this]);
12498         if(!o.concurrent){
12499             this.fxQueue.shift();
12500             this.nextFx();
12501         }
12502     },
12503
12504         /* @private */
12505     getFxEl : function(){ // support for composite element fx
12506         return Roo.get(this.dom);
12507     },
12508
12509         /* @private */
12510     fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
12511         animType = animType || 'run';
12512         opt = opt || {};
12513         var anim = Roo.lib.Anim[animType](
12514             this.dom, args,
12515             (opt.duration || defaultDur) || .35,
12516             (opt.easing || defaultEase) || 'easeOut',
12517             function(){
12518                 Roo.callback(cb, this);
12519             },
12520             this
12521         );
12522         opt.anim = anim;
12523         return anim;
12524     }
12525 };
12526
12527 // backwords compat
12528 Roo.Fx.resize = Roo.Fx.scale;
12529
12530 //When included, Roo.Fx is automatically applied to Element so that all basic
12531 //effects are available directly via the Element API
12532 Roo.apply(Roo.Element.prototype, Roo.Fx);/*
12533  * Based on:
12534  * Ext JS Library 1.1.1
12535  * Copyright(c) 2006-2007, Ext JS, LLC.
12536  *
12537  * Originally Released Under LGPL - original licence link has changed is not relivant.
12538  *
12539  * Fork - LGPL
12540  * <script type="text/javascript">
12541  */
12542
12543
12544 /**
12545  * @class Roo.CompositeElement
12546  * Standard composite class. Creates a Roo.Element for every element in the collection.
12547  * <br><br>
12548  * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
12549  * actions will be performed on all the elements in this collection.</b>
12550  * <br><br>
12551  * All methods return <i>this</i> and can be chained.
12552  <pre><code>
12553  var els = Roo.select("#some-el div.some-class", true);
12554  // or select directly from an existing element
12555  var el = Roo.get('some-el');
12556  el.select('div.some-class', true);
12557
12558  els.setWidth(100); // all elements become 100 width
12559  els.hide(true); // all elements fade out and hide
12560  // or
12561  els.setWidth(100).hide(true);
12562  </code></pre>
12563  */
12564 Roo.CompositeElement = function(els){
12565     this.elements = [];
12566     this.addElements(els);
12567 };
12568 Roo.CompositeElement.prototype = {
12569     isComposite: true,
12570     addElements : function(els){
12571         if(!els) {
12572             return this;
12573         }
12574         if(typeof els == "string"){
12575             els = Roo.Element.selectorFunction(els);
12576         }
12577         var yels = this.elements;
12578         var index = yels.length-1;
12579         for(var i = 0, len = els.length; i < len; i++) {
12580                 yels[++index] = Roo.get(els[i]);
12581         }
12582         return this;
12583     },
12584
12585     /**
12586     * Clears this composite and adds the elements returned by the passed selector.
12587     * @param {String/Array} els A string CSS selector, an array of elements or an element
12588     * @return {CompositeElement} this
12589     */
12590     fill : function(els){
12591         this.elements = [];
12592         this.add(els);
12593         return this;
12594     },
12595
12596     /**
12597     * Filters this composite to only elements that match the passed selector.
12598     * @param {String} selector A string CSS selector
12599     * @param {Boolean} inverse return inverse filter (not matches)
12600     * @return {CompositeElement} this
12601     */
12602     filter : function(selector, inverse){
12603         var els = [];
12604         inverse = inverse || false;
12605         this.each(function(el){
12606             var match = inverse ? !el.is(selector) : el.is(selector);
12607             if(match){
12608                 els[els.length] = el.dom;
12609             }
12610         });
12611         this.fill(els);
12612         return this;
12613     },
12614
12615     invoke : function(fn, args){
12616         var els = this.elements;
12617         for(var i = 0, len = els.length; i < len; i++) {
12618                 Roo.Element.prototype[fn].apply(els[i], args);
12619         }
12620         return this;
12621     },
12622     /**
12623     * Adds elements to this composite.
12624     * @param {String/Array} els A string CSS selector, an array of elements or an element
12625     * @return {CompositeElement} this
12626     */
12627     add : function(els){
12628         if(typeof els == "string"){
12629             this.addElements(Roo.Element.selectorFunction(els));
12630         }else if(els.length !== undefined){
12631             this.addElements(els);
12632         }else{
12633             this.addElements([els]);
12634         }
12635         return this;
12636     },
12637     /**
12638     * Calls the passed function passing (el, this, index) for each element in this composite.
12639     * @param {Function} fn The function to call
12640     * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12641     * @return {CompositeElement} this
12642     */
12643     each : function(fn, scope){
12644         var els = this.elements;
12645         for(var i = 0, len = els.length; i < len; i++){
12646             if(fn.call(scope || els[i], els[i], this, i) === false) {
12647                 break;
12648             }
12649         }
12650         return this;
12651     },
12652
12653     /**
12654      * Returns the Element object at the specified index
12655      * @param {Number} index
12656      * @return {Roo.Element}
12657      */
12658     item : function(index){
12659         return this.elements[index] || null;
12660     },
12661
12662     /**
12663      * Returns the first Element
12664      * @return {Roo.Element}
12665      */
12666     first : function(){
12667         return this.item(0);
12668     },
12669
12670     /**
12671      * Returns the last Element
12672      * @return {Roo.Element}
12673      */
12674     last : function(){
12675         return this.item(this.elements.length-1);
12676     },
12677
12678     /**
12679      * Returns the number of elements in this composite
12680      * @return Number
12681      */
12682     getCount : function(){
12683         return this.elements.length;
12684     },
12685
12686     /**
12687      * Returns true if this composite contains the passed element
12688      * @return Boolean
12689      */
12690     contains : function(el){
12691         return this.indexOf(el) !== -1;
12692     },
12693
12694     /**
12695      * Returns true if this composite contains the passed element
12696      * @return Boolean
12697      */
12698     indexOf : function(el){
12699         return this.elements.indexOf(Roo.get(el));
12700     },
12701
12702
12703     /**
12704     * Removes the specified element(s).
12705     * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
12706     * or an array of any of those.
12707     * @param {Boolean} removeDom (optional) True to also remove the element from the document
12708     * @return {CompositeElement} this
12709     */
12710     removeElement : function(el, removeDom){
12711         if(el instanceof Array){
12712             for(var i = 0, len = el.length; i < len; i++){
12713                 this.removeElement(el[i]);
12714             }
12715             return this;
12716         }
12717         var index = typeof el == 'number' ? el : this.indexOf(el);
12718         if(index !== -1){
12719             if(removeDom){
12720                 var d = this.elements[index];
12721                 if(d.dom){
12722                     d.remove();
12723                 }else{
12724                     d.parentNode.removeChild(d);
12725                 }
12726             }
12727             this.elements.splice(index, 1);
12728         }
12729         return this;
12730     },
12731
12732     /**
12733     * Replaces the specified element with the passed element.
12734     * @param {String/HTMLElement/Element/Number} el The id of an element, the Element itself, the index of the element in this composite
12735     * to replace.
12736     * @param {String/HTMLElement/Element} replacement The id of an element or the Element itself.
12737     * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
12738     * @return {CompositeElement} this
12739     */
12740     replaceElement : function(el, replacement, domReplace){
12741         var index = typeof el == 'number' ? el : this.indexOf(el);
12742         if(index !== -1){
12743             if(domReplace){
12744                 this.elements[index].replaceWith(replacement);
12745             }else{
12746                 this.elements.splice(index, 1, Roo.get(replacement))
12747             }
12748         }
12749         return this;
12750     },
12751
12752     /**
12753      * Removes all elements.
12754      */
12755     clear : function(){
12756         this.elements = [];
12757     }
12758 };
12759 (function(){
12760     Roo.CompositeElement.createCall = function(proto, fnName){
12761         if(!proto[fnName]){
12762             proto[fnName] = function(){
12763                 return this.invoke(fnName, arguments);
12764             };
12765         }
12766     };
12767     for(var fnName in Roo.Element.prototype){
12768         if(typeof Roo.Element.prototype[fnName] == "function"){
12769             Roo.CompositeElement.createCall(Roo.CompositeElement.prototype, fnName);
12770         }
12771     };
12772 })();
12773 /*
12774  * Based on:
12775  * Ext JS Library 1.1.1
12776  * Copyright(c) 2006-2007, Ext JS, LLC.
12777  *
12778  * Originally Released Under LGPL - original licence link has changed is not relivant.
12779  *
12780  * Fork - LGPL
12781  * <script type="text/javascript">
12782  */
12783
12784 /**
12785  * @class Roo.CompositeElementLite
12786  * @extends Roo.CompositeElement
12787  * Flyweight composite class. Reuses the same Roo.Element for element operations.
12788  <pre><code>
12789  var els = Roo.select("#some-el div.some-class");
12790  // or select directly from an existing element
12791  var el = Roo.get('some-el');
12792  el.select('div.some-class');
12793
12794  els.setWidth(100); // all elements become 100 width
12795  els.hide(true); // all elements fade out and hide
12796  // or
12797  els.setWidth(100).hide(true);
12798  </code></pre><br><br>
12799  * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
12800  * actions will be performed on all the elements in this collection.</b>
12801  */
12802 Roo.CompositeElementLite = function(els){
12803     Roo.CompositeElementLite.superclass.constructor.call(this, els);
12804     this.el = new Roo.Element.Flyweight();
12805 };
12806 Roo.extend(Roo.CompositeElementLite, Roo.CompositeElement, {
12807     addElements : function(els){
12808         if(els){
12809             if(els instanceof Array){
12810                 this.elements = this.elements.concat(els);
12811             }else{
12812                 var yels = this.elements;
12813                 var index = yels.length-1;
12814                 for(var i = 0, len = els.length; i < len; i++) {
12815                     yels[++index] = els[i];
12816                 }
12817             }
12818         }
12819         return this;
12820     },
12821     invoke : function(fn, args){
12822         var els = this.elements;
12823         var el = this.el;
12824         for(var i = 0, len = els.length; i < len; i++) {
12825             el.dom = els[i];
12826                 Roo.Element.prototype[fn].apply(el, args);
12827         }
12828         return this;
12829     },
12830     /**
12831      * Returns a flyweight Element of the dom element object at the specified index
12832      * @param {Number} index
12833      * @return {Roo.Element}
12834      */
12835     item : function(index){
12836         if(!this.elements[index]){
12837             return null;
12838         }
12839         this.el.dom = this.elements[index];
12840         return this.el;
12841     },
12842
12843     // fixes scope with flyweight
12844     addListener : function(eventName, handler, scope, opt){
12845         var els = this.elements;
12846         for(var i = 0, len = els.length; i < len; i++) {
12847             Roo.EventManager.on(els[i], eventName, handler, scope || els[i], opt);
12848         }
12849         return this;
12850     },
12851
12852     /**
12853     * Calls the passed function passing (el, this, index) for each element in this composite. <b>The element
12854     * passed is the flyweight (shared) Roo.Element instance, so if you require a
12855     * a reference to the dom node, use el.dom.</b>
12856     * @param {Function} fn The function to call
12857     * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12858     * @return {CompositeElement} this
12859     */
12860     each : function(fn, scope){
12861         var els = this.elements;
12862         var el = this.el;
12863         for(var i = 0, len = els.length; i < len; i++){
12864             el.dom = els[i];
12865                 if(fn.call(scope || el, el, this, i) === false){
12866                 break;
12867             }
12868         }
12869         return this;
12870     },
12871
12872     indexOf : function(el){
12873         return this.elements.indexOf(Roo.getDom(el));
12874     },
12875
12876     replaceElement : function(el, replacement, domReplace){
12877         var index = typeof el == 'number' ? el : this.indexOf(el);
12878         if(index !== -1){
12879             replacement = Roo.getDom(replacement);
12880             if(domReplace){
12881                 var d = this.elements[index];
12882                 d.parentNode.insertBefore(replacement, d);
12883                 d.parentNode.removeChild(d);
12884             }
12885             this.elements.splice(index, 1, replacement);
12886         }
12887         return this;
12888     }
12889 });
12890 Roo.CompositeElementLite.prototype.on = Roo.CompositeElementLite.prototype.addListener;
12891
12892 /*
12893  * Based on:
12894  * Ext JS Library 1.1.1
12895  * Copyright(c) 2006-2007, Ext JS, LLC.
12896  *
12897  * Originally Released Under LGPL - original licence link has changed is not relivant.
12898  *
12899  * Fork - LGPL
12900  * <script type="text/javascript">
12901  */
12902
12903  
12904
12905 /**
12906  * @class Roo.data.Connection
12907  * @extends Roo.util.Observable
12908  * The class encapsulates a connection to the page's originating domain, allowing requests to be made
12909  * either to a configured URL, or to a URL specified at request time. 
12910  * 
12911  * Requests made by this class are asynchronous, and will return immediately. No data from
12912  * the server will be available to the statement immediately following the {@link #request} call.
12913  * To process returned data, use a callback in the request options object, or an event listener.
12914  * 
12915  * Note: If you are doing a file upload, you will not get a normal response object sent back to
12916  * your callback or event handler.  Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
12917  * The response object is created using the innerHTML of the IFRAME's document as the responseText
12918  * property and, if present, the IFRAME's XML document as the responseXML property.
12919  * 
12920  * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
12921  * that it be placed either inside a &lt;textarea> in an HTML document and retrieved from the responseText
12922  * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
12923  * standard DOM methods.
12924  * @constructor
12925  * @param {Object} config a configuration object.
12926  */
12927 Roo.data.Connection = function(config){
12928     Roo.apply(this, config);
12929     this.addEvents({
12930         /**
12931          * @event beforerequest
12932          * Fires before a network request is made to retrieve a data object.
12933          * @param {Connection} conn This Connection object.
12934          * @param {Object} options The options config object passed to the {@link #request} method.
12935          */
12936         "beforerequest" : true,
12937         /**
12938          * @event requestcomplete
12939          * Fires if the request was successfully completed.
12940          * @param {Connection} conn This Connection object.
12941          * @param {Object} response The XHR object containing the response data.
12942          * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12943          * @param {Object} options The options config object passed to the {@link #request} method.
12944          */
12945         "requestcomplete" : true,
12946         /**
12947          * @event requestexception
12948          * Fires if an error HTTP status was returned from the server.
12949          * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
12950          * @param {Connection} conn This Connection object.
12951          * @param {Object} response The XHR object containing the response data.
12952          * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12953          * @param {Object} options The options config object passed to the {@link #request} method.
12954          */
12955         "requestexception" : true
12956     });
12957     Roo.data.Connection.superclass.constructor.call(this);
12958 };
12959
12960 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
12961     /**
12962      * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
12963      */
12964     /**
12965      * @cfg {Object} extraParams (Optional) An object containing properties which are used as
12966      * extra parameters to each request made by this object. (defaults to undefined)
12967      */
12968     /**
12969      * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
12970      *  to each request made by this object. (defaults to undefined)
12971      */
12972     /**
12973      * @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)
12974      */
12975     /**
12976      * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
12977      */
12978     timeout : 30000,
12979     /**
12980      * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
12981      * @type Boolean
12982      */
12983     autoAbort:false,
12984
12985     /**
12986      * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
12987      * @type Boolean
12988      */
12989     disableCaching: true,
12990
12991     /**
12992      * Sends an HTTP request to a remote server.
12993      * @param {Object} options An object which may contain the following properties:<ul>
12994      * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
12995      * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
12996      * request, a url encoded string or a function to call to get either.</li>
12997      * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
12998      * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
12999      * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
13000      * The callback is called regardless of success or failure and is passed the following parameters:<ul>
13001      * <li>options {Object} The parameter to the request call.</li>
13002      * <li>success {Boolean} True if the request succeeded.</li>
13003      * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
13004      * </ul></li>
13005      * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
13006      * The callback is passed the following parameters:<ul>
13007      * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
13008      * <li>options {Object} The parameter to the request call.</li>
13009      * </ul></li>
13010      * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
13011      * The callback is passed the following parameters:<ul>
13012      * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
13013      * <li>options {Object} The parameter to the request call.</li>
13014      * </ul></li>
13015      * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
13016      * for the callback function. Defaults to the browser window.</li>
13017      * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
13018      * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
13019      * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
13020      * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
13021      * params for the post data. Any params will be appended to the URL.</li>
13022      * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
13023      * </ul>
13024      * @return {Number} transactionId
13025      */
13026     request : function(o){
13027         if(this.fireEvent("beforerequest", this, o) !== false){
13028             var p = o.params;
13029
13030             if(typeof p == "function"){
13031                 p = p.call(o.scope||window, o);
13032             }
13033             if(typeof p == "object"){
13034                 p = Roo.urlEncode(o.params);
13035             }
13036             if(this.extraParams){
13037                 var extras = Roo.urlEncode(this.extraParams);
13038                 p = p ? (p + '&' + extras) : extras;
13039             }
13040
13041             var url = o.url || this.url;
13042             if(typeof url == 'function'){
13043                 url = url.call(o.scope||window, o);
13044             }
13045
13046             if(o.form){
13047                 var form = Roo.getDom(o.form);
13048                 url = url || form.action;
13049
13050                 var enctype = form.getAttribute("enctype");
13051                 
13052                 if (o.formData) {
13053                     return this.doFormDataUpload(o, url);
13054                 }
13055                 
13056                 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
13057                     return this.doFormUpload(o, p, url);
13058                 }
13059                 var f = Roo.lib.Ajax.serializeForm(form);
13060                 p = p ? (p + '&' + f) : f;
13061             }
13062             
13063             if (!o.form && o.formData) {
13064                 o.formData = o.formData === true ? new FormData() : o.formData;
13065                 for (var k in o.params) {
13066                     o.formData.append(k,o.params[k]);
13067                 }
13068                     
13069                 return this.doFormDataUpload(o, url);
13070             }
13071             
13072
13073             var hs = o.headers;
13074             if(this.defaultHeaders){
13075                 hs = Roo.apply(hs || {}, this.defaultHeaders);
13076                 if(!o.headers){
13077                     o.headers = hs;
13078                 }
13079             }
13080
13081             var cb = {
13082                 success: this.handleResponse,
13083                 failure: this.handleFailure,
13084                 scope: this,
13085                 argument: {options: o},
13086                 timeout : o.timeout || this.timeout
13087             };
13088
13089             var method = o.method||this.method||(p ? "POST" : "GET");
13090
13091             if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
13092                 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
13093             }
13094
13095             if(typeof o.autoAbort == 'boolean'){ // options gets top priority
13096                 if(o.autoAbort){
13097                     this.abort();
13098                 }
13099             }else if(this.autoAbort !== false){
13100                 this.abort();
13101             }
13102
13103             if((method == 'GET' && p) || o.xmlData){
13104                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
13105                 p = '';
13106             }
13107             Roo.lib.Ajax.useDefaultHeader = typeof(o.headers) == 'undefined' || typeof(o.headers['Content-Type']) == 'undefined';
13108             this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
13109             Roo.lib.Ajax.useDefaultHeader == true;
13110             return this.transId;
13111         }else{
13112             Roo.callback(o.callback, o.scope, [o, null, null]);
13113             return null;
13114         }
13115     },
13116
13117     /**
13118      * Determine whether this object has a request outstanding.
13119      * @param {Number} transactionId (Optional) defaults to the last transaction
13120      * @return {Boolean} True if there is an outstanding request.
13121      */
13122     isLoading : function(transId){
13123         if(transId){
13124             return Roo.lib.Ajax.isCallInProgress(transId);
13125         }else{
13126             return this.transId ? true : false;
13127         }
13128     },
13129
13130     /**
13131      * Aborts any outstanding request.
13132      * @param {Number} transactionId (Optional) defaults to the last transaction
13133      */
13134     abort : function(transId){
13135         if(transId || this.isLoading()){
13136             Roo.lib.Ajax.abort(transId || this.transId);
13137         }
13138     },
13139
13140     // private
13141     handleResponse : function(response){
13142         this.transId = false;
13143         var options = response.argument.options;
13144         response.argument = options ? options.argument : null;
13145         this.fireEvent("requestcomplete", this, response, options);
13146         Roo.callback(options.success, options.scope, [response, options]);
13147         Roo.callback(options.callback, options.scope, [options, true, response]);
13148     },
13149
13150     // private
13151     handleFailure : function(response, e){
13152         this.transId = false;
13153         var options = response.argument.options;
13154         response.argument = options ? options.argument : null;
13155         this.fireEvent("requestexception", this, response, options, e);
13156         Roo.callback(options.failure, options.scope, [response, options]);
13157         Roo.callback(options.callback, options.scope, [options, false, response]);
13158     },
13159
13160     // private
13161     doFormUpload : function(o, ps, url){
13162         var id = Roo.id();
13163         var frame = document.createElement('iframe');
13164         frame.id = id;
13165         frame.name = id;
13166         frame.className = 'x-hidden';
13167         if(Roo.isIE){
13168             frame.src = Roo.SSL_SECURE_URL;
13169         }
13170         document.body.appendChild(frame);
13171
13172         if(Roo.isIE){
13173            document.frames[id].name = id;
13174         }
13175
13176         var form = Roo.getDom(o.form);
13177         form.target = id;
13178         form.method = 'POST';
13179         form.enctype = form.encoding = 'multipart/form-data';
13180         if(url){
13181             form.action = url;
13182         }
13183
13184         var hiddens, hd;
13185         if(ps){ // add dynamic params
13186             hiddens = [];
13187             ps = Roo.urlDecode(ps, false);
13188             for(var k in ps){
13189                 if(ps.hasOwnProperty(k)){
13190                     hd = document.createElement('input');
13191                     hd.type = 'hidden';
13192                     hd.name = k;
13193                     hd.value = ps[k];
13194                     form.appendChild(hd);
13195                     hiddens.push(hd);
13196                 }
13197             }
13198         }
13199
13200         function cb(){
13201             var r = {  // bogus response object
13202                 responseText : '',
13203                 responseXML : null
13204             };
13205
13206             r.argument = o ? o.argument : null;
13207
13208             try { //
13209                 var doc;
13210                 if(Roo.isIE){
13211                     doc = frame.contentWindow.document;
13212                 }else {
13213                     doc = (frame.contentDocument || window.frames[id].document);
13214                 }
13215                 if(doc && doc.body){
13216                     r.responseText = doc.body.innerHTML;
13217                 }
13218                 if(doc && doc.XMLDocument){
13219                     r.responseXML = doc.XMLDocument;
13220                 }else {
13221                     r.responseXML = doc;
13222                 }
13223             }
13224             catch(e) {
13225                 // ignore
13226             }
13227
13228             Roo.EventManager.removeListener(frame, 'load', cb, this);
13229
13230             this.fireEvent("requestcomplete", this, r, o);
13231             Roo.callback(o.success, o.scope, [r, o]);
13232             Roo.callback(o.callback, o.scope, [o, true, r]);
13233
13234             setTimeout(function(){document.body.removeChild(frame);}, 100);
13235         }
13236
13237         Roo.EventManager.on(frame, 'load', cb, this);
13238         form.submit();
13239
13240         if(hiddens){ // remove dynamic params
13241             for(var i = 0, len = hiddens.length; i < len; i++){
13242                 form.removeChild(hiddens[i]);
13243             }
13244         }
13245     },
13246     // this is a 'formdata version???'
13247     
13248     
13249     doFormDataUpload : function(o,  url)
13250     {
13251         var formData;
13252         if (o.form) {
13253             var form =  Roo.getDom(o.form);
13254             form.enctype = form.encoding = 'multipart/form-data';
13255             formData = o.formData === true ? new FormData(form) : o.formData;
13256         } else {
13257             formData = o.formData === true ? new FormData() : o.formData;
13258         }
13259         
13260       
13261         var cb = {
13262             success: this.handleResponse,
13263             failure: this.handleFailure,
13264             scope: this,
13265             argument: {options: o},
13266             timeout : o.timeout || this.timeout
13267         };
13268  
13269         if(typeof o.autoAbort == 'boolean'){ // options gets top priority
13270             if(o.autoAbort){
13271                 this.abort();
13272             }
13273         }else if(this.autoAbort !== false){
13274             this.abort();
13275         }
13276
13277         //Roo.lib.Ajax.defaultPostHeader = null;
13278         Roo.lib.Ajax.useDefaultHeader = false;
13279         this.transId = Roo.lib.Ajax.request( "POST", url, cb,  formData, o);
13280         Roo.lib.Ajax.useDefaultHeader = true;
13281  
13282          
13283     }
13284     
13285 });
13286 /*
13287  * Based on:
13288  * Ext JS Library 1.1.1
13289  * Copyright(c) 2006-2007, Ext JS, LLC.
13290  *
13291  * Originally Released Under LGPL - original licence link has changed is not relivant.
13292  *
13293  * Fork - LGPL
13294  * <script type="text/javascript">
13295  */
13296  
13297 /**
13298  * Global Ajax request class.
13299  * 
13300  * @class Roo.Ajax
13301  * @extends Roo.data.Connection
13302  * @static
13303  * 
13304  * @cfg {String} url  The default URL to be used for requests to the server. (defaults to undefined)
13305  * @cfg {Object} extraParams  An object containing properties which are used as extra parameters to each request made by this object. (defaults to undefined)
13306  * @cfg {Object} defaultHeaders  An object containing request headers which are added to each request made by this object. (defaults to undefined)
13307  * @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)
13308  * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
13309  * @cfg {Boolean} autoAbort (Optional) Whether a new request should abort any pending requests. (defaults to false)
13310  * @cfg {Boolean} disableCaching (Optional)   True to add a unique cache-buster param to GET requests. (defaults to true)
13311  */
13312 Roo.Ajax = new Roo.data.Connection({
13313     // fix up the docs
13314     /**
13315      * @scope Roo.Ajax
13316      * @type {Boolear} 
13317      */
13318     autoAbort : false,
13319
13320     /**
13321      * Serialize the passed form into a url encoded string
13322      * @scope Roo.Ajax
13323      * @param {String/HTMLElement} form
13324      * @return {String}
13325      */
13326     serializeForm : function(form){
13327         return Roo.lib.Ajax.serializeForm(form);
13328     }
13329 });/*
13330  * Based on:
13331  * Ext JS Library 1.1.1
13332  * Copyright(c) 2006-2007, Ext JS, LLC.
13333  *
13334  * Originally Released Under LGPL - original licence link has changed is not relivant.
13335  *
13336  * Fork - LGPL
13337  * <script type="text/javascript">
13338  */
13339
13340  
13341 /**
13342  * @class Roo.UpdateManager
13343  * @extends Roo.util.Observable
13344  * Provides AJAX-style update for Element object.<br><br>
13345  * Usage:<br>
13346  * <pre><code>
13347  * // Get it from a Roo.Element object
13348  * var el = Roo.get("foo");
13349  * var mgr = el.getUpdateManager();
13350  * mgr.update("http://myserver.com/index.php", "param1=1&amp;param2=2");
13351  * ...
13352  * mgr.formUpdate("myFormId", "http://myserver.com/index.php");
13353  * <br>
13354  * // or directly (returns the same UpdateManager instance)
13355  * var mgr = new Roo.UpdateManager("myElementId");
13356  * mgr.startAutoRefresh(60, "http://myserver.com/index.php");
13357  * mgr.on("update", myFcnNeedsToKnow);
13358  * <br>
13359    // short handed call directly from the element object
13360    Roo.get("foo").load({
13361         url: "bar.php",
13362         scripts:true,
13363         params: "for=bar",
13364         text: "Loading Foo..."
13365    });
13366  * </code></pre>
13367  * @constructor
13368  * Create new UpdateManager directly.
13369  * @param {String/HTMLElement/Roo.Element} el The element to update
13370  * @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).
13371  */
13372 Roo.UpdateManager = function(el, forceNew){
13373     el = Roo.get(el);
13374     if(!forceNew && el.updateManager){
13375         return el.updateManager;
13376     }
13377     /**
13378      * The Element object
13379      * @type Roo.Element
13380      */
13381     this.el = el;
13382     /**
13383      * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
13384      * @type String
13385      */
13386     this.defaultUrl = null;
13387
13388     this.addEvents({
13389         /**
13390          * @event beforeupdate
13391          * Fired before an update is made, return false from your handler and the update is cancelled.
13392          * @param {Roo.Element} el
13393          * @param {String/Object/Function} url
13394          * @param {String/Object} params
13395          */
13396         "beforeupdate": true,
13397         /**
13398          * @event update
13399          * Fired after successful update is made.
13400          * @param {Roo.Element} el
13401          * @param {Object} oResponseObject The response Object
13402          */
13403         "update": true,
13404         /**
13405          * @event failure
13406          * Fired on update failure.
13407          * @param {Roo.Element} el
13408          * @param {Object} oResponseObject The response Object
13409          */
13410         "failure": true
13411     });
13412     var d = Roo.UpdateManager.defaults;
13413     /**
13414      * Blank page URL to use with SSL file uploads (Defaults to Roo.UpdateManager.defaults.sslBlankUrl or "about:blank").
13415      * @type String
13416      */
13417     this.sslBlankUrl = d.sslBlankUrl;
13418     /**
13419      * Whether to append unique parameter on get request to disable caching (Defaults to Roo.UpdateManager.defaults.disableCaching or false).
13420      * @type Boolean
13421      */
13422     this.disableCaching = d.disableCaching;
13423     /**
13424      * Text for loading indicator (Defaults to Roo.UpdateManager.defaults.indicatorText or '&lt;div class="loading-indicator"&gt;Loading...&lt;/div&gt;').
13425      * @type String
13426      */
13427     this.indicatorText = d.indicatorText;
13428     /**
13429      * Whether to show indicatorText when loading (Defaults to Roo.UpdateManager.defaults.showLoadIndicator or true).
13430      * @type String
13431      */
13432     this.showLoadIndicator = d.showLoadIndicator;
13433     /**
13434      * Timeout for requests or form posts in seconds (Defaults to Roo.UpdateManager.defaults.timeout or 30 seconds).
13435      * @type Number
13436      */
13437     this.timeout = d.timeout;
13438
13439     /**
13440      * True to process scripts in the output (Defaults to Roo.UpdateManager.defaults.loadScripts (false)).
13441      * @type Boolean
13442      */
13443     this.loadScripts = d.loadScripts;
13444
13445     /**
13446      * Transaction object of current executing transaction
13447      */
13448     this.transaction = null;
13449
13450     /**
13451      * @private
13452      */
13453     this.autoRefreshProcId = null;
13454     /**
13455      * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
13456      * @type Function
13457      */
13458     this.refreshDelegate = this.refresh.createDelegate(this);
13459     /**
13460      * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
13461      * @type Function
13462      */
13463     this.updateDelegate = this.update.createDelegate(this);
13464     /**
13465      * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
13466      * @type Function
13467      */
13468     this.formUpdateDelegate = this.formUpdate.createDelegate(this);
13469     /**
13470      * @private
13471      */
13472     this.successDelegate = this.processSuccess.createDelegate(this);
13473     /**
13474      * @private
13475      */
13476     this.failureDelegate = this.processFailure.createDelegate(this);
13477
13478     if(!this.renderer){
13479      /**
13480       * The renderer for this UpdateManager. Defaults to {@link Roo.UpdateManager.BasicRenderer}.
13481       */
13482     this.renderer = new Roo.UpdateManager.BasicRenderer();
13483     }
13484     
13485     Roo.UpdateManager.superclass.constructor.call(this);
13486 };
13487
13488 Roo.extend(Roo.UpdateManager, Roo.util.Observable, {
13489     /**
13490      * Get the Element this UpdateManager is bound to
13491      * @return {Roo.Element} The element
13492      */
13493     getEl : function(){
13494         return this.el;
13495     },
13496     /**
13497      * Performs an async request, updating this element with the response. If params are specified it uses POST, otherwise it uses GET.
13498      * @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:
13499 <pre><code>
13500 um.update({<br/>
13501     url: "your-url.php",<br/>
13502     params: {param1: "foo", param2: "bar"}, // or a URL encoded string<br/>
13503     callback: yourFunction,<br/>
13504     scope: yourObject, //(optional scope)  <br/>
13505     discardUrl: false, <br/>
13506     nocache: false,<br/>
13507     text: "Loading...",<br/>
13508     timeout: 30,<br/>
13509     scripts: false<br/>
13510 });
13511 </code></pre>
13512      * The only required property is url. The optional properties nocache, text and scripts
13513      * are shorthand for disableCaching, indicatorText and loadScripts and are used to set their associated property on this UpdateManager instance.
13514      * @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}
13515      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
13516      * @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.
13517      */
13518     update : function(url, params, callback, discardUrl){
13519         if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
13520             var method = this.method,
13521                 cfg;
13522             if(typeof url == "object"){ // must be config object
13523                 cfg = url;
13524                 url = cfg.url;
13525                 params = params || cfg.params;
13526                 callback = callback || cfg.callback;
13527                 discardUrl = discardUrl || cfg.discardUrl;
13528                 if(callback && cfg.scope){
13529                     callback = callback.createDelegate(cfg.scope);
13530                 }
13531                 if(typeof cfg.method != "undefined"){method = cfg.method;};
13532                 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
13533                 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
13534                 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
13535                 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
13536             }
13537             this.showLoading();
13538             if(!discardUrl){
13539                 this.defaultUrl = url;
13540             }
13541             if(typeof url == "function"){
13542                 url = url.call(this);
13543             }
13544
13545             method = method || (params ? "POST" : "GET");
13546             if(method == "GET"){
13547                 url = this.prepareUrl(url);
13548             }
13549
13550             var o = Roo.apply(cfg ||{}, {
13551                 url : url,
13552                 params: params,
13553                 success: this.successDelegate,
13554                 failure: this.failureDelegate,
13555                 callback: undefined,
13556                 timeout: (this.timeout*1000),
13557                 argument: {"url": url, "form": null, "callback": callback, "params": params}
13558             });
13559             Roo.log("updated manager called with timeout of " + o.timeout);
13560             this.transaction = Roo.Ajax.request(o);
13561         }
13562     },
13563
13564     /**
13565      * 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.
13566      * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.
13567      * @param {String/HTMLElement} form The form Id or form element
13568      * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
13569      * @param {Boolean} reset (optional) Whether to try to reset the form after the update
13570      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
13571      */
13572     formUpdate : function(form, url, reset, callback){
13573         if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
13574             if(typeof url == "function"){
13575                 url = url.call(this);
13576             }
13577             form = Roo.getDom(form);
13578             this.transaction = Roo.Ajax.request({
13579                 form: form,
13580                 url:url,
13581                 success: this.successDelegate,
13582                 failure: this.failureDelegate,
13583                 timeout: (this.timeout*1000),
13584                 argument: {"url": url, "form": form, "callback": callback, "reset": reset}
13585             });
13586             this.showLoading.defer(1, this);
13587         }
13588     },
13589
13590     /**
13591      * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
13592      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13593      */
13594     refresh : function(callback){
13595         if(this.defaultUrl == null){
13596             return;
13597         }
13598         this.update(this.defaultUrl, null, callback, true);
13599     },
13600
13601     /**
13602      * Set this element to auto refresh.
13603      * @param {Number} interval How often to update (in seconds).
13604      * @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)
13605      * @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}
13606      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13607      * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
13608      */
13609     startAutoRefresh : function(interval, url, params, callback, refreshNow){
13610         if(refreshNow){
13611             this.update(url || this.defaultUrl, params, callback, true);
13612         }
13613         if(this.autoRefreshProcId){
13614             clearInterval(this.autoRefreshProcId);
13615         }
13616         this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
13617     },
13618
13619     /**
13620      * Stop auto refresh on this element.
13621      */
13622      stopAutoRefresh : function(){
13623         if(this.autoRefreshProcId){
13624             clearInterval(this.autoRefreshProcId);
13625             delete this.autoRefreshProcId;
13626         }
13627     },
13628
13629     isAutoRefreshing : function(){
13630        return this.autoRefreshProcId ? true : false;
13631     },
13632     /**
13633      * Called to update the element to "Loading" state. Override to perform custom action.
13634      */
13635     showLoading : function(){
13636         if(this.showLoadIndicator){
13637             this.el.update(this.indicatorText);
13638         }
13639     },
13640
13641     /**
13642      * Adds unique parameter to query string if disableCaching = true
13643      * @private
13644      */
13645     prepareUrl : function(url){
13646         if(this.disableCaching){
13647             var append = "_dc=" + (new Date().getTime());
13648             if(url.indexOf("?") !== -1){
13649                 url += "&" + append;
13650             }else{
13651                 url += "?" + append;
13652             }
13653         }
13654         return url;
13655     },
13656
13657     /**
13658      * @private
13659      */
13660     processSuccess : function(response){
13661         this.transaction = null;
13662         if(response.argument.form && response.argument.reset){
13663             try{ // put in try/catch since some older FF releases had problems with this
13664                 response.argument.form.reset();
13665             }catch(e){}
13666         }
13667         if(this.loadScripts){
13668             this.renderer.render(this.el, response, this,
13669                 this.updateComplete.createDelegate(this, [response]));
13670         }else{
13671             this.renderer.render(this.el, response, this);
13672             this.updateComplete(response);
13673         }
13674     },
13675
13676     updateComplete : function(response){
13677         this.fireEvent("update", this.el, response);
13678         if(typeof response.argument.callback == "function"){
13679             response.argument.callback(this.el, true, response);
13680         }
13681     },
13682
13683     /**
13684      * @private
13685      */
13686     processFailure : function(response){
13687         this.transaction = null;
13688         this.fireEvent("failure", this.el, response);
13689         if(typeof response.argument.callback == "function"){
13690             response.argument.callback(this.el, false, response);
13691         }
13692     },
13693
13694     /**
13695      * Set the content renderer for this UpdateManager. See {@link Roo.UpdateManager.BasicRenderer#render} for more details.
13696      * @param {Object} renderer The object implementing the render() method
13697      */
13698     setRenderer : function(renderer){
13699         this.renderer = renderer;
13700     },
13701
13702     getRenderer : function(){
13703        return this.renderer;
13704     },
13705
13706     /**
13707      * Set the defaultUrl used for updates
13708      * @param {String/Function} defaultUrl The url or a function to call to get the url
13709      */
13710     setDefaultUrl : function(defaultUrl){
13711         this.defaultUrl = defaultUrl;
13712     },
13713
13714     /**
13715      * Aborts the executing transaction
13716      */
13717     abort : function(){
13718         if(this.transaction){
13719             Roo.Ajax.abort(this.transaction);
13720         }
13721     },
13722
13723     /**
13724      * Returns true if an update is in progress
13725      * @return {Boolean}
13726      */
13727     isUpdating : function(){
13728         if(this.transaction){
13729             return Roo.Ajax.isLoading(this.transaction);
13730         }
13731         return false;
13732     }
13733 });
13734
13735 /**
13736  * @class Roo.UpdateManager.defaults
13737  * @static (not really - but it helps the doc tool)
13738  * The defaults collection enables customizing the default properties of UpdateManager
13739  */
13740    Roo.UpdateManager.defaults = {
13741        /**
13742          * Timeout for requests or form posts in seconds (Defaults 30 seconds).
13743          * @type Number
13744          */
13745          timeout : 30,
13746
13747          /**
13748          * True to process scripts by default (Defaults to false).
13749          * @type Boolean
13750          */
13751         loadScripts : false,
13752
13753         /**
13754         * Blank page URL to use with SSL file uploads (Defaults to "javascript:false").
13755         * @type String
13756         */
13757         sslBlankUrl : (Roo.SSL_SECURE_URL || "javascript:false"),
13758         /**
13759          * Whether to append unique parameter on get request to disable caching (Defaults to false).
13760          * @type Boolean
13761          */
13762         disableCaching : false,
13763         /**
13764          * Whether to show indicatorText when loading (Defaults to true).
13765          * @type Boolean
13766          */
13767         showLoadIndicator : true,
13768         /**
13769          * Text for loading indicator (Defaults to '&lt;div class="loading-indicator"&gt;Loading...&lt;/div&gt;').
13770          * @type String
13771          */
13772         indicatorText : '<div class="loading-indicator">Loading...</div>'
13773    };
13774
13775 /**
13776  * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}).
13777  *Usage:
13778  * <pre><code>Roo.UpdateManager.updateElement("my-div", "stuff.php");</code></pre>
13779  * @param {String/HTMLElement/Roo.Element} el The element to update
13780  * @param {String} url The url
13781  * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
13782  * @param {Object} options (optional) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
13783  * @static
13784  * @deprecated
13785  * @member Roo.UpdateManager
13786  */
13787 Roo.UpdateManager.updateElement = function(el, url, params, options){
13788     var um = Roo.get(el, true).getUpdateManager();
13789     Roo.apply(um, options);
13790     um.update(url, params, options ? options.callback : null);
13791 };
13792 // alias for backwards compat
13793 Roo.UpdateManager.update = Roo.UpdateManager.updateElement;
13794 /**
13795  * @class Roo.UpdateManager.BasicRenderer
13796  * Default Content renderer. Updates the elements innerHTML with the responseText.
13797  */
13798 Roo.UpdateManager.BasicRenderer = function(){};
13799
13800 Roo.UpdateManager.BasicRenderer.prototype = {
13801     /**
13802      * This is called when the transaction is completed and it's time to update the element - The BasicRenderer
13803      * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),
13804      * create an object with a "render(el, response)" method and pass it to setRenderer on the UpdateManager.
13805      * @param {Roo.Element} el The element being rendered
13806      * @param {Object} response The YUI Connect response object
13807      * @param {UpdateManager} updateManager The calling update manager
13808      * @param {Function} callback A callback that will need to be called if loadScripts is true on the UpdateManager
13809      */
13810      render : function(el, response, updateManager, callback){
13811         el.update(response.responseText, updateManager.loadScripts, callback);
13812     }
13813 };
13814 /*
13815  * Based on:
13816  * Roo JS
13817  * (c)) Alan Knowles
13818  * Licence : LGPL
13819  */
13820
13821
13822 /**
13823  * @class Roo.DomTemplate
13824  * @extends Roo.Template
13825  * An effort at a dom based template engine..
13826  *
13827  * Similar to XTemplate, except it uses dom parsing to create the template..
13828  *
13829  * Supported features:
13830  *
13831  *  Tags:
13832
13833 <pre><code>
13834       {a_variable} - output encoded.
13835       {a_variable.format:("Y-m-d")} - call a method on the variable
13836       {a_variable:raw} - unencoded output
13837       {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
13838       {a_variable:this.method_on_template(...)} - call a method on the template object.
13839  
13840 </code></pre>
13841  *  The tpl tag:
13842 <pre><code>
13843         &lt;div roo-for="a_variable or condition.."&gt;&lt;/div&gt;
13844         &lt;div roo-if="a_variable or condition"&gt;&lt;/div&gt;
13845         &lt;div roo-exec="some javascript"&gt;&lt;/div&gt;
13846         &lt;div roo-name="named_template"&gt;&lt;/div&gt; 
13847   
13848 </code></pre>
13849  *      
13850  */
13851 Roo.DomTemplate = function()
13852 {
13853      Roo.DomTemplate.superclass.constructor.apply(this, arguments);
13854      if (this.html) {
13855         this.compile();
13856      }
13857 };
13858
13859
13860 Roo.extend(Roo.DomTemplate, Roo.Template, {
13861     /**
13862      * id counter for sub templates.
13863      */
13864     id : 0,
13865     /**
13866      * flag to indicate if dom parser is inside a pre,
13867      * it will strip whitespace if not.
13868      */
13869     inPre : false,
13870     
13871     /**
13872      * The various sub templates
13873      */
13874     tpls : false,
13875     
13876     
13877     
13878     /**
13879      *
13880      * basic tag replacing syntax
13881      * WORD:WORD()
13882      *
13883      * // you can fake an object call by doing this
13884      *  x.t:(test,tesT) 
13885      * 
13886      */
13887     re : /(\{|\%7B)([\w-\.]+)(?:\:([\w\.]*)(?:\(([^)]*?)?\))?)?(\}|\%7D)/g,
13888     //re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
13889     
13890     iterChild : function (node, method) {
13891         
13892         var oldPre = this.inPre;
13893         if (node.tagName == 'PRE') {
13894             this.inPre = true;
13895         }
13896         for( var i = 0; i < node.childNodes.length; i++) {
13897             method.call(this, node.childNodes[i]);
13898         }
13899         this.inPre = oldPre;
13900     },
13901     
13902     
13903     
13904     /**
13905      * compile the template
13906      *
13907      * This is not recursive, so I'm not sure how nested templates are really going to be handled..
13908      *
13909      */
13910     compile: function()
13911     {
13912         var s = this.html;
13913         
13914         // covert the html into DOM...
13915         var doc = false;
13916         var div =false;
13917         try {
13918             doc = document.implementation.createHTMLDocument("");
13919             doc.documentElement.innerHTML =   this.html  ;
13920             div = doc.documentElement;
13921         } catch (e) {
13922             // old IE... - nasty -- it causes all sorts of issues.. with
13923             // images getting pulled from server..
13924             div = document.createElement('div');
13925             div.innerHTML = this.html;
13926         }
13927         //doc.documentElement.innerHTML = htmlBody
13928          
13929         
13930         
13931         this.tpls = [];
13932         var _t = this;
13933         this.iterChild(div, function(n) {_t.compileNode(n, true); });
13934         
13935         var tpls = this.tpls;
13936         
13937         // create a top level template from the snippet..
13938         
13939         //Roo.log(div.innerHTML);
13940         
13941         var tpl = {
13942             uid : 'master',
13943             id : this.id++,
13944             attr : false,
13945             value : false,
13946             body : div.innerHTML,
13947             
13948             forCall : false,
13949             execCall : false,
13950             dom : div,
13951             isTop : true
13952             
13953         };
13954         tpls.unshift(tpl);
13955         
13956         
13957         // compile them...
13958         this.tpls = [];
13959         Roo.each(tpls, function(tp){
13960             this.compileTpl(tp);
13961             this.tpls[tp.id] = tp;
13962         }, this);
13963         
13964         this.master = tpls[0];
13965         return this;
13966         
13967         
13968     },
13969     
13970     compileNode : function(node, istop) {
13971         // test for
13972         //Roo.log(node);
13973         
13974         
13975         // skip anything not a tag..
13976         if (node.nodeType != 1) {
13977             if (node.nodeType == 3 && !this.inPre) {
13978                 // reduce white space..
13979                 node.nodeValue = node.nodeValue.replace(/\s+/g, ' '); 
13980                 
13981             }
13982             return;
13983         }
13984         
13985         var tpl = {
13986             uid : false,
13987             id : false,
13988             attr : false,
13989             value : false,
13990             body : '',
13991             
13992             forCall : false,
13993             execCall : false,
13994             dom : false,
13995             isTop : istop
13996             
13997             
13998         };
13999         
14000         
14001         switch(true) {
14002             case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
14003             case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
14004             case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
14005             case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
14006             // no default..
14007         }
14008         
14009         
14010         if (!tpl.attr) {
14011             // just itterate children..
14012             this.iterChild(node,this.compileNode);
14013             return;
14014         }
14015         tpl.uid = this.id++;
14016         tpl.value = node.getAttribute('roo-' +  tpl.attr);
14017         node.removeAttribute('roo-'+ tpl.attr);
14018         if (tpl.attr != 'name') {
14019             var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
14020             node.parentNode.replaceChild(placeholder,  node);
14021         } else {
14022             
14023             var placeholder =  document.createElement('span');
14024             placeholder.className = 'roo-tpl-' + tpl.value;
14025             node.parentNode.replaceChild(placeholder,  node);
14026         }
14027         
14028         // parent now sees '{domtplXXXX}
14029         this.iterChild(node,this.compileNode);
14030         
14031         // we should now have node body...
14032         var div = document.createElement('div');
14033         div.appendChild(node);
14034         tpl.dom = node;
14035         // this has the unfortunate side effect of converting tagged attributes
14036         // eg. href="{...}" into %7C...%7D
14037         // this has been fixed by searching for those combo's although it's a bit hacky..
14038         
14039         
14040         tpl.body = div.innerHTML;
14041         
14042         
14043          
14044         tpl.id = tpl.uid;
14045         switch(tpl.attr) {
14046             case 'for' :
14047                 switch (tpl.value) {
14048                     case '.':  tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
14049                     case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
14050                     default:   tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
14051                 }
14052                 break;
14053             
14054             case 'exec':
14055                 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
14056                 break;
14057             
14058             case 'if':     
14059                 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
14060                 break;
14061             
14062             case 'name':
14063                 tpl.id  = tpl.value; // replace non characters???
14064                 break;
14065             
14066         }
14067         
14068         
14069         this.tpls.push(tpl);
14070         
14071         
14072         
14073     },
14074     
14075     
14076     
14077     
14078     /**
14079      * Compile a segment of the template into a 'sub-template'
14080      *
14081      * 
14082      * 
14083      *
14084      */
14085     compileTpl : function(tpl)
14086     {
14087         var fm = Roo.util.Format;
14088         var useF = this.disableFormats !== true;
14089         
14090         var sep = Roo.isGecko ? "+\n" : ",\n";
14091         
14092         var undef = function(str) {
14093             Roo.debug && Roo.log("Property not found :"  + str);
14094             return '';
14095         };
14096           
14097         //Roo.log(tpl.body);
14098         
14099         
14100         
14101         var fn = function(m, lbrace, name, format, args)
14102         {
14103             //Roo.log("ARGS");
14104             //Roo.log(arguments);
14105             args = args ? args.replace(/\\'/g,"'") : args;
14106             //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
14107             if (typeof(format) == 'undefined') {
14108                 format =  'htmlEncode'; 
14109             }
14110             if (format == 'raw' ) {
14111                 format = false;
14112             }
14113             
14114             if(name.substr(0, 6) == 'domtpl'){
14115                 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
14116             }
14117             
14118             // build an array of options to determine if value is undefined..
14119             
14120             // basically get 'xxxx.yyyy' then do
14121             // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
14122             //    (function () { Roo.log("Property not found"); return ''; })() :
14123             //    ......
14124             
14125             var udef_ar = [];
14126             var lookfor = '';
14127             Roo.each(name.split('.'), function(st) {
14128                 lookfor += (lookfor.length ? '.': '') + st;
14129                 udef_ar.push(  "(typeof(" + lookfor + ") == 'undefined')"  );
14130             });
14131             
14132             var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
14133             
14134             
14135             if(format && useF){
14136                 
14137                 args = args ? ',' + args : "";
14138                  
14139                 if(format.substr(0, 5) != "this."){
14140                     format = "fm." + format + '(';
14141                 }else{
14142                     format = 'this.call("'+ format.substr(5) + '", ';
14143                     args = ", values";
14144                 }
14145                 
14146                 return "'"+ sep +   udef_st   +    format + name + args + "))"+sep+"'";
14147             }
14148              
14149             if (args && args.length) {
14150                 // called with xxyx.yuu:(test,test)
14151                 // change to ()
14152                 return "'"+ sep + udef_st  + name + '(' +  args + "))"+sep+"'";
14153             }
14154             // raw.. - :raw modifier..
14155             return "'"+ sep + udef_st  + name + ")"+sep+"'";
14156             
14157         };
14158         var body;
14159         // branched to use + in gecko and [].join() in others
14160         if(Roo.isGecko){
14161             body = "tpl.compiled = function(values, parent){  with(values) { return '" +
14162                    tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
14163                     "';};};";
14164         }else{
14165             body = ["tpl.compiled = function(values, parent){  with (values) { return ['"];
14166             body.push(tpl.body.replace(/(\r\n|\n)/g,
14167                             '\\n').replace(/'/g, "\\'").replace(this.re, fn));
14168             body.push("'].join('');};};");
14169             body = body.join('');
14170         }
14171         
14172         Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
14173        
14174         /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef  */
14175         eval(body);
14176         
14177         return this;
14178     },
14179      
14180     /**
14181      * same as applyTemplate, except it's done to one of the subTemplates
14182      * when using named templates, you can do:
14183      *
14184      * var str = pl.applySubTemplate('your-name', values);
14185      *
14186      * 
14187      * @param {Number} id of the template
14188      * @param {Object} values to apply to template
14189      * @param {Object} parent (normaly the instance of this object)
14190      */
14191     applySubTemplate : function(id, values, parent)
14192     {
14193         
14194         
14195         var t = this.tpls[id];
14196         
14197         
14198         try { 
14199             if(t.ifCall && !t.ifCall.call(this, values, parent)){
14200                 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
14201                 return '';
14202             }
14203         } catch(e) {
14204             Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
14205             Roo.log(values);
14206           
14207             return '';
14208         }
14209         try { 
14210             
14211             if(t.execCall && t.execCall.call(this, values, parent)){
14212                 return '';
14213             }
14214         } catch(e) {
14215             Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
14216             Roo.log(values);
14217             return '';
14218         }
14219         
14220         try {
14221             var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
14222             parent = t.target ? values : parent;
14223             if(t.forCall && vs instanceof Array){
14224                 var buf = [];
14225                 for(var i = 0, len = vs.length; i < len; i++){
14226                     try {
14227                         buf[buf.length] = t.compiled.call(this, vs[i], parent);
14228                     } catch (e) {
14229                         Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
14230                         Roo.log(e.body);
14231                         //Roo.log(t.compiled);
14232                         Roo.log(vs[i]);
14233                     }   
14234                 }
14235                 return buf.join('');
14236             }
14237         } catch (e) {
14238             Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
14239             Roo.log(values);
14240             return '';
14241         }
14242         try {
14243             return t.compiled.call(this, vs, parent);
14244         } catch (e) {
14245             Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
14246             Roo.log(e.body);
14247             //Roo.log(t.compiled);
14248             Roo.log(values);
14249             return '';
14250         }
14251     },
14252
14253    
14254
14255     applyTemplate : function(values){
14256         return this.master.compiled.call(this, values, {});
14257         //var s = this.subs;
14258     },
14259
14260     apply : function(){
14261         return this.applyTemplate.apply(this, arguments);
14262     }
14263
14264  });
14265
14266 Roo.DomTemplate.from = function(el){
14267     el = Roo.getDom(el);
14268     return new Roo.Domtemplate(el.value || el.innerHTML);
14269 };/*
14270  * Based on:
14271  * Ext JS Library 1.1.1
14272  * Copyright(c) 2006-2007, Ext JS, LLC.
14273  *
14274  * Originally Released Under LGPL - original licence link has changed is not relivant.
14275  *
14276  * Fork - LGPL
14277  * <script type="text/javascript">
14278  */
14279
14280 /**
14281  * @class Roo.util.DelayedTask
14282  * Provides a convenient method of performing setTimeout where a new
14283  * timeout cancels the old timeout. An example would be performing validation on a keypress.
14284  * You can use this class to buffer
14285  * the keypress events for a certain number of milliseconds, and perform only if they stop
14286  * for that amount of time.
14287  * @constructor The parameters to this constructor serve as defaults and are not required.
14288  * @param {Function} fn (optional) The default function to timeout
14289  * @param {Object} scope (optional) The default scope of that timeout
14290  * @param {Array} args (optional) The default Array of arguments
14291  */
14292 Roo.util.DelayedTask = function(fn, scope, args){
14293     var id = null, d, t;
14294
14295     var call = function(){
14296         var now = new Date().getTime();
14297         if(now - t >= d){
14298             clearInterval(id);
14299             id = null;
14300             fn.apply(scope, args || []);
14301         }
14302     };
14303     /**
14304      * Cancels any pending timeout and queues a new one
14305      * @param {Number} delay The milliseconds to delay
14306      * @param {Function} newFn (optional) Overrides function passed to constructor
14307      * @param {Object} newScope (optional) Overrides scope passed to constructor
14308      * @param {Array} newArgs (optional) Overrides args passed to constructor
14309      */
14310     this.delay = function(delay, newFn, newScope, newArgs){
14311         if(id && delay != d){
14312             this.cancel();
14313         }
14314         d = delay;
14315         t = new Date().getTime();
14316         fn = newFn || fn;
14317         scope = newScope || scope;
14318         args = newArgs || args;
14319         if(!id){
14320             id = setInterval(call, d);
14321         }
14322     };
14323
14324     /**
14325      * Cancel the last queued timeout
14326      */
14327     this.cancel = function(){
14328         if(id){
14329             clearInterval(id);
14330             id = null;
14331         }
14332     };
14333 };/*
14334  * Based on:
14335  * Ext JS Library 1.1.1
14336  * Copyright(c) 2006-2007, Ext JS, LLC.
14337  *
14338  * Originally Released Under LGPL - original licence link has changed is not relivant.
14339  *
14340  * Fork - LGPL
14341  * <script type="text/javascript">
14342  */
14343 /**
14344  * @class Roo.util.TaskRunner
14345  * Manage background tasks - not sure why this is better that setInterval?
14346  * @static
14347  *
14348  */
14349  
14350 Roo.util.TaskRunner = function(interval){
14351     interval = interval || 10;
14352     var tasks = [], removeQueue = [];
14353     var id = 0;
14354     var running = false;
14355
14356     var stopThread = function(){
14357         running = false;
14358         clearInterval(id);
14359         id = 0;
14360     };
14361
14362     var startThread = function(){
14363         if(!running){
14364             running = true;
14365             id = setInterval(runTasks, interval);
14366         }
14367     };
14368
14369     var removeTask = function(task){
14370         removeQueue.push(task);
14371         if(task.onStop){
14372             task.onStop();
14373         }
14374     };
14375
14376     var runTasks = function(){
14377         if(removeQueue.length > 0){
14378             for(var i = 0, len = removeQueue.length; i < len; i++){
14379                 tasks.remove(removeQueue[i]);
14380             }
14381             removeQueue = [];
14382             if(tasks.length < 1){
14383                 stopThread();
14384                 return;
14385             }
14386         }
14387         var now = new Date().getTime();
14388         for(var i = 0, len = tasks.length; i < len; ++i){
14389             var t = tasks[i];
14390             var itime = now - t.taskRunTime;
14391             if(t.interval <= itime){
14392                 var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
14393                 t.taskRunTime = now;
14394                 if(rt === false || t.taskRunCount === t.repeat){
14395                     removeTask(t);
14396                     return;
14397                 }
14398             }
14399             if(t.duration && t.duration <= (now - t.taskStartTime)){
14400                 removeTask(t);
14401             }
14402         }
14403     };
14404
14405     /**
14406      * Queues a new task.
14407      * @param {Object} task
14408      *
14409      * Task property : interval = how frequent to run.
14410      * Task object should implement
14411      * function run()
14412      * Task object may implement
14413      * function onStop()
14414      */
14415     this.start = function(task){
14416         tasks.push(task);
14417         task.taskStartTime = new Date().getTime();
14418         task.taskRunTime = 0;
14419         task.taskRunCount = 0;
14420         startThread();
14421         return task;
14422     };
14423     /**
14424      * Stop  new task.
14425      * @param {Object} task
14426      */
14427     this.stop = function(task){
14428         removeTask(task);
14429         return task;
14430     };
14431     /**
14432      * Stop all Tasks
14433      */
14434     this.stopAll = function(){
14435         stopThread();
14436         for(var i = 0, len = tasks.length; i < len; i++){
14437             if(tasks[i].onStop){
14438                 tasks[i].onStop();
14439             }
14440         }
14441         tasks = [];
14442         removeQueue = [];
14443     };
14444 };
14445
14446 Roo.TaskMgr = new Roo.util.TaskRunner();/*
14447  * Based on:
14448  * Ext JS Library 1.1.1
14449  * Copyright(c) 2006-2007, Ext JS, LLC.
14450  *
14451  * Originally Released Under LGPL - original licence link has changed is not relivant.
14452  *
14453  * Fork - LGPL
14454  * <script type="text/javascript">
14455  */
14456
14457  
14458 /**
14459  * @class Roo.util.MixedCollection
14460  * @extends Roo.util.Observable
14461  * A Collection class that maintains both numeric indexes and keys and exposes events.
14462  * @constructor
14463  * @param {Boolean} allowFunctions True if the addAll function should add function references to the
14464  * collection (defaults to false)
14465  * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
14466  * and return the key value for that item.  This is used when available to look up the key on items that
14467  * were passed without an explicit key parameter to a MixedCollection method.  Passing this parameter is
14468  * equivalent to providing an implementation for the {@link #getKey} method.
14469  */
14470 Roo.util.MixedCollection = function(allowFunctions, keyFn){
14471     this.items = [];
14472     this.map = {};
14473     this.keys = [];
14474     this.length = 0;
14475     this.addEvents({
14476         /**
14477          * @event clear
14478          * Fires when the collection is cleared.
14479          */
14480         "clear" : true,
14481         /**
14482          * @event add
14483          * Fires when an item is added to the collection.
14484          * @param {Number} index The index at which the item was added.
14485          * @param {Object} o The item added.
14486          * @param {String} key The key associated with the added item.
14487          */
14488         "add" : true,
14489         /**
14490          * @event replace
14491          * Fires when an item is replaced in the collection.
14492          * @param {String} key he key associated with the new added.
14493          * @param {Object} old The item being replaced.
14494          * @param {Object} new The new item.
14495          */
14496         "replace" : true,
14497         /**
14498          * @event remove
14499          * Fires when an item is removed from the collection.
14500          * @param {Object} o The item being removed.
14501          * @param {String} key (optional) The key associated with the removed item.
14502          */
14503         "remove" : true,
14504         "sort" : true
14505     });
14506     this.allowFunctions = allowFunctions === true;
14507     if(keyFn){
14508         this.getKey = keyFn;
14509     }
14510     Roo.util.MixedCollection.superclass.constructor.call(this);
14511 };
14512
14513 Roo.extend(Roo.util.MixedCollection, Roo.util.Observable, {
14514     allowFunctions : false,
14515     
14516 /**
14517  * Adds an item to the collection.
14518  * @param {String} key The key to associate with the item
14519  * @param {Object} o The item to add.
14520  * @return {Object} The item added.
14521  */
14522     add : function(key, o){
14523         if(arguments.length == 1){
14524             o = arguments[0];
14525             key = this.getKey(o);
14526         }
14527         if(typeof key == "undefined" || key === null){
14528             this.length++;
14529             this.items.push(o);
14530             this.keys.push(null);
14531         }else{
14532             var old = this.map[key];
14533             if(old){
14534                 return this.replace(key, o);
14535             }
14536             this.length++;
14537             this.items.push(o);
14538             this.map[key] = o;
14539             this.keys.push(key);
14540         }
14541         this.fireEvent("add", this.length-1, o, key);
14542         return o;
14543     },
14544        
14545 /**
14546   * MixedCollection has a generic way to fetch keys if you implement getKey.
14547 <pre><code>
14548 // normal way
14549 var mc = new Roo.util.MixedCollection();
14550 mc.add(someEl.dom.id, someEl);
14551 mc.add(otherEl.dom.id, otherEl);
14552 //and so on
14553
14554 // using getKey
14555 var mc = new Roo.util.MixedCollection();
14556 mc.getKey = function(el){
14557    return el.dom.id;
14558 };
14559 mc.add(someEl);
14560 mc.add(otherEl);
14561
14562 // or via the constructor
14563 var mc = new Roo.util.MixedCollection(false, function(el){
14564    return el.dom.id;
14565 });
14566 mc.add(someEl);
14567 mc.add(otherEl);
14568 </code></pre>
14569  * @param o {Object} The item for which to find the key.
14570  * @return {Object} The key for the passed item.
14571  */
14572     getKey : function(o){
14573          return o.id; 
14574     },
14575    
14576 /**
14577  * Replaces an item in the collection.
14578  * @param {String} key The key associated with the item to replace, or the item to replace.
14579  * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate with that key.
14580  * @return {Object}  The new item.
14581  */
14582     replace : function(key, o){
14583         if(arguments.length == 1){
14584             o = arguments[0];
14585             key = this.getKey(o);
14586         }
14587         var old = this.item(key);
14588         if(typeof key == "undefined" || key === null || typeof old == "undefined"){
14589              return this.add(key, o);
14590         }
14591         var index = this.indexOfKey(key);
14592         this.items[index] = o;
14593         this.map[key] = o;
14594         this.fireEvent("replace", key, old, o);
14595         return o;
14596     },
14597    
14598 /**
14599  * Adds all elements of an Array or an Object to the collection.
14600  * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
14601  * an Array of values, each of which are added to the collection.
14602  */
14603     addAll : function(objs){
14604         if(arguments.length > 1 || objs instanceof Array){
14605             var args = arguments.length > 1 ? arguments : objs;
14606             for(var i = 0, len = args.length; i < len; i++){
14607                 this.add(args[i]);
14608             }
14609         }else{
14610             for(var key in objs){
14611                 if(this.allowFunctions || typeof objs[key] != "function"){
14612                     this.add(key, objs[key]);
14613                 }
14614             }
14615         }
14616     },
14617    
14618 /**
14619  * Executes the specified function once for every item in the collection, passing each
14620  * item as the first and only parameter. returning false from the function will stop the iteration.
14621  * @param {Function} fn The function to execute for each item.
14622  * @param {Object} scope (optional) The scope in which to execute the function.
14623  */
14624     each : function(fn, scope){
14625         var items = [].concat(this.items); // each safe for removal
14626         for(var i = 0, len = items.length; i < len; i++){
14627             if(fn.call(scope || items[i], items[i], i, len) === false){
14628                 break;
14629             }
14630         }
14631     },
14632    
14633 /**
14634  * Executes the specified function once for every key in the collection, passing each
14635  * key, and its associated item as the first two parameters.
14636  * @param {Function} fn The function to execute for each item.
14637  * @param {Object} scope (optional) The scope in which to execute the function.
14638  */
14639     eachKey : function(fn, scope){
14640         for(var i = 0, len = this.keys.length; i < len; i++){
14641             fn.call(scope || window, this.keys[i], this.items[i], i, len);
14642         }
14643     },
14644    
14645 /**
14646  * Returns the first item in the collection which elicits a true return value from the
14647  * passed selection function.
14648  * @param {Function} fn The selection function to execute for each item.
14649  * @param {Object} scope (optional) The scope in which to execute the function.
14650  * @return {Object} The first item in the collection which returned true from the selection function.
14651  */
14652     find : function(fn, scope){
14653         for(var i = 0, len = this.items.length; i < len; i++){
14654             if(fn.call(scope || window, this.items[i], this.keys[i])){
14655                 return this.items[i];
14656             }
14657         }
14658         return null;
14659     },
14660    
14661 /**
14662  * Inserts an item at the specified index in the collection.
14663  * @param {Number} index The index to insert the item at.
14664  * @param {String} key The key to associate with the new item, or the item itself.
14665  * @param {Object} o  (optional) If the second parameter was a key, the new item.
14666  * @return {Object} The item inserted.
14667  */
14668     insert : function(index, key, o){
14669         if(arguments.length == 2){
14670             o = arguments[1];
14671             key = this.getKey(o);
14672         }
14673         if(index >= this.length){
14674             return this.add(key, o);
14675         }
14676         this.length++;
14677         this.items.splice(index, 0, o);
14678         if(typeof key != "undefined" && key != null){
14679             this.map[key] = o;
14680         }
14681         this.keys.splice(index, 0, key);
14682         this.fireEvent("add", index, o, key);
14683         return o;
14684     },
14685    
14686 /**
14687  * Removed an item from the collection.
14688  * @param {Object} o The item to remove.
14689  * @return {Object} The item removed.
14690  */
14691     remove : function(o){
14692         return this.removeAt(this.indexOf(o));
14693     },
14694    
14695 /**
14696  * Remove an item from a specified index in the collection.
14697  * @param {Number} index The index within the collection of the item to remove.
14698  */
14699     removeAt : function(index){
14700         if(index < this.length && index >= 0){
14701             this.length--;
14702             var o = this.items[index];
14703             this.items.splice(index, 1);
14704             var key = this.keys[index];
14705             if(typeof key != "undefined"){
14706                 delete this.map[key];
14707             }
14708             this.keys.splice(index, 1);
14709             this.fireEvent("remove", o, key);
14710         }
14711     },
14712    
14713 /**
14714  * Removed an item associated with the passed key fom the collection.
14715  * @param {String} key The key of the item to remove.
14716  */
14717     removeKey : function(key){
14718         return this.removeAt(this.indexOfKey(key));
14719     },
14720    
14721 /**
14722  * Returns the number of items in the collection.
14723  * @return {Number} the number of items in the collection.
14724  */
14725     getCount : function(){
14726         return this.length; 
14727     },
14728    
14729 /**
14730  * Returns index within the collection of the passed Object.
14731  * @param {Object} o The item to find the index of.
14732  * @return {Number} index of the item.
14733  */
14734     indexOf : function(o){
14735         if(!this.items.indexOf){
14736             for(var i = 0, len = this.items.length; i < len; i++){
14737                 if(this.items[i] == o) {
14738                     return i;
14739                 }
14740             }
14741             return -1;
14742         }else{
14743             return this.items.indexOf(o);
14744         }
14745     },
14746    
14747 /**
14748  * Returns index within the collection of the passed key.
14749  * @param {String} key The key to find the index of.
14750  * @return {Number} index of the key.
14751  */
14752     indexOfKey : function(key){
14753         if(!this.keys.indexOf){
14754             for(var i = 0, len = this.keys.length; i < len; i++){
14755                 if(this.keys[i] == key) {
14756                     return i;
14757                 }
14758             }
14759             return -1;
14760         }else{
14761             return this.keys.indexOf(key);
14762         }
14763     },
14764    
14765 /**
14766  * Returns the item associated with the passed key OR index. Key has priority over index.
14767  * @param {String/Number} key The key or index of the item.
14768  * @return {Object} The item associated with the passed key.
14769  */
14770     item : function(key){
14771         if (key === 'length') {
14772             return null;
14773         }
14774         var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
14775         return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
14776     },
14777     
14778 /**
14779  * Returns the item at the specified index.
14780  * @param {Number} index The index of the item.
14781  * @return {Object}
14782  */
14783     itemAt : function(index){
14784         return this.items[index];
14785     },
14786     
14787 /**
14788  * Returns the item associated with the passed key.
14789  * @param {String/Number} key The key of the item.
14790  * @return {Object} The item associated with the passed key.
14791  */
14792     key : function(key){
14793         return this.map[key];
14794     },
14795    
14796 /**
14797  * Returns true if the collection contains the passed Object as an item.
14798  * @param {Object} o  The Object to look for in the collection.
14799  * @return {Boolean} True if the collection contains the Object as an item.
14800  */
14801     contains : function(o){
14802         return this.indexOf(o) != -1;
14803     },
14804    
14805 /**
14806  * Returns true if the collection contains the passed Object as a key.
14807  * @param {String} key The key to look for in the collection.
14808  * @return {Boolean} True if the collection contains the Object as a key.
14809  */
14810     containsKey : function(key){
14811         return typeof this.map[key] != "undefined";
14812     },
14813    
14814 /**
14815  * Removes all items from the collection.
14816  */
14817     clear : function(){
14818         this.length = 0;
14819         this.items = [];
14820         this.keys = [];
14821         this.map = {};
14822         this.fireEvent("clear");
14823     },
14824    
14825 /**
14826  * Returns the first item in the collection.
14827  * @return {Object} the first item in the collection..
14828  */
14829     first : function(){
14830         return this.items[0]; 
14831     },
14832    
14833 /**
14834  * Returns the last item in the collection.
14835  * @return {Object} the last item in the collection..
14836  */
14837     last : function(){
14838         return this.items[this.length-1];   
14839     },
14840     
14841     _sort : function(property, dir, fn){
14842         var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
14843         fn = fn || function(a, b){
14844             return a-b;
14845         };
14846         var c = [], k = this.keys, items = this.items;
14847         for(var i = 0, len = items.length; i < len; i++){
14848             c[c.length] = {key: k[i], value: items[i], index: i};
14849         }
14850         c.sort(function(a, b){
14851             var v = fn(a[property], b[property]) * dsc;
14852             if(v == 0){
14853                 v = (a.index < b.index ? -1 : 1);
14854             }
14855             return v;
14856         });
14857         for(var i = 0, len = c.length; i < len; i++){
14858             items[i] = c[i].value;
14859             k[i] = c[i].key;
14860         }
14861         this.fireEvent("sort", this);
14862     },
14863     
14864     /**
14865      * Sorts this collection with the passed comparison function
14866      * @param {String} direction (optional) "ASC" or "DESC"
14867      * @param {Function} fn (optional) comparison function
14868      */
14869     sort : function(dir, fn){
14870         this._sort("value", dir, fn);
14871     },
14872     
14873     /**
14874      * Sorts this collection by keys
14875      * @param {String} direction (optional) "ASC" or "DESC"
14876      * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
14877      */
14878     keySort : function(dir, fn){
14879         this._sort("key", dir, fn || function(a, b){
14880             return String(a).toUpperCase()-String(b).toUpperCase();
14881         });
14882     },
14883     
14884     /**
14885      * Returns a range of items in this collection
14886      * @param {Number} startIndex (optional) defaults to 0
14887      * @param {Number} endIndex (optional) default to the last item
14888      * @return {Array} An array of items
14889      */
14890     getRange : function(start, end){
14891         var items = this.items;
14892         if(items.length < 1){
14893             return [];
14894         }
14895         start = start || 0;
14896         end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
14897         var r = [];
14898         if(start <= end){
14899             for(var i = start; i <= end; i++) {
14900                     r[r.length] = items[i];
14901             }
14902         }else{
14903             for(var i = start; i >= end; i--) {
14904                     r[r.length] = items[i];
14905             }
14906         }
14907         return r;
14908     },
14909         
14910     /**
14911      * Filter the <i>objects</i> in this collection by a specific property. 
14912      * Returns a new collection that has been filtered.
14913      * @param {String} property A property on your objects
14914      * @param {String/RegExp} value Either string that the property values 
14915      * should start with or a RegExp to test against the property
14916      * @return {MixedCollection} The new filtered collection
14917      */
14918     filter : function(property, value){
14919         if(!value.exec){ // not a regex
14920             value = String(value);
14921             if(value.length == 0){
14922                 return this.clone();
14923             }
14924             value = new RegExp("^" + Roo.escapeRe(value), "i");
14925         }
14926         return this.filterBy(function(o){
14927             return o && value.test(o[property]);
14928         });
14929         },
14930     
14931     /**
14932      * Filter by a function. * Returns a new collection that has been filtered.
14933      * The passed function will be called with each 
14934      * object in the collection. If the function returns true, the value is included 
14935      * otherwise it is filtered.
14936      * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
14937      * @param {Object} scope (optional) The scope of the function (defaults to this) 
14938      * @return {MixedCollection} The new filtered collection
14939      */
14940     filterBy : function(fn, scope){
14941         var r = new Roo.util.MixedCollection();
14942         r.getKey = this.getKey;
14943         var k = this.keys, it = this.items;
14944         for(var i = 0, len = it.length; i < len; i++){
14945             if(fn.call(scope||this, it[i], k[i])){
14946                                 r.add(k[i], it[i]);
14947                         }
14948         }
14949         return r;
14950     },
14951     
14952     /**
14953      * Creates a duplicate of this collection
14954      * @return {MixedCollection}
14955      */
14956     clone : function(){
14957         var r = new Roo.util.MixedCollection();
14958         var k = this.keys, it = this.items;
14959         for(var i = 0, len = it.length; i < len; i++){
14960             r.add(k[i], it[i]);
14961         }
14962         r.getKey = this.getKey;
14963         return r;
14964     }
14965 });
14966 /**
14967  * Returns the item associated with the passed key or index.
14968  * @method
14969  * @param {String/Number} key The key or index of the item.
14970  * @return {Object} The item associated with the passed key.
14971  */
14972 Roo.util.MixedCollection.prototype.get = Roo.util.MixedCollection.prototype.item;/*
14973  * Based on:
14974  * Ext JS Library 1.1.1
14975  * Copyright(c) 2006-2007, Ext JS, LLC.
14976  *
14977  * Originally Released Under LGPL - original licence link has changed is not relivant.
14978  *
14979  * Fork - LGPL
14980  * <script type="text/javascript">
14981  */
14982 /**
14983  * @class Roo.util.JSON
14984  * Modified version of Douglas Crockford"s json.js that doesn"t
14985  * mess with the Object prototype 
14986  * http://www.json.org/js.html
14987  * @static
14988  */
14989 Roo.util.JSON = new (function(){
14990     var useHasOwn = {}.hasOwnProperty ? true : false;
14991     
14992     // crashes Safari in some instances
14993     //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
14994     
14995     var pad = function(n) {
14996         return n < 10 ? "0" + n : n;
14997     };
14998     
14999     var m = {
15000         "\b": '\\b',
15001         "\t": '\\t',
15002         "\n": '\\n',
15003         "\f": '\\f',
15004         "\r": '\\r',
15005         '"' : '\\"',
15006         "\\": '\\\\'
15007     };
15008
15009     var encodeString = function(s){
15010         if (/["\\\x00-\x1f]/.test(s)) {
15011             return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
15012                 var c = m[b];
15013                 if(c){
15014                     return c;
15015                 }
15016                 c = b.charCodeAt();
15017                 return "\\u00" +
15018                     Math.floor(c / 16).toString(16) +
15019                     (c % 16).toString(16);
15020             }) + '"';
15021         }
15022         return '"' + s + '"';
15023     };
15024     
15025     var encodeArray = function(o){
15026         var a = ["["], b, i, l = o.length, v;
15027             for (i = 0; i < l; i += 1) {
15028                 v = o[i];
15029                 switch (typeof v) {
15030                     case "undefined":
15031                     case "function":
15032                     case "unknown":
15033                         break;
15034                     default:
15035                         if (b) {
15036                             a.push(',');
15037                         }
15038                         a.push(v === null ? "null" : Roo.util.JSON.encode(v));
15039                         b = true;
15040                 }
15041             }
15042             a.push("]");
15043             return a.join("");
15044     };
15045     
15046     var encodeDate = function(o){
15047         return '"' + o.getFullYear() + "-" +
15048                 pad(o.getMonth() + 1) + "-" +
15049                 pad(o.getDate()) + "T" +
15050                 pad(o.getHours()) + ":" +
15051                 pad(o.getMinutes()) + ":" +
15052                 pad(o.getSeconds()) + '"';
15053     };
15054     
15055     /**
15056      * Encodes an Object, Array or other value
15057      * @param {Mixed} o The variable to encode
15058      * @return {String} The JSON string
15059      */
15060     this.encode = function(o)
15061     {
15062         // should this be extended to fully wrap stringify..
15063         
15064         if(typeof o == "undefined" || o === null){
15065             return "null";
15066         }else if(o instanceof Array){
15067             return encodeArray(o);
15068         }else if(o instanceof Date){
15069             return encodeDate(o);
15070         }else if(typeof o == "string"){
15071             return encodeString(o);
15072         }else if(typeof o == "number"){
15073             return isFinite(o) ? String(o) : "null";
15074         }else if(typeof o == "boolean"){
15075             return String(o);
15076         }else {
15077             var a = ["{"], b, i, v;
15078             for (i in o) {
15079                 if(!useHasOwn || o.hasOwnProperty(i)) {
15080                     v = o[i];
15081                     switch (typeof v) {
15082                     case "undefined":
15083                     case "function":
15084                     case "unknown":
15085                         break;
15086                     default:
15087                         if(b){
15088                             a.push(',');
15089                         }
15090                         a.push(this.encode(i), ":",
15091                                 v === null ? "null" : this.encode(v));
15092                         b = true;
15093                     }
15094                 }
15095             }
15096             a.push("}");
15097             return a.join("");
15098         }
15099     };
15100     
15101     /**
15102      * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
15103      * @param {String} json The JSON string
15104      * @return {Object} The resulting object
15105      */
15106     this.decode = function(json){
15107         
15108         return  /** eval:var:json */ eval("(" + json + ')');
15109     };
15110 })();
15111 /** 
15112  * Shorthand for {@link Roo.util.JSON#encode}
15113  * @member Roo encode 
15114  * @method */
15115 Roo.encode = typeof(JSON) != 'undefined' && JSON.stringify ? JSON.stringify : Roo.util.JSON.encode;
15116 /** 
15117  * Shorthand for {@link Roo.util.JSON#decode}
15118  * @member Roo decode 
15119  * @method */
15120 Roo.decode = typeof(JSON) != 'undefined' && JSON.parse ? JSON.parse : Roo.util.JSON.decode;
15121 /*
15122  * Based on:
15123  * Ext JS Library 1.1.1
15124  * Copyright(c) 2006-2007, Ext JS, LLC.
15125  *
15126  * Originally Released Under LGPL - original licence link has changed is not relivant.
15127  *
15128  * Fork - LGPL
15129  * <script type="text/javascript">
15130  */
15131  
15132 /**
15133  * @class Roo.util.Format
15134  * Reusable data formatting functions
15135  * @static
15136  */
15137 Roo.util.Format = function(){
15138     var trimRe = /^\s+|\s+$/g;
15139     return {
15140         /**
15141          * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
15142          * @param {String} value The string to truncate
15143          * @param {Number} length The maximum length to allow before truncating
15144          * @return {String} The converted text
15145          */
15146         ellipsis : function(value, len){
15147             if(value && value.length > len){
15148                 return value.substr(0, len-3)+"...";
15149             }
15150             return value;
15151         },
15152
15153         /**
15154          * Checks a reference and converts it to empty string if it is undefined
15155          * @param {Mixed} value Reference to check
15156          * @return {Mixed} Empty string if converted, otherwise the original value
15157          */
15158         undef : function(value){
15159             return typeof value != "undefined" ? value : "";
15160         },
15161
15162         /**
15163          * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
15164          * @param {String} value The string to encode
15165          * @return {String} The encoded text
15166          */
15167         htmlEncode : function(value){
15168             return !value ? value : String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
15169         },
15170
15171         /**
15172          * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
15173          * @param {String} value The string to decode
15174          * @return {String} The decoded text
15175          */
15176         htmlDecode : function(value){
15177             return !value ? value : String(value).replace(/&amp;/g, "&").replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"');
15178         },
15179
15180         /**
15181          * Trims any whitespace from either side of a string
15182          * @param {String} value The text to trim
15183          * @return {String} The trimmed text
15184          */
15185         trim : function(value){
15186             return String(value).replace(trimRe, "");
15187         },
15188
15189         /**
15190          * Returns a substring from within an original string
15191          * @param {String} value The original text
15192          * @param {Number} start The start index of the substring
15193          * @param {Number} length The length of the substring
15194          * @return {String} The substring
15195          */
15196         substr : function(value, start, length){
15197             return String(value).substr(start, length);
15198         },
15199
15200         /**
15201          * Converts a string to all lower case letters
15202          * @param {String} value The text to convert
15203          * @return {String} The converted text
15204          */
15205         lowercase : function(value){
15206             return String(value).toLowerCase();
15207         },
15208
15209         /**
15210          * Converts a string to all upper case letters
15211          * @param {String} value The text to convert
15212          * @return {String} The converted text
15213          */
15214         uppercase : function(value){
15215             return String(value).toUpperCase();
15216         },
15217
15218         /**
15219          * Converts the first character only of a string to upper case
15220          * @param {String} value The text to convert
15221          * @return {String} The converted text
15222          */
15223         capitalize : function(value){
15224             return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
15225         },
15226
15227         // private
15228         call : function(value, fn){
15229             if(arguments.length > 2){
15230                 var args = Array.prototype.slice.call(arguments, 2);
15231                 args.unshift(value);
15232                  
15233                 return /** eval:var:value */  eval(fn).apply(window, args);
15234             }else{
15235                 /** eval:var:value */
15236                 return /** eval:var:value */ eval(fn).call(window, value);
15237             }
15238         },
15239
15240        
15241         /**
15242          * safer version of Math.toFixed..??/
15243          * @param {Number/String} value The numeric value to format
15244          * @param {Number/String} value Decimal places 
15245          * @return {String} The formatted currency string
15246          */
15247         toFixed : function(v, n)
15248         {
15249             // why not use to fixed - precision is buggered???
15250             if (!n) {
15251                 return Math.round(v-0);
15252             }
15253             var fact = Math.pow(10,n+1);
15254             v = (Math.round((v-0)*fact))/fact;
15255             var z = (''+fact).substring(2);
15256             if (v == Math.floor(v)) {
15257                 return Math.floor(v) + '.' + z;
15258             }
15259             
15260             // now just padd decimals..
15261             var ps = String(v).split('.');
15262             var fd = (ps[1] + z);
15263             var r = fd.substring(0,n); 
15264             var rm = fd.substring(n); 
15265             if (rm < 5) {
15266                 return ps[0] + '.' + r;
15267             }
15268             r*=1; // turn it into a number;
15269             r++;
15270             if (String(r).length != n) {
15271                 ps[0]*=1;
15272                 ps[0]++;
15273                 r = String(r).substring(1); // chop the end off.
15274             }
15275             
15276             return ps[0] + '.' + r;
15277              
15278         },
15279         
15280         /**
15281          * Format a number as US currency
15282          * @param {Number/String} value The numeric value to format
15283          * @return {String} The formatted currency string
15284          */
15285         usMoney : function(v){
15286             return '$' + Roo.util.Format.number(v);
15287         },
15288         
15289         /**
15290          * Format a number
15291          * eventually this should probably emulate php's number_format
15292          * @param {Number/String} value The numeric value to format
15293          * @param {Number} decimals number of decimal places
15294          * @param {String} delimiter for thousands (default comma)
15295          * @return {String} The formatted currency string
15296          */
15297         number : function(v, decimals, thousandsDelimiter)
15298         {
15299             // multiply and round.
15300             decimals = typeof(decimals) == 'undefined' ? 2 : decimals;
15301             thousandsDelimiter = typeof(thousandsDelimiter) == 'undefined' ? ',' : thousandsDelimiter;
15302             
15303             var mul = Math.pow(10, decimals);
15304             var zero = String(mul).substring(1);
15305             v = (Math.round((v-0)*mul))/mul;
15306             
15307             // if it's '0' number.. then
15308             
15309             //v = (v == Math.floor(v)) ? v + "." + zero : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
15310             v = String(v);
15311             var ps = v.split('.');
15312             var whole = ps[0];
15313             
15314             var r = /(\d+)(\d{3})/;
15315             // add comma's
15316             
15317             if(thousandsDelimiter.length != 0) {
15318                 whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsDelimiter );
15319             } 
15320             
15321             var sub = ps[1] ?
15322                     // has decimals..
15323                     (decimals ?  ('.'+ ps[1] + zero.substring(ps[1].length)) : '') :
15324                     // does not have decimals
15325                     (decimals ? ('.' + zero) : '');
15326             
15327             
15328             return whole + sub ;
15329         },
15330         
15331         /**
15332          * Parse a value into a formatted date using the specified format pattern.
15333          * @param {Mixed} value The value to format
15334          * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
15335          * @return {String} The formatted date string
15336          */
15337         date : function(v, format){
15338             if(!v){
15339                 return "";
15340             }
15341             if(!(v instanceof Date)){
15342                 v = new Date(Date.parse(v));
15343             }
15344             return v.dateFormat(format || Roo.util.Format.defaults.date);
15345         },
15346
15347         /**
15348          * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
15349          * @param {String} format Any valid date format string
15350          * @return {Function} The date formatting function
15351          */
15352         dateRenderer : function(format){
15353             return function(v){
15354                 return Roo.util.Format.date(v, format);  
15355             };
15356         },
15357
15358         // private
15359         stripTagsRE : /<\/?[^>]+>/gi,
15360         
15361         /**
15362          * Strips all HTML tags
15363          * @param {Mixed} value The text from which to strip tags
15364          * @return {String} The stripped text
15365          */
15366         stripTags : function(v){
15367             return !v ? v : String(v).replace(this.stripTagsRE, "");
15368         },
15369         
15370         /**
15371          * Size in Mb,Gb etc.
15372          * @param {Number} value The number to be formated
15373          * @param {number} decimals how many decimal places
15374          * @return {String} the formated string
15375          */
15376         size : function(value, decimals)
15377         {
15378             var sizes = ['b', 'k', 'M', 'G', 'T'];
15379             if (value == 0) {
15380                 return 0;
15381             }
15382             var i = parseInt(Math.floor(Math.log(value) / Math.log(1024)));
15383             return Roo.util.Format.number(value/ Math.pow(1024, i) ,decimals)   + sizes[i];
15384         }
15385         
15386         
15387         
15388     };
15389 }();
15390 Roo.util.Format.defaults = {
15391     date : 'd/M/Y'
15392 };/*
15393  * Based on:
15394  * Ext JS Library 1.1.1
15395  * Copyright(c) 2006-2007, Ext JS, LLC.
15396  *
15397  * Originally Released Under LGPL - original licence link has changed is not relivant.
15398  *
15399  * Fork - LGPL
15400  * <script type="text/javascript">
15401  */
15402
15403
15404  
15405
15406 /**
15407  * @class Roo.MasterTemplate
15408  * @extends Roo.Template
15409  * Provides a template that can have child templates. The syntax is:
15410 <pre><code>
15411 var t = new Roo.MasterTemplate(
15412         '&lt;select name="{name}"&gt;',
15413                 '&lt;tpl name="options"&gt;&lt;option value="{value:trim}"&gt;{text:ellipsis(10)}&lt;/option&gt;&lt;/tpl&gt;',
15414         '&lt;/select&gt;'
15415 );
15416 t.add('options', {value: 'foo', text: 'bar'});
15417 // or you can add multiple child elements in one shot
15418 t.addAll('options', [
15419     {value: 'foo', text: 'bar'},
15420     {value: 'foo2', text: 'bar2'},
15421     {value: 'foo3', text: 'bar3'}
15422 ]);
15423 // then append, applying the master template values
15424 t.append('my-form', {name: 'my-select'});
15425 </code></pre>
15426 * A name attribute for the child template is not required if you have only one child
15427 * template or you want to refer to them by index.
15428  */
15429 Roo.MasterTemplate = function(){
15430     Roo.MasterTemplate.superclass.constructor.apply(this, arguments);
15431     this.originalHtml = this.html;
15432     var st = {};
15433     var m, re = this.subTemplateRe;
15434     re.lastIndex = 0;
15435     var subIndex = 0;
15436     while(m = re.exec(this.html)){
15437         var name = m[1], content = m[2];
15438         st[subIndex] = {
15439             name: name,
15440             index: subIndex,
15441             buffer: [],
15442             tpl : new Roo.Template(content)
15443         };
15444         if(name){
15445             st[name] = st[subIndex];
15446         }
15447         st[subIndex].tpl.compile();
15448         st[subIndex].tpl.call = this.call.createDelegate(this);
15449         subIndex++;
15450     }
15451     this.subCount = subIndex;
15452     this.subs = st;
15453 };
15454 Roo.extend(Roo.MasterTemplate, Roo.Template, {
15455     /**
15456     * The regular expression used to match sub templates
15457     * @type RegExp
15458     * @property
15459     */
15460     subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi,
15461
15462     /**
15463      * Applies the passed values to a child template.
15464      * @param {String/Number} name (optional) The name or index of the child template
15465      * @param {Array/Object} values The values to be applied to the template
15466      * @return {MasterTemplate} this
15467      */
15468      add : function(name, values){
15469         if(arguments.length == 1){
15470             values = arguments[0];
15471             name = 0;
15472         }
15473         var s = this.subs[name];
15474         s.buffer[s.buffer.length] = s.tpl.apply(values);
15475         return this;
15476     },
15477
15478     /**
15479      * Applies all the passed values to a child template.
15480      * @param {String/Number} name (optional) The name or index of the child template
15481      * @param {Array} values The values to be applied to the template, this should be an array of objects.
15482      * @param {Boolean} reset (optional) True to reset the template first
15483      * @return {MasterTemplate} this
15484      */
15485     fill : function(name, values, reset){
15486         var a = arguments;
15487         if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){
15488             values = a[0];
15489             name = 0;
15490             reset = a[1];
15491         }
15492         if(reset){
15493             this.reset();
15494         }
15495         for(var i = 0, len = values.length; i < len; i++){
15496             this.add(name, values[i]);
15497         }
15498         return this;
15499     },
15500
15501     /**
15502      * Resets the template for reuse
15503      * @return {MasterTemplate} this
15504      */
15505      reset : function(){
15506         var s = this.subs;
15507         for(var i = 0; i < this.subCount; i++){
15508             s[i].buffer = [];
15509         }
15510         return this;
15511     },
15512
15513     applyTemplate : function(values){
15514         var s = this.subs;
15515         var replaceIndex = -1;
15516         this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){
15517             return s[++replaceIndex].buffer.join("");
15518         });
15519         return Roo.MasterTemplate.superclass.applyTemplate.call(this, values);
15520     },
15521
15522     apply : function(){
15523         return this.applyTemplate.apply(this, arguments);
15524     },
15525
15526     compile : function(){return this;}
15527 });
15528
15529 /**
15530  * Alias for fill().
15531  * @method
15532  */
15533 Roo.MasterTemplate.prototype.addAll = Roo.MasterTemplate.prototype.fill;
15534  /**
15535  * Creates a template from the passed element's value (display:none textarea, preferred) or innerHTML. e.g.
15536  * var tpl = Roo.MasterTemplate.from('element-id');
15537  * @param {String/HTMLElement} el
15538  * @param {Object} config
15539  * @static
15540  */
15541 Roo.MasterTemplate.from = function(el, config){
15542     el = Roo.getDom(el);
15543     return new Roo.MasterTemplate(el.value || el.innerHTML, config || '');
15544 };/*
15545  * Based on:
15546  * Ext JS Library 1.1.1
15547  * Copyright(c) 2006-2007, Ext JS, LLC.
15548  *
15549  * Originally Released Under LGPL - original licence link has changed is not relivant.
15550  *
15551  * Fork - LGPL
15552  * <script type="text/javascript">
15553  */
15554
15555  
15556 /**
15557  * @class Roo.util.CSS
15558  * Utility class for manipulating CSS rules
15559  * @static
15560
15561  */
15562 Roo.util.CSS = function(){
15563         var rules = null;
15564         var doc = document;
15565
15566     var camelRe = /(-[a-z])/gi;
15567     var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
15568
15569    return {
15570    /**
15571     * Very simple dynamic creation of stylesheets from a text blob of rules.  The text will wrapped in a style
15572     * tag and appended to the HEAD of the document.
15573     * @param {String|Object} cssText The text containing the css rules
15574     * @param {String} id An id to add to the stylesheet for later removal
15575     * @return {StyleSheet}
15576     */
15577     createStyleSheet : function(cssText, id){
15578         var ss;
15579         var head = doc.getElementsByTagName("head")[0];
15580         var nrules = doc.createElement("style");
15581         nrules.setAttribute("type", "text/css");
15582         if(id){
15583             nrules.setAttribute("id", id);
15584         }
15585         if (typeof(cssText) != 'string') {
15586             // support object maps..
15587             // not sure if this a good idea.. 
15588             // perhaps it should be merged with the general css handling
15589             // and handle js style props.
15590             var cssTextNew = [];
15591             for(var n in cssText) {
15592                 var citems = [];
15593                 for(var k in cssText[n]) {
15594                     citems.push( k + ' : ' +cssText[n][k] + ';' );
15595                 }
15596                 cssTextNew.push( n + ' { ' + citems.join(' ') + '} ');
15597                 
15598             }
15599             cssText = cssTextNew.join("\n");
15600             
15601         }
15602        
15603        
15604        if(Roo.isIE){
15605            head.appendChild(nrules);
15606            ss = nrules.styleSheet;
15607            ss.cssText = cssText;
15608        }else{
15609            try{
15610                 nrules.appendChild(doc.createTextNode(cssText));
15611            }catch(e){
15612                nrules.cssText = cssText; 
15613            }
15614            head.appendChild(nrules);
15615            ss = nrules.styleSheet ? nrules.styleSheet : (nrules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
15616        }
15617        this.cacheStyleSheet(ss);
15618        return ss;
15619    },
15620
15621    /**
15622     * Removes a style or link tag by id
15623     * @param {String} id The id of the tag
15624     */
15625    removeStyleSheet : function(id){
15626        var existing = doc.getElementById(id);
15627        if(existing){
15628            existing.parentNode.removeChild(existing);
15629        }
15630    },
15631
15632    /**
15633     * Dynamically swaps an existing stylesheet reference for a new one
15634     * @param {String} id The id of an existing link tag to remove
15635     * @param {String} url The href of the new stylesheet to include
15636     */
15637    swapStyleSheet : function(id, url){
15638        this.removeStyleSheet(id);
15639        var ss = doc.createElement("link");
15640        ss.setAttribute("rel", "stylesheet");
15641        ss.setAttribute("type", "text/css");
15642        ss.setAttribute("id", id);
15643        ss.setAttribute("href", url);
15644        doc.getElementsByTagName("head")[0].appendChild(ss);
15645    },
15646    
15647    /**
15648     * Refresh the rule cache if you have dynamically added stylesheets
15649     * @return {Object} An object (hash) of rules indexed by selector
15650     */
15651    refreshCache : function(){
15652        return this.getRules(true);
15653    },
15654
15655    // private
15656    cacheStyleSheet : function(stylesheet){
15657        if(!rules){
15658            rules = {};
15659        }
15660        try{// try catch for cross domain access issue
15661            var ssRules = stylesheet.cssRules || stylesheet.rules;
15662            for(var j = ssRules.length-1; j >= 0; --j){
15663                rules[ssRules[j].selectorText] = ssRules[j];
15664            }
15665        }catch(e){}
15666    },
15667    
15668    /**
15669     * Gets all css rules for the document
15670     * @param {Boolean} refreshCache true to refresh the internal cache
15671     * @return {Object} An object (hash) of rules indexed by selector
15672     */
15673    getRules : function(refreshCache){
15674                 if(rules == null || refreshCache){
15675                         rules = {};
15676                         var ds = doc.styleSheets;
15677                         for(var i =0, len = ds.length; i < len; i++){
15678                             try{
15679                         this.cacheStyleSheet(ds[i]);
15680                     }catch(e){} 
15681                 }
15682                 }
15683                 return rules;
15684         },
15685         
15686         /**
15687     * Gets an an individual CSS rule by selector(s)
15688     * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
15689     * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
15690     * @return {CSSRule} The CSS rule or null if one is not found
15691     */
15692    getRule : function(selector, refreshCache){
15693                 var rs = this.getRules(refreshCache);
15694                 if(!(selector instanceof Array)){
15695                     return rs[selector];
15696                 }
15697                 for(var i = 0; i < selector.length; i++){
15698                         if(rs[selector[i]]){
15699                                 return rs[selector[i]];
15700                         }
15701                 }
15702                 return null;
15703         },
15704         
15705         
15706         /**
15707     * Updates a rule property
15708     * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
15709     * @param {String} property The css property
15710     * @param {String} value The new value for the property
15711     * @return {Boolean} true If a rule was found and updated
15712     */
15713    updateRule : function(selector, property, value){
15714                 if(!(selector instanceof Array)){
15715                         var rule = this.getRule(selector);
15716                         if(rule){
15717                                 rule.style[property.replace(camelRe, camelFn)] = value;
15718                                 return true;
15719                         }
15720                 }else{
15721                         for(var i = 0; i < selector.length; i++){
15722                                 if(this.updateRule(selector[i], property, value)){
15723                                         return true;
15724                                 }
15725                         }
15726                 }
15727                 return false;
15728         }
15729    };   
15730 }();/*
15731  * Based on:
15732  * Ext JS Library 1.1.1
15733  * Copyright(c) 2006-2007, Ext JS, LLC.
15734  *
15735  * Originally Released Under LGPL - original licence link has changed is not relivant.
15736  *
15737  * Fork - LGPL
15738  * <script type="text/javascript">
15739  */
15740
15741  
15742
15743 /**
15744  * @class Roo.util.ClickRepeater
15745  * @extends Roo.util.Observable
15746  * 
15747  * A wrapper class which can be applied to any element. Fires a "click" event while the
15748  * mouse is pressed. The interval between firings may be specified in the config but
15749  * defaults to 10 milliseconds.
15750  * 
15751  * Optionally, a CSS class may be applied to the element during the time it is pressed.
15752  * 
15753  * @cfg {String/HTMLElement/Element} el The element to act as a button.
15754  * @cfg {Number} delay The initial delay before the repeating event begins firing.
15755  * Similar to an autorepeat key delay.
15756  * @cfg {Number} interval The interval between firings of the "click" event. Default 10 ms.
15757  * @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
15758  * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
15759  *           "interval" and "delay" are ignored. "immediate" is honored.
15760  * @cfg {Boolean} preventDefault True to prevent the default click event
15761  * @cfg {Boolean} stopDefault True to stop the default click event
15762  * 
15763  * @history
15764  *     2007-02-02 jvs Original code contributed by Nige "Animal" White
15765  *     2007-02-02 jvs Renamed to ClickRepeater
15766  *   2007-02-03 jvs Modifications for FF Mac and Safari 
15767  *
15768  *  @constructor
15769  * @param {String/HTMLElement/Element} el The element to listen on
15770  * @param {Object} config
15771  **/
15772 Roo.util.ClickRepeater = function(el, config)
15773 {
15774     this.el = Roo.get(el);
15775     this.el.unselectable();
15776
15777     Roo.apply(this, config);
15778
15779     this.addEvents({
15780     /**
15781      * @event mousedown
15782      * Fires when the mouse button is depressed.
15783      * @param {Roo.util.ClickRepeater} this
15784      */
15785         "mousedown" : true,
15786     /**
15787      * @event click
15788      * Fires on a specified interval during the time the element is pressed.
15789      * @param {Roo.util.ClickRepeater} this
15790      */
15791         "click" : true,
15792     /**
15793      * @event mouseup
15794      * Fires when the mouse key is released.
15795      * @param {Roo.util.ClickRepeater} this
15796      */
15797         "mouseup" : true
15798     });
15799
15800     this.el.on("mousedown", this.handleMouseDown, this);
15801     if(this.preventDefault || this.stopDefault){
15802         this.el.on("click", function(e){
15803             if(this.preventDefault){
15804                 e.preventDefault();
15805             }
15806             if(this.stopDefault){
15807                 e.stopEvent();
15808             }
15809         }, this);
15810     }
15811
15812     // allow inline handler
15813     if(this.handler){
15814         this.on("click", this.handler,  this.scope || this);
15815     }
15816
15817     Roo.util.ClickRepeater.superclass.constructor.call(this);
15818 };
15819
15820 Roo.extend(Roo.util.ClickRepeater, Roo.util.Observable, {
15821     interval : 20,
15822     delay: 250,
15823     preventDefault : true,
15824     stopDefault : false,
15825     timer : 0,
15826
15827     // private
15828     handleMouseDown : function(){
15829         clearTimeout(this.timer);
15830         this.el.blur();
15831         if(this.pressClass){
15832             this.el.addClass(this.pressClass);
15833         }
15834         this.mousedownTime = new Date();
15835
15836         Roo.get(document).on("mouseup", this.handleMouseUp, this);
15837         this.el.on("mouseout", this.handleMouseOut, this);
15838
15839         this.fireEvent("mousedown", this);
15840         this.fireEvent("click", this);
15841         
15842         this.timer = this.click.defer(this.delay || this.interval, this);
15843     },
15844
15845     // private
15846     click : function(){
15847         this.fireEvent("click", this);
15848         this.timer = this.click.defer(this.getInterval(), this);
15849     },
15850
15851     // private
15852     getInterval: function(){
15853         if(!this.accelerate){
15854             return this.interval;
15855         }
15856         var pressTime = this.mousedownTime.getElapsed();
15857         if(pressTime < 500){
15858             return 400;
15859         }else if(pressTime < 1700){
15860             return 320;
15861         }else if(pressTime < 2600){
15862             return 250;
15863         }else if(pressTime < 3500){
15864             return 180;
15865         }else if(pressTime < 4400){
15866             return 140;
15867         }else if(pressTime < 5300){
15868             return 80;
15869         }else if(pressTime < 6200){
15870             return 50;
15871         }else{
15872             return 10;
15873         }
15874     },
15875
15876     // private
15877     handleMouseOut : function(){
15878         clearTimeout(this.timer);
15879         if(this.pressClass){
15880             this.el.removeClass(this.pressClass);
15881         }
15882         this.el.on("mouseover", this.handleMouseReturn, this);
15883     },
15884
15885     // private
15886     handleMouseReturn : function(){
15887         this.el.un("mouseover", this.handleMouseReturn);
15888         if(this.pressClass){
15889             this.el.addClass(this.pressClass);
15890         }
15891         this.click();
15892     },
15893
15894     // private
15895     handleMouseUp : function(){
15896         clearTimeout(this.timer);
15897         this.el.un("mouseover", this.handleMouseReturn);
15898         this.el.un("mouseout", this.handleMouseOut);
15899         Roo.get(document).un("mouseup", this.handleMouseUp);
15900         this.el.removeClass(this.pressClass);
15901         this.fireEvent("mouseup", this);
15902     }
15903 });/**
15904  * @class Roo.util.Clipboard
15905  * @static
15906  * 
15907  * Clipboard UTILS
15908  * 
15909  **/
15910 Roo.util.Clipboard = {
15911     /**
15912      * Writes a string to the clipboard - using the Clipboard API if https, otherwise using text area.
15913      * @param {String} text to copy to clipboard
15914      */
15915     write : function(text) {
15916         // navigator clipboard api needs a secure context (https)
15917         if (navigator.clipboard && window.isSecureContext) {
15918             // navigator clipboard api method'
15919             navigator.clipboard.writeText(text);
15920             return ;
15921         } 
15922         // text area method
15923         var ta = document.createElement("textarea");
15924         ta.value = text;
15925         // make the textarea out of viewport
15926         ta.style.position = "fixed";
15927         ta.style.left = "-999999px";
15928         ta.style.top = "-999999px";
15929         document.body.appendChild(ta);
15930         ta.focus();
15931         ta.select();
15932         document.execCommand('copy');
15933         (function() {
15934             ta.remove();
15935         }).defer(100);
15936         
15937     }
15938         
15939 }
15940     /*
15941  * Based on:
15942  * Ext JS Library 1.1.1
15943  * Copyright(c) 2006-2007, Ext JS, LLC.
15944  *
15945  * Originally Released Under LGPL - original licence link has changed is not relivant.
15946  *
15947  * Fork - LGPL
15948  * <script type="text/javascript">
15949  */
15950
15951  
15952 /**
15953  * @class Roo.KeyNav
15954  * <p>Provides a convenient wrapper for normalized keyboard navigation.  KeyNav allows you to bind
15955  * navigation keys to function calls that will get called when the keys are pressed, providing an easy
15956  * way to implement custom navigation schemes for any UI component.</p>
15957  * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
15958  * pageUp, pageDown, del, home, end.  Usage:</p>
15959  <pre><code>
15960 var nav = new Roo.KeyNav("my-element", {
15961     "left" : function(e){
15962         this.moveLeft(e.ctrlKey);
15963     },
15964     "right" : function(e){
15965         this.moveRight(e.ctrlKey);
15966     },
15967     "enter" : function(e){
15968         this.save();
15969     },
15970     scope : this
15971 });
15972 </code></pre>
15973  * @constructor
15974  * @param {String/HTMLElement/Roo.Element} el The element to bind to
15975  * @param {Object} config The config
15976  */
15977 Roo.KeyNav = function(el, config){
15978     this.el = Roo.get(el);
15979     Roo.apply(this, config);
15980     if(!this.disabled){
15981         this.disabled = true;
15982         this.enable();
15983     }
15984 };
15985
15986 Roo.KeyNav.prototype = {
15987     /**
15988      * @cfg {Boolean} disabled
15989      * True to disable this KeyNav instance (defaults to false)
15990      */
15991     disabled : false,
15992     /**
15993      * @cfg {String} defaultEventAction
15994      * The method to call on the {@link Roo.EventObject} after this KeyNav intercepts a key.  Valid values are
15995      * {@link Roo.EventObject#stopEvent}, {@link Roo.EventObject#preventDefault} and
15996      * {@link Roo.EventObject#stopPropagation} (defaults to 'stopEvent')
15997      */
15998     defaultEventAction: "stopEvent",
15999     /**
16000      * @cfg {Boolean} forceKeyDown
16001      * Handle the keydown event instead of keypress (defaults to false).  KeyNav automatically does this for IE since
16002      * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
16003      * handle keydown instead of keypress.
16004      */
16005     forceKeyDown : false,
16006
16007     // private
16008     prepareEvent : function(e){
16009         var k = e.getKey();
16010         var h = this.keyToHandler[k];
16011         //if(h && this[h]){
16012         //    e.stopPropagation();
16013         //}
16014         if(Roo.isSafari && h && k >= 37 && k <= 40){
16015             e.stopEvent();
16016         }
16017     },
16018
16019     // private
16020     relay : function(e){
16021         var k = e.getKey();
16022         var h = this.keyToHandler[k];
16023         if(h && this[h]){
16024             if(this.doRelay(e, this[h], h) !== true){
16025                 e[this.defaultEventAction]();
16026             }
16027         }
16028     },
16029
16030     // private
16031     doRelay : function(e, h, hname){
16032         return h.call(this.scope || this, e);
16033     },
16034
16035     // possible handlers
16036     enter : false,
16037     left : false,
16038     right : false,
16039     up : false,
16040     down : false,
16041     tab : false,
16042     esc : false,
16043     pageUp : false,
16044     pageDown : false,
16045     del : false,
16046     home : false,
16047     end : false,
16048
16049     // quick lookup hash
16050     keyToHandler : {
16051         37 : "left",
16052         39 : "right",
16053         38 : "up",
16054         40 : "down",
16055         33 : "pageUp",
16056         34 : "pageDown",
16057         46 : "del",
16058         36 : "home",
16059         35 : "end",
16060         13 : "enter",
16061         27 : "esc",
16062         9  : "tab"
16063     },
16064
16065         /**
16066          * Enable this KeyNav
16067          */
16068         enable: function(){
16069                 if(this.disabled){
16070             // ie won't do special keys on keypress, no one else will repeat keys with keydown
16071             // the EventObject will normalize Safari automatically
16072             if(this.forceKeyDown || Roo.isIE || Roo.isAir){
16073                 this.el.on("keydown", this.relay,  this);
16074             }else{
16075                 this.el.on("keydown", this.prepareEvent,  this);
16076                 this.el.on("keypress", this.relay,  this);
16077             }
16078                     this.disabled = false;
16079                 }
16080         },
16081
16082         /**
16083          * Disable this KeyNav
16084          */
16085         disable: function(){
16086                 if(!this.disabled){
16087                     if(this.forceKeyDown || Roo.isIE || Roo.isAir){
16088                 this.el.un("keydown", this.relay);
16089             }else{
16090                 this.el.un("keydown", this.prepareEvent);
16091                 this.el.un("keypress", this.relay);
16092             }
16093                     this.disabled = true;
16094                 }
16095         }
16096 };/*
16097  * Based on:
16098  * Ext JS Library 1.1.1
16099  * Copyright(c) 2006-2007, Ext JS, LLC.
16100  *
16101  * Originally Released Under LGPL - original licence link has changed is not relivant.
16102  *
16103  * Fork - LGPL
16104  * <script type="text/javascript">
16105  */
16106
16107  
16108 /**
16109  * @class Roo.KeyMap
16110  * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
16111  * The constructor accepts the same config object as defined by {@link #addBinding}.
16112  * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
16113  * combination it will call the function with this signature (if the match is a multi-key
16114  * combination the callback will still be called only once): (String key, Roo.EventObject e)
16115  * A KeyMap can also handle a string representation of keys.<br />
16116  * Usage:
16117  <pre><code>
16118 // map one key by key code
16119 var map = new Roo.KeyMap("my-element", {
16120     key: 13, // or Roo.EventObject.ENTER
16121     fn: myHandler,
16122     scope: myObject
16123 });
16124
16125 // map multiple keys to one action by string
16126 var map = new Roo.KeyMap("my-element", {
16127     key: "a\r\n\t",
16128     fn: myHandler,
16129     scope: myObject
16130 });
16131
16132 // map multiple keys to multiple actions by strings and array of codes
16133 var map = new Roo.KeyMap("my-element", [
16134     {
16135         key: [10,13],
16136         fn: function(){ alert("Return was pressed"); }
16137     }, {
16138         key: "abc",
16139         fn: function(){ alert('a, b or c was pressed'); }
16140     }, {
16141         key: "\t",
16142         ctrl:true,
16143         shift:true,
16144         fn: function(){ alert('Control + shift + tab was pressed.'); }
16145     }
16146 ]);
16147 </code></pre>
16148  * <b>Note: A KeyMap starts enabled</b>
16149  * @constructor
16150  * @param {String/HTMLElement/Roo.Element} el The element to bind to
16151  * @param {Object} config The config (see {@link #addBinding})
16152  * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
16153  */
16154 Roo.KeyMap = function(el, config, eventName){
16155     this.el  = Roo.get(el);
16156     this.eventName = eventName || "keydown";
16157     this.bindings = [];
16158     if(config){
16159         this.addBinding(config);
16160     }
16161     this.enable();
16162 };
16163
16164 Roo.KeyMap.prototype = {
16165     /**
16166      * True to stop the event from bubbling and prevent the default browser action if the
16167      * key was handled by the KeyMap (defaults to false)
16168      * @type Boolean
16169      */
16170     stopEvent : false,
16171
16172     /**
16173      * Add a new binding to this KeyMap. The following config object properties are supported:
16174      * <pre>
16175 Property    Type             Description
16176 ----------  ---------------  ----------------------------------------------------------------------
16177 key         String/Array     A single keycode or an array of keycodes to handle
16178 shift       Boolean          True to handle key only when shift is pressed (defaults to false)
16179 ctrl        Boolean          True to handle key only when ctrl is pressed (defaults to false)
16180 alt         Boolean          True to handle key only when alt is pressed (defaults to false)
16181 fn          Function         The function to call when KeyMap finds the expected key combination
16182 scope       Object           The scope of the callback function
16183 </pre>
16184      *
16185      * Usage:
16186      * <pre><code>
16187 // Create a KeyMap
16188 var map = new Roo.KeyMap(document, {
16189     key: Roo.EventObject.ENTER,
16190     fn: handleKey,
16191     scope: this
16192 });
16193
16194 //Add a new binding to the existing KeyMap later
16195 map.addBinding({
16196     key: 'abc',
16197     shift: true,
16198     fn: handleKey,
16199     scope: this
16200 });
16201 </code></pre>
16202      * @param {Object/Array} config A single KeyMap config or an array of configs
16203      */
16204         addBinding : function(config){
16205         if(config instanceof Array){
16206             for(var i = 0, len = config.length; i < len; i++){
16207                 this.addBinding(config[i]);
16208             }
16209             return;
16210         }
16211         var keyCode = config.key,
16212             shift = config.shift, 
16213             ctrl = config.ctrl, 
16214             alt = config.alt,
16215             fn = config.fn,
16216             scope = config.scope;
16217         if(typeof keyCode == "string"){
16218             var ks = [];
16219             var keyString = keyCode.toUpperCase();
16220             for(var j = 0, len = keyString.length; j < len; j++){
16221                 ks.push(keyString.charCodeAt(j));
16222             }
16223             keyCode = ks;
16224         }
16225         var keyArray = keyCode instanceof Array;
16226         var handler = function(e){
16227             if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) &&  (!alt || e.altKey)){
16228                 var k = e.getKey();
16229                 if(keyArray){
16230                     for(var i = 0, len = keyCode.length; i < len; i++){
16231                         if(keyCode[i] == k){
16232                           if(this.stopEvent){
16233                               e.stopEvent();
16234                           }
16235                           fn.call(scope || window, k, e);
16236                           return;
16237                         }
16238                     }
16239                 }else{
16240                     if(k == keyCode){
16241                         if(this.stopEvent){
16242                            e.stopEvent();
16243                         }
16244                         fn.call(scope || window, k, e);
16245                     }
16246                 }
16247             }
16248         };
16249         this.bindings.push(handler);  
16250         },
16251
16252     /**
16253      * Shorthand for adding a single key listener
16254      * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
16255      * following options:
16256      * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
16257      * @param {Function} fn The function to call
16258      * @param {Object} scope (optional) The scope of the function
16259      */
16260     on : function(key, fn, scope){
16261         var keyCode, shift, ctrl, alt;
16262         if(typeof key == "object" && !(key instanceof Array)){
16263             keyCode = key.key;
16264             shift = key.shift;
16265             ctrl = key.ctrl;
16266             alt = key.alt;
16267         }else{
16268             keyCode = key;
16269         }
16270         this.addBinding({
16271             key: keyCode,
16272             shift: shift,
16273             ctrl: ctrl,
16274             alt: alt,
16275             fn: fn,
16276             scope: scope
16277         })
16278     },
16279
16280     // private
16281     handleKeyDown : function(e){
16282             if(this.enabled){ //just in case
16283             var b = this.bindings;
16284             for(var i = 0, len = b.length; i < len; i++){
16285                 b[i].call(this, e);
16286             }
16287             }
16288         },
16289         
16290         /**
16291          * Returns true if this KeyMap is enabled
16292          * @return {Boolean} 
16293          */
16294         isEnabled : function(){
16295             return this.enabled;  
16296         },
16297         
16298         /**
16299          * Enables this KeyMap
16300          */
16301         enable: function(){
16302                 if(!this.enabled){
16303                     this.el.on(this.eventName, this.handleKeyDown, this);
16304                     this.enabled = true;
16305                 }
16306         },
16307
16308         /**
16309          * Disable this KeyMap
16310          */
16311         disable: function(){
16312                 if(this.enabled){
16313                     this.el.removeListener(this.eventName, this.handleKeyDown, this);
16314                     this.enabled = false;
16315                 }
16316         }
16317 };/*
16318  * Based on:
16319  * Ext JS Library 1.1.1
16320  * Copyright(c) 2006-2007, Ext JS, LLC.
16321  *
16322  * Originally Released Under LGPL - original licence link has changed is not relivant.
16323  *
16324  * Fork - LGPL
16325  * <script type="text/javascript">
16326  */
16327
16328  
16329 /**
16330  * @class Roo.util.TextMetrics
16331  * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
16332  * wide, in pixels, a given block of text will be.
16333  * @static
16334  */
16335 Roo.util.TextMetrics = function(){
16336     var shared;
16337     return {
16338         /**
16339          * Measures the size of the specified text
16340          * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
16341          * that can affect the size of the rendered text
16342          * @param {String} text The text to measure
16343          * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
16344          * in order to accurately measure the text height
16345          * @return {Object} An object containing the text's size {width: (width), height: (height)}
16346          */
16347         measure : function(el, text, fixedWidth){
16348             if(!shared){
16349                 shared = Roo.util.TextMetrics.Instance(el, fixedWidth);
16350             }
16351             shared.bind(el);
16352             shared.setFixedWidth(fixedWidth || 'auto');
16353             return shared.getSize(text);
16354         },
16355
16356         /**
16357          * Return a unique TextMetrics instance that can be bound directly to an element and reused.  This reduces
16358          * the overhead of multiple calls to initialize the style properties on each measurement.
16359          * @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
16360          * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
16361          * in order to accurately measure the text height
16362          * @return {Roo.util.TextMetrics.Instance} instance The new instance
16363          */
16364         createInstance : function(el, fixedWidth){
16365             return Roo.util.TextMetrics.Instance(el, fixedWidth);
16366         }
16367     };
16368 }();
16369
16370 /**
16371  * @class Roo.util.TextMetrics.Instance
16372  * Instance of  TextMetrics Calcuation
16373  * @constructor
16374  * Create a new TextMetrics Instance
16375  * @param {Object} bindto
16376  * @param {Boolean} fixedWidth
16377  */
16378
16379 Roo.util.TextMetrics.Instance = function(bindTo, fixedWidth)
16380 {
16381     var ml = new Roo.Element(document.createElement('div'));
16382     document.body.appendChild(ml.dom);
16383     ml.position('absolute');
16384     ml.setLeftTop(-1000, -1000);
16385     ml.hide();
16386
16387     if(fixedWidth){
16388         ml.setWidth(fixedWidth);
16389     }
16390      
16391     var instance = {
16392         /**
16393          * Returns the size of the specified text based on the internal element's style and width properties
16394          * @param {String} text The text to measure
16395          * @return {Object} An object containing the text's size {width: (width), height: (height)}
16396          */
16397         getSize : function(text){
16398             ml.update(text);
16399             var s = ml.getSize();
16400             ml.update('');
16401             return s;
16402         },
16403
16404         /**
16405          * Binds this TextMetrics instance to an element from which to copy existing CSS styles
16406          * that can affect the size of the rendered text
16407          * @param {String/HTMLElement} el The element, dom node or id
16408          */
16409         bind : function(el){
16410             ml.setStyle(
16411                 Roo.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
16412             );
16413         },
16414
16415         /**
16416          * Sets a fixed width on the internal measurement element.  If the text will be multiline, you have
16417          * to set a fixed width in order to accurately measure the text height.
16418          * @param {Number} width The width to set on the element
16419          */
16420         setFixedWidth : function(width){
16421             ml.setWidth(width);
16422         },
16423
16424         /**
16425          * Returns the measured width of the specified text
16426          * @param {String} text The text to measure
16427          * @return {Number} width The width in pixels
16428          */
16429         getWidth : function(text){
16430             ml.dom.style.width = 'auto';
16431             return this.getSize(text).width;
16432         },
16433
16434         /**
16435          * Returns the measured height of the specified text.  For multiline text, be sure to call
16436          * {@link #setFixedWidth} if necessary.
16437          * @param {String} text The text to measure
16438          * @return {Number} height The height in pixels
16439          */
16440         getHeight : function(text){
16441             return this.getSize(text).height;
16442         }
16443     };
16444
16445     instance.bind(bindTo);
16446
16447     return instance;
16448 };
16449
16450 // backwards compat
16451 Roo.Element.measureText = Roo.util.TextMetrics.measure;/*
16452  * Based on:
16453  * Ext JS Library 1.1.1
16454  * Copyright(c) 2006-2007, Ext JS, LLC.
16455  *
16456  * Originally Released Under LGPL - original licence link has changed is not relivant.
16457  *
16458  * Fork - LGPL
16459  * <script type="text/javascript">
16460  */
16461
16462 /**
16463  * @class Roo.state.Provider
16464  * Abstract base class for state provider implementations. This class provides methods
16465  * for encoding and decoding <b>typed</b> variables including dates and defines the 
16466  * Provider interface.
16467  */
16468 Roo.state.Provider = function(){
16469     /**
16470      * @event statechange
16471      * Fires when a state change occurs.
16472      * @param {Provider} this This state provider
16473      * @param {String} key The state key which was changed
16474      * @param {String} value The encoded value for the state
16475      */
16476     this.addEvents({
16477         "statechange": true
16478     });
16479     this.state = {};
16480     Roo.state.Provider.superclass.constructor.call(this);
16481 };
16482 Roo.extend(Roo.state.Provider, Roo.util.Observable, {
16483     /**
16484      * Returns the current value for a key
16485      * @param {String} name The key name
16486      * @param {Mixed} defaultValue A default value to return if the key's value is not found
16487      * @return {Mixed} The state data
16488      */
16489     get : function(name, defaultValue){
16490         return typeof this.state[name] == "undefined" ?
16491             defaultValue : this.state[name];
16492     },
16493     
16494     /**
16495      * Clears a value from the state
16496      * @param {String} name The key name
16497      */
16498     clear : function(name){
16499         delete this.state[name];
16500         this.fireEvent("statechange", this, name, null);
16501     },
16502     
16503     /**
16504      * Sets the value for a key
16505      * @param {String} name The key name
16506      * @param {Mixed} value The value to set
16507      */
16508     set : function(name, value){
16509         this.state[name] = value;
16510         this.fireEvent("statechange", this, name, value);
16511     },
16512     
16513     /**
16514      * Decodes a string previously encoded with {@link #encodeValue}.
16515      * @param {String} value The value to decode
16516      * @return {Mixed} The decoded value
16517      */
16518     decodeValue : function(cookie){
16519         var re = /^(a|n|d|b|s|o)\:(.*)$/;
16520         var matches = re.exec(unescape(cookie));
16521         if(!matches || !matches[1]) {
16522             return; // non state cookie
16523         }
16524         var type = matches[1];
16525         var v = matches[2];
16526         switch(type){
16527             case "n":
16528                 return parseFloat(v);
16529             case "d":
16530                 return new Date(Date.parse(v));
16531             case "b":
16532                 return (v == "1");
16533             case "a":
16534                 var all = [];
16535                 var values = v.split("^");
16536                 for(var i = 0, len = values.length; i < len; i++){
16537                     all.push(this.decodeValue(values[i]));
16538                 }
16539                 return all;
16540            case "o":
16541                 var all = {};
16542                 var values = v.split("^");
16543                 for(var i = 0, len = values.length; i < len; i++){
16544                     var kv = values[i].split("=");
16545                     all[kv[0]] = this.decodeValue(kv[1]);
16546                 }
16547                 return all;
16548            default:
16549                 return v;
16550         }
16551     },
16552     
16553     /**
16554      * Encodes a value including type information.  Decode with {@link #decodeValue}.
16555      * @param {Mixed} value The value to encode
16556      * @return {String} The encoded value
16557      */
16558     encodeValue : function(v){
16559         var enc;
16560         if(typeof v == "number"){
16561             enc = "n:" + v;
16562         }else if(typeof v == "boolean"){
16563             enc = "b:" + (v ? "1" : "0");
16564         }else if(v instanceof Date){
16565             enc = "d:" + v.toGMTString();
16566         }else if(v instanceof Array){
16567             var flat = "";
16568             for(var i = 0, len = v.length; i < len; i++){
16569                 flat += this.encodeValue(v[i]);
16570                 if(i != len-1) {
16571                     flat += "^";
16572                 }
16573             }
16574             enc = "a:" + flat;
16575         }else if(typeof v == "object"){
16576             var flat = "";
16577             for(var key in v){
16578                 if(typeof v[key] != "function"){
16579                     flat += key + "=" + this.encodeValue(v[key]) + "^";
16580                 }
16581             }
16582             enc = "o:" + flat.substring(0, flat.length-1);
16583         }else{
16584             enc = "s:" + v;
16585         }
16586         return escape(enc);        
16587     }
16588 });
16589
16590 /*
16591  * Based on:
16592  * Ext JS Library 1.1.1
16593  * Copyright(c) 2006-2007, Ext JS, LLC.
16594  *
16595  * Originally Released Under LGPL - original licence link has changed is not relivant.
16596  *
16597  * Fork - LGPL
16598  * <script type="text/javascript">
16599  */
16600 /**
16601  * @class Roo.state.Manager
16602  * This is the global state manager. By default all components that are "state aware" check this class
16603  * for state information if you don't pass them a custom state provider. In order for this class
16604  * to be useful, it must be initialized with a provider when your application initializes.
16605  <pre><code>
16606 // in your initialization function
16607 init : function(){
16608    Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
16609    ...
16610    // supposed you have a {@link Roo.BorderLayout}
16611    var layout = new Roo.BorderLayout(...);
16612    layout.restoreState();
16613    // or a {Roo.BasicDialog}
16614    var dialog = new Roo.BasicDialog(...);
16615    dialog.restoreState();
16616  </code></pre>
16617  * @static
16618  */
16619 Roo.state.Manager = function(){
16620     var provider = new Roo.state.Provider();
16621     
16622     return {
16623         /**
16624          * Configures the default state provider for your application
16625          * @param {Provider} stateProvider The state provider to set
16626          */
16627         setProvider : function(stateProvider){
16628             provider = stateProvider;
16629         },
16630         
16631         /**
16632          * Returns the current value for a key
16633          * @param {String} name The key name
16634          * @param {Mixed} defaultValue The default value to return if the key lookup does not match
16635          * @return {Mixed} The state data
16636          */
16637         get : function(key, defaultValue){
16638             return provider.get(key, defaultValue);
16639         },
16640         
16641         /**
16642          * Sets the value for a key
16643          * @param {String} name The key name
16644          * @param {Mixed} value The state data
16645          */
16646          set : function(key, value){
16647             provider.set(key, value);
16648         },
16649         
16650         /**
16651          * Clears a value from the state
16652          * @param {String} name The key name
16653          */
16654         clear : function(key){
16655             provider.clear(key);
16656         },
16657         
16658         /**
16659          * Gets the currently configured state provider
16660          * @return {Provider} The state provider
16661          */
16662         getProvider : function(){
16663             return provider;
16664         }
16665     };
16666 }();
16667 /*
16668  * Based on:
16669  * Ext JS Library 1.1.1
16670  * Copyright(c) 2006-2007, Ext JS, LLC.
16671  *
16672  * Originally Released Under LGPL - original licence link has changed is not relivant.
16673  *
16674  * Fork - LGPL
16675  * <script type="text/javascript">
16676  */
16677 /**
16678  * @class Roo.state.CookieProvider
16679  * @extends Roo.state.Provider
16680  * The default Provider implementation which saves state via cookies.
16681  * <br />Usage:
16682  <pre><code>
16683    var cp = new Roo.state.CookieProvider({
16684        path: "/cgi-bin/",
16685        expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30 days
16686        domain: "roojs.com"
16687    })
16688    Roo.state.Manager.setProvider(cp);
16689  </code></pre>
16690  * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
16691  * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
16692  * @cfg {String} domain The domain to save the cookie for.  Note that you cannot specify a different domain than
16693  * your page is on, but you can specify a sub-domain, or simply the domain itself like 'roojs.com' to include
16694  * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
16695  * domain the page is running on including the 'www' like 'www.roojs.com')
16696  * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
16697  * @constructor
16698  * Create a new CookieProvider
16699  * @param {Object} config The configuration object
16700  */
16701 Roo.state.CookieProvider = function(config){
16702     Roo.state.CookieProvider.superclass.constructor.call(this);
16703     this.path = "/";
16704     this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
16705     this.domain = null;
16706     this.secure = false;
16707     Roo.apply(this, config);
16708     this.state = this.readCookies();
16709 };
16710
16711 Roo.extend(Roo.state.CookieProvider, Roo.state.Provider, {
16712     // private
16713     set : function(name, value){
16714         if(typeof value == "undefined" || value === null){
16715             this.clear(name);
16716             return;
16717         }
16718         this.setCookie(name, value);
16719         Roo.state.CookieProvider.superclass.set.call(this, name, value);
16720     },
16721
16722     // private
16723     clear : function(name){
16724         this.clearCookie(name);
16725         Roo.state.CookieProvider.superclass.clear.call(this, name);
16726     },
16727
16728     // private
16729     readCookies : function(){
16730         var cookies = {};
16731         var c = document.cookie + ";";
16732         var re = /\s?(.*?)=(.*?);/g;
16733         var matches;
16734         while((matches = re.exec(c)) != null){
16735             var name = matches[1];
16736             var value = matches[2];
16737             if(name && name.substring(0,3) == "ys-"){
16738                 cookies[name.substr(3)] = this.decodeValue(value);
16739             }
16740         }
16741         return cookies;
16742     },
16743
16744     // private
16745     setCookie : function(name, value){
16746         document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
16747            ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
16748            ((this.path == null) ? "" : ("; path=" + this.path)) +
16749            ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16750            ((this.secure == true) ? "; secure" : "");
16751     },
16752
16753     // private
16754     clearCookie : function(name){
16755         document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
16756            ((this.path == null) ? "" : ("; path=" + this.path)) +
16757            ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16758            ((this.secure == true) ? "; secure" : "");
16759     }
16760 });/*
16761  * Based on:
16762  * Ext JS Library 1.1.1
16763  * Copyright(c) 2006-2007, Ext JS, LLC.
16764  *
16765  * Originally Released Under LGPL - original licence link has changed is not relivant.
16766  *
16767  * Fork - LGPL
16768  * <script type="text/javascript">
16769  */
16770  
16771
16772 /**
16773  * @class Roo.ComponentMgr
16774  * Provides a common registry of all components on a page so that they can be easily accessed by component id (see {@link Roo.getCmp}).
16775  * @static
16776  */
16777 Roo.ComponentMgr = function(){
16778     var all = new Roo.util.MixedCollection();
16779
16780     return {
16781         /**
16782          * Registers a component.
16783          * @param {Roo.Component} c The component
16784          */
16785         register : function(c){
16786             all.add(c);
16787         },
16788
16789         /**
16790          * Unregisters a component.
16791          * @param {Roo.Component} c The component
16792          */
16793         unregister : function(c){
16794             all.remove(c);
16795         },
16796
16797         /**
16798          * Returns a component by id
16799          * @param {String} id The component id
16800          */
16801         get : function(id){
16802             return all.get(id);
16803         },
16804
16805         /**
16806          * Registers a function that will be called when a specified component is added to ComponentMgr
16807          * @param {String} id The component id
16808          * @param {Funtction} fn The callback function
16809          * @param {Object} scope The scope of the callback
16810          */
16811         onAvailable : function(id, fn, scope){
16812             all.on("add", function(index, o){
16813                 if(o.id == id){
16814                     fn.call(scope || o, o);
16815                     all.un("add", fn, scope);
16816                 }
16817             });
16818         }
16819     };
16820 }();/*
16821  * Based on:
16822  * Ext JS Library 1.1.1
16823  * Copyright(c) 2006-2007, Ext JS, LLC.
16824  *
16825  * Originally Released Under LGPL - original licence link has changed is not relivant.
16826  *
16827  * Fork - LGPL
16828  * <script type="text/javascript">
16829  */
16830  
16831 /**
16832  * @class Roo.Component
16833  * @extends Roo.util.Observable
16834  * Base class for all major Roo components.  All subclasses of Component can automatically participate in the standard
16835  * Roo component lifecycle of creation, rendering and destruction.  They also have automatic support for basic hide/show
16836  * and enable/disable behavior.  Component allows any subclass to be lazy-rendered into any {@link Roo.Container} and
16837  * to be automatically registered with the {@link Roo.ComponentMgr} so that it can be referenced at any time via {@link Roo.getCmp}.
16838  * All visual components (widgets) that require rendering into a layout should subclass Component.
16839  * @constructor
16840  * @param {Roo.Element/String/Object} config The configuration options.  If an element is passed, it is set as the internal
16841  * element and its id used as the component id.  If a string is passed, it is assumed to be the id of an existing element
16842  * and is used as the component id.  Otherwise, it is assumed to be a standard config object and is applied to the component.
16843  */
16844 Roo.Component = function(config){
16845     config = config || {};
16846     if(config.tagName || config.dom || typeof config == "string"){ // element object
16847         config = {el: config, id: config.id || config};
16848     }
16849     this.initialConfig = config;
16850
16851     Roo.apply(this, config);
16852     this.addEvents({
16853         /**
16854          * @event disable
16855          * Fires after the component is disabled.
16856              * @param {Roo.Component} this
16857              */
16858         disable : true,
16859         /**
16860          * @event enable
16861          * Fires after the component is enabled.
16862              * @param {Roo.Component} this
16863              */
16864         enable : true,
16865         /**
16866          * @event beforeshow
16867          * Fires before the component is shown.  Return false to stop the show.
16868              * @param {Roo.Component} this
16869              */
16870         beforeshow : true,
16871         /**
16872          * @event show
16873          * Fires after the component is shown.
16874              * @param {Roo.Component} this
16875              */
16876         show : true,
16877         /**
16878          * @event beforehide
16879          * Fires before the component is hidden. Return false to stop the hide.
16880              * @param {Roo.Component} this
16881              */
16882         beforehide : true,
16883         /**
16884          * @event hide
16885          * Fires after the component is hidden.
16886              * @param {Roo.Component} this
16887              */
16888         hide : true,
16889         /**
16890          * @event beforerender
16891          * Fires before the component is rendered. Return false to stop the render.
16892              * @param {Roo.Component} this
16893              */
16894         beforerender : true,
16895         /**
16896          * @event render
16897          * Fires after the component is rendered.
16898              * @param {Roo.Component} this
16899              */
16900         render : true,
16901         /**
16902          * @event beforedestroy
16903          * Fires before the component is destroyed. Return false to stop the destroy.
16904              * @param {Roo.Component} this
16905              */
16906         beforedestroy : true,
16907         /**
16908          * @event destroy
16909          * Fires after the component is destroyed.
16910              * @param {Roo.Component} this
16911              */
16912         destroy : true
16913     });
16914     if(!this.id){
16915         this.id = "roo-comp-" + (++Roo.Component.AUTO_ID);
16916     }
16917     Roo.ComponentMgr.register(this);
16918     Roo.Component.superclass.constructor.call(this);
16919     this.initComponent();
16920     if(this.renderTo){ // not supported by all components yet. use at your own risk!
16921         this.render(this.renderTo);
16922         delete this.renderTo;
16923     }
16924 };
16925
16926 /** @private */
16927 Roo.Component.AUTO_ID = 1000;
16928
16929 Roo.extend(Roo.Component, Roo.util.Observable, {
16930     /**
16931      * @scope Roo.Component.prototype
16932      * @type {Boolean}
16933      * true if this component is hidden. Read-only.
16934      */
16935     hidden : false,
16936     /**
16937      * @type {Boolean}
16938      * true if this component is disabled. Read-only.
16939      */
16940     disabled : false,
16941     /**
16942      * @type {Boolean}
16943      * true if this component has been rendered. Read-only.
16944      */
16945     rendered : false,
16946     
16947     /** @cfg {String} disableClass
16948      * CSS class added to the component when it is disabled (defaults to "x-item-disabled").
16949      */
16950     disabledClass : "x-item-disabled",
16951         /** @cfg {Boolean} allowDomMove
16952          * Whether the component can move the Dom node when rendering (defaults to true).
16953          */
16954     allowDomMove : true,
16955     /** @cfg {String} hideMode (display|visibility)
16956      * How this component should hidden. Supported values are
16957      * "visibility" (css visibility), "offsets" (negative offset position) and
16958      * "display" (css display) - defaults to "display".
16959      */
16960     hideMode: 'display',
16961
16962     /** @private */
16963     ctype : "Roo.Component",
16964
16965     /**
16966      * @cfg {String} actionMode 
16967      * which property holds the element that used for  hide() / show() / disable() / enable()
16968      * default is 'el' for forms you probably want to set this to fieldEl 
16969      */
16970     actionMode : "el",
16971
16972     /** @private */
16973     getActionEl : function(){
16974         return this[this.actionMode];
16975     },
16976
16977     initComponent : Roo.emptyFn,
16978     /**
16979      * If this is a lazy rendering component, render it to its container element.
16980      * @param {String/HTMLElement/Element} container (optional) The element this component should be rendered into. If it is being applied to existing markup, this should be left off.
16981      */
16982     render : function(container, position){
16983         
16984         if(this.rendered){
16985             return this;
16986         }
16987         
16988         if(this.fireEvent("beforerender", this) === false){
16989             return false;
16990         }
16991         
16992         if(!container && this.el){
16993             this.el = Roo.get(this.el);
16994             container = this.el.dom.parentNode;
16995             this.allowDomMove = false;
16996         }
16997         this.container = Roo.get(container);
16998         this.rendered = true;
16999         if(position !== undefined){
17000             if(typeof position == 'number'){
17001                 position = this.container.dom.childNodes[position];
17002             }else{
17003                 position = Roo.getDom(position);
17004             }
17005         }
17006         this.onRender(this.container, position || null);
17007         if(this.cls){
17008             this.el.addClass(this.cls);
17009             delete this.cls;
17010         }
17011         if(this.style){
17012             this.el.applyStyles(this.style);
17013             delete this.style;
17014         }
17015         this.fireEvent("render", this);
17016         this.afterRender(this.container);
17017         if(this.hidden){
17018             this.hide();
17019         }
17020         if(this.disabled){
17021             this.disable();
17022         }
17023
17024         return this;
17025         
17026     },
17027
17028     /** @private */
17029     // default function is not really useful
17030     onRender : function(ct, position){
17031         if(this.el){
17032             this.el = Roo.get(this.el);
17033             if(this.allowDomMove !== false){
17034                 ct.dom.insertBefore(this.el.dom, position);
17035             }
17036         }
17037     },
17038
17039     /** @private */
17040     getAutoCreate : function(){
17041         var cfg = typeof this.autoCreate == "object" ?
17042                       this.autoCreate : Roo.apply({}, this.defaultAutoCreate);
17043         if(this.id && !cfg.id){
17044             cfg.id = this.id;
17045         }
17046         return cfg;
17047     },
17048
17049     /** @private */
17050     afterRender : Roo.emptyFn,
17051
17052     /**
17053      * Destroys this component by purging any event listeners, removing the component's element from the DOM,
17054      * removing the component from its {@link Roo.Container} (if applicable) and unregistering it from {@link Roo.ComponentMgr}.
17055      */
17056     destroy : function(){
17057         if(this.fireEvent("beforedestroy", this) !== false){
17058             this.purgeListeners();
17059             this.beforeDestroy();
17060             if(this.rendered){
17061                 this.el.removeAllListeners();
17062                 this.el.remove();
17063                 if(this.actionMode == "container"){
17064                     this.container.remove();
17065                 }
17066             }
17067             this.onDestroy();
17068             Roo.ComponentMgr.unregister(this);
17069             this.fireEvent("destroy", this);
17070         }
17071     },
17072
17073         /** @private */
17074     beforeDestroy : function(){
17075
17076     },
17077
17078         /** @private */
17079         onDestroy : function(){
17080
17081     },
17082
17083     /**
17084      * Returns the underlying {@link Roo.Element}.
17085      * @return {Roo.Element} The element
17086      */
17087     getEl : function(){
17088         return this.el;
17089     },
17090
17091     /**
17092      * Returns the id of this component.
17093      * @return {String}
17094      */
17095     getId : function(){
17096         return this.id;
17097     },
17098
17099     /**
17100      * Try to focus this component.
17101      * @param {Boolean} selectText True to also select the text in this component (if applicable)
17102      * @return {Roo.Component} this
17103      */
17104     focus : function(selectText){
17105         if(this.rendered){
17106             this.el.focus();
17107             if(selectText === true){
17108                 this.el.dom.select();
17109             }
17110         }
17111         return this;
17112     },
17113
17114     /** @private */
17115     blur : function(){
17116         if(this.rendered){
17117             this.el.blur();
17118         }
17119         return this;
17120     },
17121
17122     /**
17123      * Disable this component.
17124      * @return {Roo.Component} this
17125      */
17126     disable : function(){
17127         if(this.rendered){
17128             this.onDisable();
17129         }
17130         this.disabled = true;
17131         this.fireEvent("disable", this);
17132         return this;
17133     },
17134
17135         // private
17136     onDisable : function(){
17137         this.getActionEl().addClass(this.disabledClass);
17138         this.el.dom.disabled = true;
17139     },
17140
17141     /**
17142      * Enable this component.
17143      * @return {Roo.Component} this
17144      */
17145     enable : function(){
17146         if(this.rendered){
17147             this.onEnable();
17148         }
17149         this.disabled = false;
17150         this.fireEvent("enable", this);
17151         return this;
17152     },
17153
17154         // private
17155     onEnable : function(){
17156         this.getActionEl().removeClass(this.disabledClass);
17157         this.el.dom.disabled = false;
17158     },
17159
17160     /**
17161      * Convenience function for setting disabled/enabled by boolean.
17162      * @param {Boolean} disabled
17163      */
17164     setDisabled : function(disabled){
17165         this[disabled ? "disable" : "enable"]();
17166     },
17167
17168     /**
17169      * Show this component.
17170      * @return {Roo.Component} this
17171      */
17172     show: function(){
17173         if(this.fireEvent("beforeshow", this) !== false){
17174             this.hidden = false;
17175             if(this.rendered){
17176                 this.onShow();
17177             }
17178             this.fireEvent("show", this);
17179         }
17180         return this;
17181     },
17182
17183     // private
17184     onShow : function(){
17185         var ae = this.getActionEl();
17186         if(this.hideMode == 'visibility'){
17187             ae.dom.style.visibility = "visible";
17188         }else if(this.hideMode == 'offsets'){
17189             ae.removeClass('x-hidden');
17190         }else{
17191             ae.dom.style.display = "";
17192         }
17193     },
17194
17195     /**
17196      * Hide this component.
17197      * @return {Roo.Component} this
17198      */
17199     hide: function(){
17200         if(this.fireEvent("beforehide", this) !== false){
17201             this.hidden = true;
17202             if(this.rendered){
17203                 this.onHide();
17204             }
17205             this.fireEvent("hide", this);
17206         }
17207         return this;
17208     },
17209
17210     // private
17211     onHide : function(){
17212         var ae = this.getActionEl();
17213         if(this.hideMode == 'visibility'){
17214             ae.dom.style.visibility = "hidden";
17215         }else if(this.hideMode == 'offsets'){
17216             ae.addClass('x-hidden');
17217         }else{
17218             ae.dom.style.display = "none";
17219         }
17220     },
17221
17222     /**
17223      * Convenience function to hide or show this component by boolean.
17224      * @param {Boolean} visible True to show, false to hide
17225      * @return {Roo.Component} this
17226      */
17227     setVisible: function(visible){
17228         if(visible) {
17229             this.show();
17230         }else{
17231             this.hide();
17232         }
17233         return this;
17234     },
17235
17236     /**
17237      * Returns true if this component is visible.
17238      */
17239     isVisible : function(){
17240         return this.getActionEl().isVisible();
17241     },
17242
17243     cloneConfig : function(overrides){
17244         overrides = overrides || {};
17245         var id = overrides.id || Roo.id();
17246         var cfg = Roo.applyIf(overrides, this.initialConfig);
17247         cfg.id = id; // prevent dup id
17248         return new this.constructor(cfg);
17249     }
17250 });/*
17251  * Based on:
17252  * Ext JS Library 1.1.1
17253  * Copyright(c) 2006-2007, Ext JS, LLC.
17254  *
17255  * Originally Released Under LGPL - original licence link has changed is not relivant.
17256  *
17257  * Fork - LGPL
17258  * <script type="text/javascript">
17259  */
17260
17261 /**
17262  * @class Roo.BoxComponent
17263  * @extends Roo.Component
17264  * Base class for any visual {@link Roo.Component} that uses a box container.  BoxComponent provides automatic box
17265  * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model.  All
17266  * container classes should subclass BoxComponent so that they will work consistently when nested within other Roo
17267  * layout containers.
17268  * @constructor
17269  * @param {Roo.Element/String/Object} config The configuration options.
17270  */
17271 Roo.BoxComponent = function(config){
17272     Roo.Component.call(this, config);
17273     this.addEvents({
17274         /**
17275          * @event resize
17276          * Fires after the component is resized.
17277              * @param {Roo.Component} this
17278              * @param {Number} adjWidth The box-adjusted width that was set
17279              * @param {Number} adjHeight The box-adjusted height that was set
17280              * @param {Number} rawWidth The width that was originally specified
17281              * @param {Number} rawHeight The height that was originally specified
17282              */
17283         resize : true,
17284         /**
17285          * @event move
17286          * Fires after the component is moved.
17287              * @param {Roo.Component} this
17288              * @param {Number} x The new x position
17289              * @param {Number} y The new y position
17290              */
17291         move : true
17292     });
17293 };
17294
17295 Roo.extend(Roo.BoxComponent, Roo.Component, {
17296     // private, set in afterRender to signify that the component has been rendered
17297     boxReady : false,
17298     // private, used to defer height settings to subclasses
17299     deferHeight: false,
17300     /** @cfg {Number} width
17301      * width (optional) size of component
17302      */
17303      /** @cfg {Number} height
17304      * height (optional) size of component
17305      */
17306      
17307     /**
17308      * Sets the width and height of the component.  This method fires the resize event.  This method can accept
17309      * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
17310      * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
17311      * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
17312      * @return {Roo.BoxComponent} this
17313      */
17314     setSize : function(w, h){
17315         // support for standard size objects
17316         if(typeof w == 'object'){
17317             h = w.height;
17318             w = w.width;
17319         }
17320         // not rendered
17321         if(!this.boxReady){
17322             this.width = w;
17323             this.height = h;
17324             return this;
17325         }
17326
17327         // prevent recalcs when not needed
17328         if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
17329             return this;
17330         }
17331         this.lastSize = {width: w, height: h};
17332
17333         var adj = this.adjustSize(w, h);
17334         var aw = adj.width, ah = adj.height;
17335         if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
17336             var rz = this.getResizeEl();
17337             if(!this.deferHeight && aw !== undefined && ah !== undefined){
17338                 rz.setSize(aw, ah);
17339             }else if(!this.deferHeight && ah !== undefined){
17340                 rz.setHeight(ah);
17341             }else if(aw !== undefined){
17342                 rz.setWidth(aw);
17343             }
17344             this.onResize(aw, ah, w, h);
17345             this.fireEvent('resize', this, aw, ah, w, h);
17346         }
17347         return this;
17348     },
17349
17350     /**
17351      * Gets the current size of the component's underlying element.
17352      * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
17353      */
17354     getSize : function(){
17355         return this.el.getSize();
17356     },
17357
17358     /**
17359      * Gets the current XY position of the component's underlying element.
17360      * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
17361      * @return {Array} The XY position of the element (e.g., [100, 200])
17362      */
17363     getPosition : function(local){
17364         if(local === true){
17365             return [this.el.getLeft(true), this.el.getTop(true)];
17366         }
17367         return this.xy || this.el.getXY();
17368     },
17369
17370     /**
17371      * Gets the current box measurements of the component's underlying element.
17372      * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
17373      * @returns {Object} box An object in the format {x, y, width, height}
17374      */
17375     getBox : function(local){
17376         var s = this.el.getSize();
17377         if(local){
17378             s.x = this.el.getLeft(true);
17379             s.y = this.el.getTop(true);
17380         }else{
17381             var xy = this.xy || this.el.getXY();
17382             s.x = xy[0];
17383             s.y = xy[1];
17384         }
17385         return s;
17386     },
17387
17388     /**
17389      * Sets the current box measurements of the component's underlying element.
17390      * @param {Object} box An object in the format {x, y, width, height}
17391      * @returns {Roo.BoxComponent} this
17392      */
17393     updateBox : function(box){
17394         this.setSize(box.width, box.height);
17395         this.setPagePosition(box.x, box.y);
17396         return this;
17397     },
17398
17399     // protected
17400     getResizeEl : function(){
17401         return this.resizeEl || this.el;
17402     },
17403
17404     // protected
17405     getPositionEl : function(){
17406         return this.positionEl || this.el;
17407     },
17408
17409     /**
17410      * Sets the left and top of the component.  To set the page XY position instead, use {@link #setPagePosition}.
17411      * This method fires the move event.
17412      * @param {Number} left The new left
17413      * @param {Number} top The new top
17414      * @returns {Roo.BoxComponent} this
17415      */
17416     setPosition : function(x, y){
17417         this.x = x;
17418         this.y = y;
17419         if(!this.boxReady){
17420             return this;
17421         }
17422         var adj = this.adjustPosition(x, y);
17423         var ax = adj.x, ay = adj.y;
17424
17425         var el = this.getPositionEl();
17426         if(ax !== undefined || ay !== undefined){
17427             if(ax !== undefined && ay !== undefined){
17428                 el.setLeftTop(ax, ay);
17429             }else if(ax !== undefined){
17430                 el.setLeft(ax);
17431             }else if(ay !== undefined){
17432                 el.setTop(ay);
17433             }
17434             this.onPosition(ax, ay);
17435             this.fireEvent('move', this, ax, ay);
17436         }
17437         return this;
17438     },
17439
17440     /**
17441      * Sets the page XY position of the component.  To set the left and top instead, use {@link #setPosition}.
17442      * This method fires the move event.
17443      * @param {Number} x The new x position
17444      * @param {Number} y The new y position
17445      * @returns {Roo.BoxComponent} this
17446      */
17447     setPagePosition : function(x, y){
17448         this.pageX = x;
17449         this.pageY = y;
17450         if(!this.boxReady){
17451             return;
17452         }
17453         if(x === undefined || y === undefined){ // cannot translate undefined points
17454             return;
17455         }
17456         var p = this.el.translatePoints(x, y);
17457         this.setPosition(p.left, p.top);
17458         return this;
17459     },
17460
17461     // private
17462     onRender : function(ct, position){
17463         Roo.BoxComponent.superclass.onRender.call(this, ct, position);
17464         if(this.resizeEl){
17465             this.resizeEl = Roo.get(this.resizeEl);
17466         }
17467         if(this.positionEl){
17468             this.positionEl = Roo.get(this.positionEl);
17469         }
17470     },
17471
17472     // private
17473     afterRender : function(){
17474         Roo.BoxComponent.superclass.afterRender.call(this);
17475         this.boxReady = true;
17476         this.setSize(this.width, this.height);
17477         if(this.x || this.y){
17478             this.setPosition(this.x, this.y);
17479         }
17480         if(this.pageX || this.pageY){
17481             this.setPagePosition(this.pageX, this.pageY);
17482         }
17483     },
17484
17485     /**
17486      * Force the component's size to recalculate based on the underlying element's current height and width.
17487      * @returns {Roo.BoxComponent} this
17488      */
17489     syncSize : function(){
17490         delete this.lastSize;
17491         this.setSize(this.el.getWidth(), this.el.getHeight());
17492         return this;
17493     },
17494
17495     /**
17496      * Called after the component is resized, this method is empty by default but can be implemented by any
17497      * subclass that needs to perform custom logic after a resize occurs.
17498      * @param {Number} adjWidth The box-adjusted width that was set
17499      * @param {Number} adjHeight The box-adjusted height that was set
17500      * @param {Number} rawWidth The width that was originally specified
17501      * @param {Number} rawHeight The height that was originally specified
17502      */
17503     onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
17504
17505     },
17506
17507     /**
17508      * Called after the component is moved, this method is empty by default but can be implemented by any
17509      * subclass that needs to perform custom logic after a move occurs.
17510      * @param {Number} x The new x position
17511      * @param {Number} y The new y position
17512      */
17513     onPosition : function(x, y){
17514
17515     },
17516
17517     // private
17518     adjustSize : function(w, h){
17519         if(this.autoWidth){
17520             w = 'auto';
17521         }
17522         if(this.autoHeight){
17523             h = 'auto';
17524         }
17525         return {width : w, height: h};
17526     },
17527
17528     // private
17529     adjustPosition : function(x, y){
17530         return {x : x, y: y};
17531     }
17532 });/*
17533  * Based on:
17534  * Ext JS Library 1.1.1
17535  * Copyright(c) 2006-2007, Ext JS, LLC.
17536  *
17537  * Originally Released Under LGPL - original licence link has changed is not relivant.
17538  *
17539  * Fork - LGPL
17540  * <script type="text/javascript">
17541  */
17542  (function(){ 
17543 /**
17544  * @class Roo.Layer
17545  * @extends Roo.Element
17546  * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
17547  * automatic maintaining of shadow/shim positions.
17548  * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
17549  * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
17550  * you can pass a string with a CSS class name. False turns off the shadow.
17551  * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
17552  * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
17553  * @cfg {String} cls CSS class to add to the element
17554  * @cfg {Number} zindex Starting z-index (defaults to 11000)
17555  * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
17556  * @constructor
17557  * @param {Object} config An object with config options.
17558  * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
17559  */
17560
17561 Roo.Layer = function(config, existingEl){
17562     config = config || {};
17563     var dh = Roo.DomHelper;
17564     var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
17565     if(existingEl){
17566         this.dom = Roo.getDom(existingEl);
17567     }
17568     if(!this.dom){
17569         var o = config.dh || {tag: "div", cls: "x-layer"};
17570         this.dom = dh.append(pel, o);
17571     }
17572     if(config.cls){
17573         this.addClass(config.cls);
17574     }
17575     this.constrain = config.constrain !== false;
17576     this.visibilityMode = Roo.Element.VISIBILITY;
17577     if(config.id){
17578         this.id = this.dom.id = config.id;
17579     }else{
17580         this.id = Roo.id(this.dom);
17581     }
17582     this.zindex = config.zindex || this.getZIndex();
17583     this.position("absolute", this.zindex);
17584     if(config.shadow){
17585         this.shadowOffset = config.shadowOffset || 4;
17586         this.shadow = new Roo.Shadow({
17587             offset : this.shadowOffset,
17588             mode : config.shadow
17589         });
17590     }else{
17591         this.shadowOffset = 0;
17592     }
17593     this.useShim = config.shim !== false && Roo.useShims;
17594     this.useDisplay = config.useDisplay;
17595     this.hide();
17596 };
17597
17598 var supr = Roo.Element.prototype;
17599
17600 // shims are shared among layer to keep from having 100 iframes
17601 var shims = [];
17602
17603 Roo.extend(Roo.Layer, Roo.Element, {
17604
17605     getZIndex : function(){
17606         return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
17607     },
17608
17609     getShim : function(){
17610         if(!this.useShim){
17611             return null;
17612         }
17613         if(this.shim){
17614             return this.shim;
17615         }
17616         var shim = shims.shift();
17617         if(!shim){
17618             shim = this.createShim();
17619             shim.enableDisplayMode('block');
17620             shim.dom.style.display = 'none';
17621             shim.dom.style.visibility = 'visible';
17622         }
17623         var pn = this.dom.parentNode;
17624         if(shim.dom.parentNode != pn){
17625             pn.insertBefore(shim.dom, this.dom);
17626         }
17627         shim.setStyle('z-index', this.getZIndex()-2);
17628         this.shim = shim;
17629         return shim;
17630     },
17631
17632     hideShim : function(){
17633         if(this.shim){
17634             this.shim.setDisplayed(false);
17635             shims.push(this.shim);
17636             delete this.shim;
17637         }
17638     },
17639
17640     disableShadow : function(){
17641         if(this.shadow){
17642             this.shadowDisabled = true;
17643             this.shadow.hide();
17644             this.lastShadowOffset = this.shadowOffset;
17645             this.shadowOffset = 0;
17646         }
17647     },
17648
17649     enableShadow : function(show){
17650         if(this.shadow){
17651             this.shadowDisabled = false;
17652             this.shadowOffset = this.lastShadowOffset;
17653             delete this.lastShadowOffset;
17654             if(show){
17655                 this.sync(true);
17656             }
17657         }
17658     },
17659
17660     // private
17661     // this code can execute repeatedly in milliseconds (i.e. during a drag) so
17662     // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
17663     sync : function(doShow){
17664         var sw = this.shadow;
17665         if(!this.updating && this.isVisible() && (sw || this.useShim)){
17666             var sh = this.getShim();
17667
17668             var w = this.getWidth(),
17669                 h = this.getHeight();
17670
17671             var l = this.getLeft(true),
17672                 t = this.getTop(true);
17673
17674             if(sw && !this.shadowDisabled){
17675                 if(doShow && !sw.isVisible()){
17676                     sw.show(this);
17677                 }else{
17678                     sw.realign(l, t, w, h);
17679                 }
17680                 if(sh){
17681                     if(doShow){
17682                        sh.show();
17683                     }
17684                     // fit the shim behind the shadow, so it is shimmed too
17685                     var a = sw.adjusts, s = sh.dom.style;
17686                     s.left = (Math.min(l, l+a.l))+"px";
17687                     s.top = (Math.min(t, t+a.t))+"px";
17688                     s.width = (w+a.w)+"px";
17689                     s.height = (h+a.h)+"px";
17690                 }
17691             }else if(sh){
17692                 if(doShow){
17693                    sh.show();
17694                 }
17695                 sh.setSize(w, h);
17696                 sh.setLeftTop(l, t);
17697             }
17698             
17699         }
17700     },
17701
17702     // private
17703     destroy : function(){
17704         this.hideShim();
17705         if(this.shadow){
17706             this.shadow.hide();
17707         }
17708         this.removeAllListeners();
17709         var pn = this.dom.parentNode;
17710         if(pn){
17711             pn.removeChild(this.dom);
17712         }
17713         Roo.Element.uncache(this.id);
17714     },
17715
17716     remove : function(){
17717         this.destroy();
17718     },
17719
17720     // private
17721     beginUpdate : function(){
17722         this.updating = true;
17723     },
17724
17725     // private
17726     endUpdate : function(){
17727         this.updating = false;
17728         this.sync(true);
17729     },
17730
17731     // private
17732     hideUnders : function(negOffset){
17733         if(this.shadow){
17734             this.shadow.hide();
17735         }
17736         this.hideShim();
17737     },
17738
17739     // private
17740     constrainXY : function(){
17741         if(this.constrain){
17742             var vw = Roo.lib.Dom.getViewWidth(),
17743                 vh = Roo.lib.Dom.getViewHeight();
17744             var s = Roo.get(document).getScroll();
17745
17746             var xy = this.getXY();
17747             var x = xy[0], y = xy[1];   
17748             var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
17749             // only move it if it needs it
17750             var moved = false;
17751             // first validate right/bottom
17752             if((x + w) > vw+s.left){
17753                 x = vw - w - this.shadowOffset;
17754                 moved = true;
17755             }
17756             if((y + h) > vh+s.top){
17757                 y = vh - h - this.shadowOffset;
17758                 moved = true;
17759             }
17760             // then make sure top/left isn't negative
17761             if(x < s.left){
17762                 x = s.left;
17763                 moved = true;
17764             }
17765             if(y < s.top){
17766                 y = s.top;
17767                 moved = true;
17768             }
17769             if(moved){
17770                 if(this.avoidY){
17771                     var ay = this.avoidY;
17772                     if(y <= ay && (y+h) >= ay){
17773                         y = ay-h-5;   
17774                     }
17775                 }
17776                 xy = [x, y];
17777                 this.storeXY(xy);
17778                 supr.setXY.call(this, xy);
17779                 this.sync();
17780             }
17781         }
17782     },
17783
17784     isVisible : function(){
17785         return this.visible;    
17786     },
17787
17788     // private
17789     showAction : function(){
17790         this.visible = true; // track visibility to prevent getStyle calls
17791         if(this.useDisplay === true){
17792             this.setDisplayed("");
17793         }else if(this.lastXY){
17794             supr.setXY.call(this, this.lastXY);
17795         }else if(this.lastLT){
17796             supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
17797         }
17798     },
17799
17800     // private
17801     hideAction : function(){
17802         this.visible = false;
17803         if(this.useDisplay === true){
17804             this.setDisplayed(false);
17805         }else{
17806             this.setLeftTop(-10000,-10000);
17807         }
17808     },
17809
17810     // overridden Element method
17811     setVisible : function(v, a, d, c, e){
17812         if(v){
17813             this.showAction();
17814         }
17815         if(a && v){
17816             var cb = function(){
17817                 this.sync(true);
17818                 if(c){
17819                     c();
17820                 }
17821             }.createDelegate(this);
17822             supr.setVisible.call(this, true, true, d, cb, e);
17823         }else{
17824             if(!v){
17825                 this.hideUnders(true);
17826             }
17827             var cb = c;
17828             if(a){
17829                 cb = function(){
17830                     this.hideAction();
17831                     if(c){
17832                         c();
17833                     }
17834                 }.createDelegate(this);
17835             }
17836             supr.setVisible.call(this, v, a, d, cb, e);
17837             if(v){
17838                 this.sync(true);
17839             }else if(!a){
17840                 this.hideAction();
17841             }
17842         }
17843     },
17844
17845     storeXY : function(xy){
17846         delete this.lastLT;
17847         this.lastXY = xy;
17848     },
17849
17850     storeLeftTop : function(left, top){
17851         delete this.lastXY;
17852         this.lastLT = [left, top];
17853     },
17854
17855     // private
17856     beforeFx : function(){
17857         this.beforeAction();
17858         return Roo.Layer.superclass.beforeFx.apply(this, arguments);
17859     },
17860
17861     // private
17862     afterFx : function(){
17863         Roo.Layer.superclass.afterFx.apply(this, arguments);
17864         this.sync(this.isVisible());
17865     },
17866
17867     // private
17868     beforeAction : function(){
17869         if(!this.updating && this.shadow){
17870             this.shadow.hide();
17871         }
17872     },
17873
17874     // overridden Element method
17875     setLeft : function(left){
17876         this.storeLeftTop(left, this.getTop(true));
17877         supr.setLeft.apply(this, arguments);
17878         this.sync();
17879     },
17880
17881     setTop : function(top){
17882         this.storeLeftTop(this.getLeft(true), top);
17883         supr.setTop.apply(this, arguments);
17884         this.sync();
17885     },
17886
17887     setLeftTop : function(left, top){
17888         this.storeLeftTop(left, top);
17889         supr.setLeftTop.apply(this, arguments);
17890         this.sync();
17891     },
17892
17893     setXY : function(xy, a, d, c, e){
17894         this.fixDisplay();
17895         this.beforeAction();
17896         this.storeXY(xy);
17897         var cb = this.createCB(c);
17898         supr.setXY.call(this, xy, a, d, cb, e);
17899         if(!a){
17900             cb();
17901         }
17902     },
17903
17904     // private
17905     createCB : function(c){
17906         var el = this;
17907         return function(){
17908             el.constrainXY();
17909             el.sync(true);
17910             if(c){
17911                 c();
17912             }
17913         };
17914     },
17915
17916     // overridden Element method
17917     setX : function(x, a, d, c, e){
17918         this.setXY([x, this.getY()], a, d, c, e);
17919     },
17920
17921     // overridden Element method
17922     setY : function(y, a, d, c, e){
17923         this.setXY([this.getX(), y], a, d, c, e);
17924     },
17925
17926     // overridden Element method
17927     setSize : function(w, h, a, d, c, e){
17928         this.beforeAction();
17929         var cb = this.createCB(c);
17930         supr.setSize.call(this, w, h, a, d, cb, e);
17931         if(!a){
17932             cb();
17933         }
17934     },
17935
17936     // overridden Element method
17937     setWidth : function(w, a, d, c, e){
17938         this.beforeAction();
17939         var cb = this.createCB(c);
17940         supr.setWidth.call(this, w, a, d, cb, e);
17941         if(!a){
17942             cb();
17943         }
17944     },
17945
17946     // overridden Element method
17947     setHeight : function(h, a, d, c, e){
17948         this.beforeAction();
17949         var cb = this.createCB(c);
17950         supr.setHeight.call(this, h, a, d, cb, e);
17951         if(!a){
17952             cb();
17953         }
17954     },
17955
17956     // overridden Element method
17957     setBounds : function(x, y, w, h, a, d, c, e){
17958         this.beforeAction();
17959         var cb = this.createCB(c);
17960         if(!a){
17961             this.storeXY([x, y]);
17962             supr.setXY.call(this, [x, y]);
17963             supr.setSize.call(this, w, h, a, d, cb, e);
17964             cb();
17965         }else{
17966             supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
17967         }
17968         return this;
17969     },
17970     
17971     /**
17972      * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
17973      * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
17974      * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
17975      * @param {Number} zindex The new z-index to set
17976      * @return {this} The Layer
17977      */
17978     setZIndex : function(zindex){
17979         this.zindex = zindex;
17980         this.setStyle("z-index", zindex + 2);
17981         if(this.shadow){
17982             this.shadow.setZIndex(zindex + 1);
17983         }
17984         if(this.shim){
17985             this.shim.setStyle("z-index", zindex);
17986         }
17987     }
17988 });
17989 })();/*
17990  * Original code for Roojs - LGPL
17991  * <script type="text/javascript">
17992  */
17993  
17994 /**
17995  * @class Roo.XComponent
17996  * A delayed Element creator...
17997  * Or a way to group chunks of interface together.
17998  * technically this is a wrapper around a tree of Roo elements (which defines a 'module'),
17999  *  used in conjunction with XComponent.build() it will create an instance of each element,
18000  *  then call addxtype() to build the User interface.
18001  * 
18002  * Mypart.xyx = new Roo.XComponent({
18003
18004     parent : 'Mypart.xyz', // empty == document.element.!!
18005     order : '001',
18006     name : 'xxxx'
18007     region : 'xxxx'
18008     disabled : function() {} 
18009      
18010     tree : function() { // return an tree of xtype declared components
18011         var MODULE = this;
18012         return 
18013         {
18014             xtype : 'NestedLayoutPanel',
18015             // technicall
18016         }
18017      ]
18018  *})
18019  *
18020  *
18021  * It can be used to build a big heiracy, with parent etc.
18022  * or you can just use this to render a single compoent to a dom element
18023  * MYPART.render(Roo.Element | String(id) | dom_element )
18024  *
18025  *
18026  * Usage patterns.
18027  *
18028  * Classic Roo
18029  *
18030  * Roo is designed primarily as a single page application, so the UI build for a standard interface will
18031  * expect a single 'TOP' level module normally indicated by the 'parent' of the XComponent definition being defined as false.
18032  *
18033  * Each sub module is expected to have a parent pointing to the class name of it's parent module.
18034  *
18035  * When the top level is false, a 'Roo.BorderLayout' is created and the element is flagged as 'topModule'
18036  * - if mulitple topModules exist, the last one is defined as the top module.
18037  *
18038  * Embeded Roo
18039  * 
18040  * When the top level or multiple modules are to embedded into a existing HTML page,
18041  * the parent element can container '#id' of the element where the module will be drawn.
18042  *
18043  * Bootstrap Roo
18044  *
18045  * Unlike classic Roo, the bootstrap tends not to be used as a single page.
18046  * it relies more on a include mechanism, where sub modules are included into an outer page.
18047  * This is normally managed by the builder tools using Roo.apply( options, Included.Sub.Module )
18048  * 
18049  * Bootstrap Roo Included elements
18050  *
18051  * Our builder application needs the ability to preview these sub compoennts. They will normally have parent=false set,
18052  * hence confusing the component builder as it thinks there are multiple top level elements. 
18053  *
18054  * String Over-ride & Translations
18055  *
18056  * Our builder application writes all the strings as _strings and _named_strings. This is to enable the translation of elements,
18057  * and also the 'overlaying of string values - needed when different versions of the same application with different text content
18058  * are needed. @see Roo.XComponent.overlayString  
18059  * 
18060  * 
18061  * 
18062  * @extends Roo.util.Observable
18063  * @constructor
18064  * @param cfg {Object} configuration of component
18065  * 
18066  */
18067 Roo.XComponent = function(cfg) {
18068     Roo.apply(this, cfg);
18069     this.addEvents({ 
18070         /**
18071              * @event built
18072              * Fires when this the componnt is built
18073              * @param {Roo.XComponent} c the component
18074              */
18075         'built' : true
18076         
18077     });
18078     this.region = this.region || 'center'; // default..
18079     Roo.XComponent.register(this);
18080     this.modules = false;
18081     this.el = false; // where the layout goes..
18082     
18083     
18084 }
18085 Roo.extend(Roo.XComponent, Roo.util.Observable, {
18086     /**
18087      * @property el
18088      * The created element (with Roo.factory())
18089      * @type {Roo.Layout}
18090      */
18091     el  : false,
18092     
18093     /**
18094      * @property el
18095      * for BC  - use el in new code
18096      * @type {Roo.Layout}
18097      */
18098     panel : false,
18099     
18100     /**
18101      * @property layout
18102      * for BC  - use el in new code
18103      * @type {Roo.Layout}
18104      */
18105     layout : false,
18106     
18107      /**
18108      * @cfg {Function|boolean} disabled
18109      * If this module is disabled by some rule, return true from the funtion
18110      */
18111     disabled : false,
18112     
18113     /**
18114      * @cfg {String} parent 
18115      * Name of parent element which it get xtype added to..
18116      */
18117     parent: false,
18118     
18119     /**
18120      * @cfg {String} order
18121      * Used to set the order in which elements are created (usefull for multiple tabs)
18122      */
18123     
18124     order : false,
18125     /**
18126      * @cfg {String} name
18127      * String to display while loading.
18128      */
18129     name : false,
18130     /**
18131      * @cfg {String} region
18132      * Region to render component to (defaults to center)
18133      */
18134     region : 'center',
18135     
18136     /**
18137      * @cfg {Array} items
18138      * A single item array - the first element is the root of the tree..
18139      * It's done this way to stay compatible with the Xtype system...
18140      */
18141     items : false,
18142     
18143     /**
18144      * @property _tree
18145      * The method that retuns the tree of parts that make up this compoennt 
18146      * @type {function}
18147      */
18148     _tree  : false,
18149     
18150      /**
18151      * render
18152      * render element to dom or tree
18153      * @param {Roo.Element|String|DomElement} optional render to if parent is not set.
18154      */
18155     
18156     render : function(el)
18157     {
18158         
18159         el = el || false;
18160         var hp = this.parent ? 1 : 0;
18161         Roo.debug &&  Roo.log(this);
18162         
18163         var tree = this._tree ? this._tree() : this.tree();
18164
18165         
18166         if (!el && typeof(this.parent) == 'string' && this.parent.substring(0,1) == '#') {
18167             // if parent is a '#.....' string, then let's use that..
18168             var ename = this.parent.substr(1);
18169             this.parent = false;
18170             Roo.debug && Roo.log(ename);
18171             switch (ename) {
18172                 case 'bootstrap-body':
18173                     if (typeof(tree.el) != 'undefined' && tree.el == document.body)  {
18174                         // this is the BorderLayout standard?
18175                        this.parent = { el : true };
18176                        break;
18177                     }
18178                     if (["Nest", "Content", "Grid", "Tree"].indexOf(tree.xtype)  > -1)  {
18179                         // need to insert stuff...
18180                         this.parent =  {
18181                              el : new Roo.bootstrap.layout.Border({
18182                                  el : document.body, 
18183                      
18184                                  center: {
18185                                     titlebar: false,
18186                                     autoScroll:false,
18187                                     closeOnTab: true,
18188                                     tabPosition: 'top',
18189                                       //resizeTabs: true,
18190                                     alwaysShowTabs: true,
18191                                     hideTabs: false
18192                                      //minTabWidth: 140
18193                                  }
18194                              })
18195                         
18196                          };
18197                          break;
18198                     }
18199                          
18200                     if (typeof(Roo.bootstrap.Body) != 'undefined' ) {
18201                         this.parent = { el :  new  Roo.bootstrap.Body() };
18202                         Roo.debug && Roo.log("setting el to doc body");
18203                          
18204                     } else {
18205                         throw "Container is bootstrap body, but Roo.bootstrap.Body is not defined";
18206                     }
18207                     break;
18208                 case 'bootstrap':
18209                     this.parent = { el : true};
18210                     // fall through
18211                 default:
18212                     el = Roo.get(ename);
18213                     if (typeof(Roo.bootstrap) != 'undefined' && tree['|xns'] == 'Roo.bootstrap') {
18214                         this.parent = { el : true};
18215                     }
18216                     
18217                     break;
18218             }
18219                 
18220             
18221             if (!el && !this.parent) {
18222                 Roo.debug && Roo.log("Warning - element can not be found :#" + ename );
18223                 return;
18224             }
18225         }
18226         
18227         Roo.debug && Roo.log("EL:");
18228         Roo.debug && Roo.log(el);
18229         Roo.debug && Roo.log("this.parent.el:");
18230         Roo.debug && Roo.log(this.parent.el);
18231         
18232
18233         // altertive root elements ??? - we need a better way to indicate these.
18234         var is_alt = Roo.XComponent.is_alt ||
18235                     (typeof(tree.el) != 'undefined' && tree.el == document.body) ||
18236                     (typeof(Roo.bootstrap) != 'undefined' && tree.xns == Roo.bootstrap) ||
18237                     (typeof(Roo.mailer) != 'undefined' && tree.xns == Roo.mailer) ;
18238         
18239         
18240         
18241         if (!this.parent && is_alt) {
18242             //el = Roo.get(document.body);
18243             this.parent = { el : true };
18244         }
18245             
18246             
18247         
18248         if (!this.parent) {
18249             
18250             Roo.debug && Roo.log("no parent - creating one");
18251             
18252             el = el ? Roo.get(el) : false;      
18253             
18254             if (typeof(Roo.BorderLayout) == 'undefined' ) {
18255                 
18256                 this.parent =  {
18257                     el : new Roo.bootstrap.layout.Border({
18258                         el: el || document.body,
18259                     
18260                         center: {
18261                             titlebar: false,
18262                             autoScroll:false,
18263                             closeOnTab: true,
18264                             tabPosition: 'top',
18265                              //resizeTabs: true,
18266                             alwaysShowTabs: false,
18267                             hideTabs: true,
18268                             minTabWidth: 140,
18269                             overflow: 'visible'
18270                          }
18271                      })
18272                 };
18273             } else {
18274             
18275                 // it's a top level one..
18276                 this.parent =  {
18277                     el : new Roo.BorderLayout(el || document.body, {
18278                         center: {
18279                             titlebar: false,
18280                             autoScroll:false,
18281                             closeOnTab: true,
18282                             tabPosition: 'top',
18283                              //resizeTabs: true,
18284                             alwaysShowTabs: el && hp? false :  true,
18285                             hideTabs: el || !hp ? true :  false,
18286                             minTabWidth: 140
18287                          }
18288                     })
18289                 };
18290             }
18291         }
18292         
18293         if (!this.parent.el) {
18294                 // probably an old style ctor, which has been disabled.
18295                 return;
18296
18297         }
18298                 // The 'tree' method is  '_tree now' 
18299             
18300         tree.region = tree.region || this.region;
18301         var is_body = false;
18302         if (this.parent.el === true) {
18303             // bootstrap... - body..
18304             if (el) {
18305                 tree.el = el;
18306             }
18307             this.parent.el = Roo.factory(tree);
18308             is_body = true;
18309         }
18310         
18311         this.el = this.parent.el.addxtype(tree, undefined, is_body);
18312         this.fireEvent('built', this);
18313         
18314         this.panel = this.el;
18315         this.layout = this.panel.layout;
18316         this.parentLayout = this.parent.layout  || false;  
18317          
18318     }
18319     
18320 });
18321
18322 Roo.apply(Roo.XComponent, {
18323     /**
18324      * @property  hideProgress
18325      * true to disable the building progress bar.. usefull on single page renders.
18326      * @type Boolean
18327      */
18328     hideProgress : false,
18329     /**
18330      * @property  buildCompleted
18331      * True when the builder has completed building the interface.
18332      * @type Boolean
18333      */
18334     buildCompleted : false,
18335      
18336     /**
18337      * @property  topModule
18338      * the upper most module - uses document.element as it's constructor.
18339      * @type Object
18340      */
18341      
18342     topModule  : false,
18343       
18344     /**
18345      * @property  modules
18346      * array of modules to be created by registration system.
18347      * @type {Array} of Roo.XComponent
18348      */
18349     
18350     modules : [],
18351     /**
18352      * @property  elmodules
18353      * array of modules to be created by which use #ID 
18354      * @type {Array} of Roo.XComponent
18355      */
18356      
18357     elmodules : [],
18358
18359      /**
18360      * @property  is_alt
18361      * Is an alternative Root - normally used by bootstrap or other systems,
18362      *    where the top element in the tree can wrap 'body' 
18363      * @type {boolean}  (default false)
18364      */
18365      
18366     is_alt : false,
18367     /**
18368      * @property  build_from_html
18369      * Build elements from html - used by bootstrap HTML stuff 
18370      *    - this is cleared after build is completed
18371      * @type {boolean}    (default false)
18372      */
18373      
18374     build_from_html : false,
18375     /**
18376      * Register components to be built later.
18377      *
18378      * This solves the following issues
18379      * - Building is not done on page load, but after an authentication process has occured.
18380      * - Interface elements are registered on page load
18381      * - Parent Interface elements may not be loaded before child, so this handles that..
18382      * 
18383      *
18384      * example:
18385      * 
18386      * MyApp.register({
18387           order : '000001',
18388           module : 'Pman.Tab.projectMgr',
18389           region : 'center',
18390           parent : 'Pman.layout',
18391           disabled : false,  // or use a function..
18392         })
18393      
18394      * * @param {Object} details about module
18395      */
18396     register : function(obj) {
18397                 
18398         Roo.XComponent.event.fireEvent('register', obj);
18399         switch(typeof(obj.disabled) ) {
18400                 
18401             case 'undefined':
18402                 break;
18403             
18404             case 'function':
18405                 if ( obj.disabled() ) {
18406                         return;
18407                 }
18408                 break;
18409             
18410             default:
18411                 if (obj.disabled || obj.region == '#disabled') {
18412                         return;
18413                 }
18414                 break;
18415         }
18416                 
18417         this.modules.push(obj);
18418          
18419     },
18420     /**
18421      * convert a string to an object..
18422      * eg. 'AAA.BBB' -> finds AAA.BBB
18423
18424      */
18425     
18426     toObject : function(str)
18427     {
18428         if (!str || typeof(str) == 'object') {
18429             return str;
18430         }
18431         if (str.substring(0,1) == '#') {
18432             return str;
18433         }
18434
18435         var ar = str.split('.');
18436         var rt, o;
18437         rt = ar.shift();
18438             /** eval:var:o */
18439         try {
18440             eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
18441         } catch (e) {
18442             throw "Module not found : " + str;
18443         }
18444         
18445         if (o === false) {
18446             throw "Module not found : " + str;
18447         }
18448         Roo.each(ar, function(e) {
18449             if (typeof(o[e]) == 'undefined') {
18450                 throw "Module not found : " + str;
18451             }
18452             o = o[e];
18453         });
18454         
18455         return o;
18456         
18457     },
18458     
18459     
18460     /**
18461      * move modules into their correct place in the tree..
18462      * 
18463      */
18464     preBuild : function ()
18465     {
18466         var _t = this;
18467         Roo.each(this.modules , function (obj)
18468         {
18469             Roo.XComponent.event.fireEvent('beforebuild', obj);
18470             
18471             var opar = obj.parent;
18472             try { 
18473                 obj.parent = this.toObject(opar);
18474             } catch(e) {
18475                 Roo.debug && Roo.log("parent:toObject failed: " + e.toString());
18476                 return;
18477             }
18478             
18479             if (!obj.parent) {
18480                 Roo.debug && Roo.log("GOT top level module");
18481                 Roo.debug && Roo.log(obj);
18482                 obj.modules = new Roo.util.MixedCollection(false, 
18483                     function(o) { return o.order + '' }
18484                 );
18485                 this.topModule = obj;
18486                 return;
18487             }
18488                         // parent is a string (usually a dom element name..)
18489             if (typeof(obj.parent) == 'string') {
18490                 this.elmodules.push(obj);
18491                 return;
18492             }
18493             if (obj.parent.constructor != Roo.XComponent) {
18494                 Roo.debug && Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
18495             }
18496             if (!obj.parent.modules) {
18497                 obj.parent.modules = new Roo.util.MixedCollection(false, 
18498                     function(o) { return o.order + '' }
18499                 );
18500             }
18501             if (obj.parent.disabled) {
18502                 obj.disabled = true;
18503             }
18504             obj.parent.modules.add(obj);
18505         }, this);
18506     },
18507     
18508      /**
18509      * make a list of modules to build.
18510      * @return {Array} list of modules. 
18511      */ 
18512     
18513     buildOrder : function()
18514     {
18515         var _this = this;
18516         var cmp = function(a,b) {   
18517             return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
18518         };
18519         if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
18520             throw "No top level modules to build";
18521         }
18522         
18523         // make a flat list in order of modules to build.
18524         var mods = this.topModule ? [ this.topModule ] : [];
18525                 
18526         
18527         // elmodules (is a list of DOM based modules )
18528         Roo.each(this.elmodules, function(e) {
18529             mods.push(e);
18530             if (!this.topModule &&
18531                 typeof(e.parent) == 'string' &&
18532                 e.parent.substring(0,1) == '#' &&
18533                 Roo.get(e.parent.substr(1))
18534                ) {
18535                 
18536                 _this.topModule = e;
18537             }
18538             
18539         });
18540
18541         
18542         // add modules to their parents..
18543         var addMod = function(m) {
18544             Roo.debug && Roo.log("build Order: add: " + m.name);
18545                 
18546             mods.push(m);
18547             if (m.modules && !m.disabled) {
18548                 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
18549                 m.modules.keySort('ASC',  cmp );
18550                 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
18551     
18552                 m.modules.each(addMod);
18553             } else {
18554                 Roo.debug && Roo.log("build Order: no child modules");
18555             }
18556             // not sure if this is used any more..
18557             if (m.finalize) {
18558                 m.finalize.name = m.name + " (clean up) ";
18559                 mods.push(m.finalize);
18560             }
18561             
18562         }
18563         if (this.topModule && this.topModule.modules) { 
18564             this.topModule.modules.keySort('ASC',  cmp );
18565             this.topModule.modules.each(addMod);
18566         } 
18567         return mods;
18568     },
18569     
18570      /**
18571      * Build the registered modules.
18572      * @param {Object} parent element.
18573      * @param {Function} optional method to call after module has been added.
18574      * 
18575      */ 
18576    
18577     build : function(opts) 
18578     {
18579         
18580         if (typeof(opts) != 'undefined') {
18581             Roo.apply(this,opts);
18582         }
18583         
18584         this.preBuild();
18585         var mods = this.buildOrder();
18586       
18587         //this.allmods = mods;
18588         //Roo.debug && Roo.log(mods);
18589         //return;
18590         if (!mods.length) { // should not happen
18591             throw "NO modules!!!";
18592         }
18593         
18594         
18595         var msg = "Building Interface...";
18596         // flash it up as modal - so we store the mask!?
18597         if (!this.hideProgress && Roo.MessageBox) {
18598             Roo.MessageBox.show({ title: 'loading' });
18599             Roo.MessageBox.show({
18600                title: "Please wait...",
18601                msg: msg,
18602                width:450,
18603                progress:true,
18604                buttons : false,
18605                closable:false,
18606                modal: false
18607               
18608             });
18609         }
18610         var total = mods.length;
18611         
18612         var _this = this;
18613         var progressRun = function() {
18614             if (!mods.length) {
18615                 Roo.debug && Roo.log('hide?');
18616                 if (!this.hideProgress && Roo.MessageBox) {
18617                     Roo.MessageBox.hide();
18618                 }
18619                 Roo.XComponent.build_from_html = false; // reset, so dialogs will be build from javascript
18620                 
18621                 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
18622                 
18623                 // THE END...
18624                 return false;   
18625             }
18626             
18627             var m = mods.shift();
18628             
18629             
18630             Roo.debug && Roo.log(m);
18631             // not sure if this is supported any more.. - modules that are are just function
18632             if (typeof(m) == 'function') { 
18633                 m.call(this);
18634                 return progressRun.defer(10, _this);
18635             } 
18636             
18637             
18638             msg = "Building Interface " + (total  - mods.length) + 
18639                     " of " + total + 
18640                     (m.name ? (' - ' + m.name) : '');
18641                         Roo.debug && Roo.log(msg);
18642             if (!_this.hideProgress &&  Roo.MessageBox) { 
18643                 Roo.MessageBox.updateProgress(  (total  - mods.length)/total, msg  );
18644             }
18645             
18646          
18647             // is the module disabled?
18648             var disabled = (typeof(m.disabled) == 'function') ?
18649                 m.disabled.call(m.module.disabled) : m.disabled;    
18650             
18651             
18652             if (disabled) {
18653                 return progressRun(); // we do not update the display!
18654             }
18655             
18656             // now build 
18657             
18658                         
18659                         
18660             m.render();
18661             // it's 10 on top level, and 1 on others??? why...
18662             return progressRun.defer(10, _this);
18663              
18664         }
18665         progressRun.defer(1, _this);
18666      
18667         
18668         
18669     },
18670     /**
18671      * Overlay a set of modified strings onto a component
18672      * This is dependant on our builder exporting the strings and 'named strings' elements.
18673      * 
18674      * @param {Object} element to overlay on - eg. Pman.Dialog.Login
18675      * @param {Object} associative array of 'named' string and it's new value.
18676      * 
18677      */
18678         overlayStrings : function( component, strings )
18679     {
18680         if (typeof(component['_named_strings']) == 'undefined') {
18681             throw "ERROR: component does not have _named_strings";
18682         }
18683         for ( var k in strings ) {
18684             var md = typeof(component['_named_strings'][k]) == 'undefined' ? false : component['_named_strings'][k];
18685             if (md !== false) {
18686                 component['_strings'][md] = strings[k];
18687             } else {
18688                 Roo.log('could not find named string: ' + k + ' in');
18689                 Roo.log(component);
18690             }
18691             
18692         }
18693         
18694     },
18695     
18696         
18697         /**
18698          * Event Object.
18699          *
18700          *
18701          */
18702         event: false, 
18703     /**
18704          * wrapper for event.on - aliased later..  
18705          * Typically use to register a event handler for register:
18706          *
18707          * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
18708          *
18709          */
18710     on : false
18711    
18712     
18713     
18714 });
18715
18716 Roo.XComponent.event = new Roo.util.Observable({
18717                 events : { 
18718                         /**
18719                          * @event register
18720                          * Fires when an Component is registered,
18721                          * set the disable property on the Component to stop registration.
18722                          * @param {Roo.XComponent} c the component being registerd.
18723                          * 
18724                          */
18725                         'register' : true,
18726             /**
18727                          * @event beforebuild
18728                          * Fires before each Component is built
18729                          * can be used to apply permissions.
18730                          * @param {Roo.XComponent} c the component being registerd.
18731                          * 
18732                          */
18733                         'beforebuild' : true,
18734                         /**
18735                          * @event buildcomplete
18736                          * Fires on the top level element when all elements have been built
18737                          * @param {Roo.XComponent} the top level component.
18738                          */
18739                         'buildcomplete' : true
18740                         
18741                 }
18742 });
18743
18744 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event); 
18745  //
18746  /**
18747  * marked - a markdown parser
18748  * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
18749  * https://github.com/chjj/marked
18750  */
18751
18752
18753 /**
18754  *
18755  * Roo.Markdown - is a very crude wrapper around marked..
18756  *
18757  * usage:
18758  * 
18759  * alert( Roo.Markdown.toHtml("Markdown *rocks*.") );
18760  * 
18761  * Note: move the sample code to the bottom of this
18762  * file before uncommenting it.
18763  *
18764  */
18765
18766 Roo.Markdown = {};
18767 Roo.Markdown.toHtml = function(text) {
18768     
18769     var c = new Roo.Markdown.marked.setOptions({
18770             renderer: new Roo.Markdown.marked.Renderer(),
18771             gfm: true,
18772             tables: true,
18773             breaks: false,
18774             pedantic: false,
18775             sanitize: false,
18776             smartLists: true,
18777             smartypants: false
18778           });
18779     // A FEW HACKS!!?
18780     
18781     text = text.replace(/\\\n/g,' ');
18782     return Roo.Markdown.marked(text);
18783 };
18784 //
18785 // converter
18786 //
18787 // Wraps all "globals" so that the only thing
18788 // exposed is makeHtml().
18789 //
18790 (function() {
18791     
18792      /**
18793          * eval:var:escape
18794          * eval:var:unescape
18795          * eval:var:replace
18796          */
18797       
18798     /**
18799      * Helpers
18800      */
18801     
18802     var escape = function (html, encode) {
18803       return html
18804         .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
18805         .replace(/</g, '&lt;')
18806         .replace(/>/g, '&gt;')
18807         .replace(/"/g, '&quot;')
18808         .replace(/'/g, '&#39;');
18809     }
18810     
18811     var unescape = function (html) {
18812         // explicitly match decimal, hex, and named HTML entities 
18813       return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
18814         n = n.toLowerCase();
18815         if (n === 'colon') { return ':'; }
18816         if (n.charAt(0) === '#') {
18817           return n.charAt(1) === 'x'
18818             ? String.fromCharCode(parseInt(n.substring(2), 16))
18819             : String.fromCharCode(+n.substring(1));
18820         }
18821         return '';
18822       });
18823     }
18824     
18825     var replace = function (regex, opt) {
18826       regex = regex.source;
18827       opt = opt || '';
18828       return function self(name, val) {
18829         if (!name) { return new RegExp(regex, opt); }
18830         val = val.source || val;
18831         val = val.replace(/(^|[^\[])\^/g, '$1');
18832         regex = regex.replace(name, val);
18833         return self;
18834       };
18835     }
18836
18837
18838          /**
18839          * eval:var:noop
18840     */
18841     var noop = function () {}
18842     noop.exec = noop;
18843     
18844          /**
18845          * eval:var:merge
18846     */
18847     var merge = function (obj) {
18848       var i = 1
18849         , target
18850         , key;
18851     
18852       for (; i < arguments.length; i++) {
18853         target = arguments[i];
18854         for (key in target) {
18855           if (Object.prototype.hasOwnProperty.call(target, key)) {
18856             obj[key] = target[key];
18857           }
18858         }
18859       }
18860     
18861       return obj;
18862     }
18863     
18864     
18865     /**
18866      * Block-Level Grammar
18867      */
18868     
18869     
18870     
18871     
18872     var block = {
18873       newline: /^\n+/,
18874       code: /^( {4}[^\n]+\n*)+/,
18875       fences: noop,
18876       hr: /^( *[-*_]){3,} *(?:\n+|$)/,
18877       heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
18878       nptable: noop,
18879       lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
18880       blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
18881       list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
18882       html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
18883       def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
18884       table: noop,
18885       paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
18886       text: /^[^\n]+/
18887     };
18888     
18889     block.bullet = /(?:[*+-]|\d+\.)/;
18890     block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
18891     block.item = replace(block.item, 'gm')
18892       (/bull/g, block.bullet)
18893       ();
18894     
18895     block.list = replace(block.list)
18896       (/bull/g, block.bullet)
18897       ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
18898       ('def', '\\n+(?=' + block.def.source + ')')
18899       ();
18900     
18901     block.blockquote = replace(block.blockquote)
18902       ('def', block.def)
18903       ();
18904     
18905     block._tag = '(?!(?:'
18906       + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
18907       + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
18908       + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
18909     
18910     block.html = replace(block.html)
18911       ('comment', /<!--[\s\S]*?-->/)
18912       ('closed', /<(tag)[\s\S]+?<\/\1>/)
18913       ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
18914       (/tag/g, block._tag)
18915       ();
18916     
18917     block.paragraph = replace(block.paragraph)
18918       ('hr', block.hr)
18919       ('heading', block.heading)
18920       ('lheading', block.lheading)
18921       ('blockquote', block.blockquote)
18922       ('tag', '<' + block._tag)
18923       ('def', block.def)
18924       ();
18925     
18926     /**
18927      * Normal Block Grammar
18928      */
18929     
18930     block.normal = merge({}, block);
18931     
18932     /**
18933      * GFM Block Grammar
18934      */
18935     
18936     block.gfm = merge({}, block.normal, {
18937       fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
18938       paragraph: /^/,
18939       heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
18940     });
18941     
18942     block.gfm.paragraph = replace(block.paragraph)
18943       ('(?!', '(?!'
18944         + block.gfm.fences.source.replace('\\1', '\\2') + '|'
18945         + block.list.source.replace('\\1', '\\3') + '|')
18946       ();
18947     
18948     /**
18949      * GFM + Tables Block Grammar
18950      */
18951     
18952     block.tables = merge({}, block.gfm, {
18953       nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
18954       table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
18955     });
18956     
18957     /**
18958      * Block Lexer
18959      */
18960     
18961     var Lexer = function (options) {
18962       this.tokens = [];
18963       this.tokens.links = {};
18964       this.options = options || marked.defaults;
18965       this.rules = block.normal;
18966     
18967       if (this.options.gfm) {
18968         if (this.options.tables) {
18969           this.rules = block.tables;
18970         } else {
18971           this.rules = block.gfm;
18972         }
18973       }
18974     }
18975     
18976     /**
18977      * Expose Block Rules
18978      */
18979     
18980     Lexer.rules = block;
18981     
18982     /**
18983      * Static Lex Method
18984      */
18985     
18986     Lexer.lex = function(src, options) {
18987       var lexer = new Lexer(options);
18988       return lexer.lex(src);
18989     };
18990     
18991     /**
18992      * Preprocessing
18993      */
18994     
18995     Lexer.prototype.lex = function(src) {
18996       src = src
18997         .replace(/\r\n|\r/g, '\n')
18998         .replace(/\t/g, '    ')
18999         .replace(/\u00a0/g, ' ')
19000         .replace(/\u2424/g, '\n');
19001     
19002       return this.token(src, true);
19003     };
19004     
19005     /**
19006      * Lexing
19007      */
19008     
19009     Lexer.prototype.token = function(src, top, bq) {
19010       var src = src.replace(/^ +$/gm, '')
19011         , next
19012         , loose
19013         , cap
19014         , bull
19015         , b
19016         , item
19017         , space
19018         , i
19019         , l;
19020     
19021       while (src) {
19022         // newline
19023         if (cap = this.rules.newline.exec(src)) {
19024           src = src.substring(cap[0].length);
19025           if (cap[0].length > 1) {
19026             this.tokens.push({
19027               type: 'space'
19028             });
19029           }
19030         }
19031     
19032         // code
19033         if (cap = this.rules.code.exec(src)) {
19034           src = src.substring(cap[0].length);
19035           cap = cap[0].replace(/^ {4}/gm, '');
19036           this.tokens.push({
19037             type: 'code',
19038             text: !this.options.pedantic
19039               ? cap.replace(/\n+$/, '')
19040               : cap
19041           });
19042           continue;
19043         }
19044     
19045         // fences (gfm)
19046         if (cap = this.rules.fences.exec(src)) {
19047           src = src.substring(cap[0].length);
19048           this.tokens.push({
19049             type: 'code',
19050             lang: cap[2],
19051             text: cap[3] || ''
19052           });
19053           continue;
19054         }
19055     
19056         // heading
19057         if (cap = this.rules.heading.exec(src)) {
19058           src = src.substring(cap[0].length);
19059           this.tokens.push({
19060             type: 'heading',
19061             depth: cap[1].length,
19062             text: cap[2]
19063           });
19064           continue;
19065         }
19066     
19067         // table no leading pipe (gfm)
19068         if (top && (cap = this.rules.nptable.exec(src))) {
19069           src = src.substring(cap[0].length);
19070     
19071           item = {
19072             type: 'table',
19073             header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
19074             align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
19075             cells: cap[3].replace(/\n$/, '').split('\n')
19076           };
19077     
19078           for (i = 0; i < item.align.length; i++) {
19079             if (/^ *-+: *$/.test(item.align[i])) {
19080               item.align[i] = 'right';
19081             } else if (/^ *:-+: *$/.test(item.align[i])) {
19082               item.align[i] = 'center';
19083             } else if (/^ *:-+ *$/.test(item.align[i])) {
19084               item.align[i] = 'left';
19085             } else {
19086               item.align[i] = null;
19087             }
19088           }
19089     
19090           for (i = 0; i < item.cells.length; i++) {
19091             item.cells[i] = item.cells[i].split(/ *\| */);
19092           }
19093     
19094           this.tokens.push(item);
19095     
19096           continue;
19097         }
19098     
19099         // lheading
19100         if (cap = this.rules.lheading.exec(src)) {
19101           src = src.substring(cap[0].length);
19102           this.tokens.push({
19103             type: 'heading',
19104             depth: cap[2] === '=' ? 1 : 2,
19105             text: cap[1]
19106           });
19107           continue;
19108         }
19109     
19110         // hr
19111         if (cap = this.rules.hr.exec(src)) {
19112           src = src.substring(cap[0].length);
19113           this.tokens.push({
19114             type: 'hr'
19115           });
19116           continue;
19117         }
19118     
19119         // blockquote
19120         if (cap = this.rules.blockquote.exec(src)) {
19121           src = src.substring(cap[0].length);
19122     
19123           this.tokens.push({
19124             type: 'blockquote_start'
19125           });
19126     
19127           cap = cap[0].replace(/^ *> ?/gm, '');
19128     
19129           // Pass `top` to keep the current
19130           // "toplevel" state. This is exactly
19131           // how markdown.pl works.
19132           this.token(cap, top, true);
19133     
19134           this.tokens.push({
19135             type: 'blockquote_end'
19136           });
19137     
19138           continue;
19139         }
19140     
19141         // list
19142         if (cap = this.rules.list.exec(src)) {
19143           src = src.substring(cap[0].length);
19144           bull = cap[2];
19145     
19146           this.tokens.push({
19147             type: 'list_start',
19148             ordered: bull.length > 1
19149           });
19150     
19151           // Get each top-level item.
19152           cap = cap[0].match(this.rules.item);
19153     
19154           next = false;
19155           l = cap.length;
19156           i = 0;
19157     
19158           for (; i < l; i++) {
19159             item = cap[i];
19160     
19161             // Remove the list item's bullet
19162             // so it is seen as the next token.
19163             space = item.length;
19164             item = item.replace(/^ *([*+-]|\d+\.) +/, '');
19165     
19166             // Outdent whatever the
19167             // list item contains. Hacky.
19168             if (~item.indexOf('\n ')) {
19169               space -= item.length;
19170               item = !this.options.pedantic
19171                 ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
19172                 : item.replace(/^ {1,4}/gm, '');
19173             }
19174     
19175             // Determine whether the next list item belongs here.
19176             // Backpedal if it does not belong in this list.
19177             if (this.options.smartLists && i !== l - 1) {
19178               b = block.bullet.exec(cap[i + 1])[0];
19179               if (bull !== b && !(bull.length > 1 && b.length > 1)) {
19180                 src = cap.slice(i + 1).join('\n') + src;
19181                 i = l - 1;
19182               }
19183             }
19184     
19185             // Determine whether item is loose or not.
19186             // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
19187             // for discount behavior.
19188             loose = next || /\n\n(?!\s*$)/.test(item);
19189             if (i !== l - 1) {
19190               next = item.charAt(item.length - 1) === '\n';
19191               if (!loose) { loose = next; }
19192             }
19193     
19194             this.tokens.push({
19195               type: loose
19196                 ? 'loose_item_start'
19197                 : 'list_item_start'
19198             });
19199     
19200             // Recurse.
19201             this.token(item, false, bq);
19202     
19203             this.tokens.push({
19204               type: 'list_item_end'
19205             });
19206           }
19207     
19208           this.tokens.push({
19209             type: 'list_end'
19210           });
19211     
19212           continue;
19213         }
19214     
19215         // html
19216         if (cap = this.rules.html.exec(src)) {
19217           src = src.substring(cap[0].length);
19218           this.tokens.push({
19219             type: this.options.sanitize
19220               ? 'paragraph'
19221               : 'html',
19222             pre: !this.options.sanitizer
19223               && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
19224             text: cap[0]
19225           });
19226           continue;
19227         }
19228     
19229         // def
19230         if ((!bq && top) && (cap = this.rules.def.exec(src))) {
19231           src = src.substring(cap[0].length);
19232           this.tokens.links[cap[1].toLowerCase()] = {
19233             href: cap[2],
19234             title: cap[3]
19235           };
19236           continue;
19237         }
19238     
19239         // table (gfm)
19240         if (top && (cap = this.rules.table.exec(src))) {
19241           src = src.substring(cap[0].length);
19242     
19243           item = {
19244             type: 'table',
19245             header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
19246             align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
19247             cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
19248           };
19249     
19250           for (i = 0; i < item.align.length; i++) {
19251             if (/^ *-+: *$/.test(item.align[i])) {
19252               item.align[i] = 'right';
19253             } else if (/^ *:-+: *$/.test(item.align[i])) {
19254               item.align[i] = 'center';
19255             } else if (/^ *:-+ *$/.test(item.align[i])) {
19256               item.align[i] = 'left';
19257             } else {
19258               item.align[i] = null;
19259             }
19260           }
19261     
19262           for (i = 0; i < item.cells.length; i++) {
19263             item.cells[i] = item.cells[i]
19264               .replace(/^ *\| *| *\| *$/g, '')
19265               .split(/ *\| */);
19266           }
19267     
19268           this.tokens.push(item);
19269     
19270           continue;
19271         }
19272     
19273         // top-level paragraph
19274         if (top && (cap = this.rules.paragraph.exec(src))) {
19275           src = src.substring(cap[0].length);
19276           this.tokens.push({
19277             type: 'paragraph',
19278             text: cap[1].charAt(cap[1].length - 1) === '\n'
19279               ? cap[1].slice(0, -1)
19280               : cap[1]
19281           });
19282           continue;
19283         }
19284     
19285         // text
19286         if (cap = this.rules.text.exec(src)) {
19287           // Top-level should never reach here.
19288           src = src.substring(cap[0].length);
19289           this.tokens.push({
19290             type: 'text',
19291             text: cap[0]
19292           });
19293           continue;
19294         }
19295     
19296         if (src) {
19297           throw new
19298             Error('Infinite loop on byte: ' + src.charCodeAt(0));
19299         }
19300       }
19301     
19302       return this.tokens;
19303     };
19304     
19305     /**
19306      * Inline-Level Grammar
19307      */
19308     
19309     var inline = {
19310       escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
19311       autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
19312       url: noop,
19313       tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
19314       link: /^!?\[(inside)\]\(href\)/,
19315       reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
19316       nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
19317       strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
19318       em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
19319       code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
19320       br: /^ {2,}\n(?!\s*$)/,
19321       del: noop,
19322       text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
19323     };
19324     
19325     inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
19326     inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
19327     
19328     inline.link = replace(inline.link)
19329       ('inside', inline._inside)
19330       ('href', inline._href)
19331       ();
19332     
19333     inline.reflink = replace(inline.reflink)
19334       ('inside', inline._inside)
19335       ();
19336     
19337     /**
19338      * Normal Inline Grammar
19339      */
19340     
19341     inline.normal = merge({}, inline);
19342     
19343     /**
19344      * Pedantic Inline Grammar
19345      */
19346     
19347     inline.pedantic = merge({}, inline.normal, {
19348       strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
19349       em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
19350     });
19351     
19352     /**
19353      * GFM Inline Grammar
19354      */
19355     
19356     inline.gfm = merge({}, inline.normal, {
19357       escape: replace(inline.escape)('])', '~|])')(),
19358       url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
19359       del: /^~~(?=\S)([\s\S]*?\S)~~/,
19360       text: replace(inline.text)
19361         (']|', '~]|')
19362         ('|', '|https?://|')
19363         ()
19364     });
19365     
19366     /**
19367      * GFM + Line Breaks Inline Grammar
19368      */
19369     
19370     inline.breaks = merge({}, inline.gfm, {
19371       br: replace(inline.br)('{2,}', '*')(),
19372       text: replace(inline.gfm.text)('{2,}', '*')()
19373     });
19374     
19375     /**
19376      * Inline Lexer & Compiler
19377      */
19378     
19379     var InlineLexer  = function (links, options) {
19380       this.options = options || marked.defaults;
19381       this.links = links;
19382       this.rules = inline.normal;
19383       this.renderer = this.options.renderer || new Renderer;
19384       this.renderer.options = this.options;
19385     
19386       if (!this.links) {
19387         throw new
19388           Error('Tokens array requires a `links` property.');
19389       }
19390     
19391       if (this.options.gfm) {
19392         if (this.options.breaks) {
19393           this.rules = inline.breaks;
19394         } else {
19395           this.rules = inline.gfm;
19396         }
19397       } else if (this.options.pedantic) {
19398         this.rules = inline.pedantic;
19399       }
19400     }
19401     
19402     /**
19403      * Expose Inline Rules
19404      */
19405     
19406     InlineLexer.rules = inline;
19407     
19408     /**
19409      * Static Lexing/Compiling Method
19410      */
19411     
19412     InlineLexer.output = function(src, links, options) {
19413       var inline = new InlineLexer(links, options);
19414       return inline.output(src);
19415     };
19416     
19417     /**
19418      * Lexing/Compiling
19419      */
19420     
19421     InlineLexer.prototype.output = function(src) {
19422       var out = ''
19423         , link
19424         , text
19425         , href
19426         , cap;
19427     
19428       while (src) {
19429         // escape
19430         if (cap = this.rules.escape.exec(src)) {
19431           src = src.substring(cap[0].length);
19432           out += cap[1];
19433           continue;
19434         }
19435     
19436         // autolink
19437         if (cap = this.rules.autolink.exec(src)) {
19438           src = src.substring(cap[0].length);
19439           if (cap[2] === '@') {
19440             text = cap[1].charAt(6) === ':'
19441               ? this.mangle(cap[1].substring(7))
19442               : this.mangle(cap[1]);
19443             href = this.mangle('mailto:') + text;
19444           } else {
19445             text = escape(cap[1]);
19446             href = text;
19447           }
19448           out += this.renderer.link(href, null, text);
19449           continue;
19450         }
19451     
19452         // url (gfm)
19453         if (!this.inLink && (cap = this.rules.url.exec(src))) {
19454           src = src.substring(cap[0].length);
19455           text = escape(cap[1]);
19456           href = text;
19457           out += this.renderer.link(href, null, text);
19458           continue;
19459         }
19460     
19461         // tag
19462         if (cap = this.rules.tag.exec(src)) {
19463           if (!this.inLink && /^<a /i.test(cap[0])) {
19464             this.inLink = true;
19465           } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
19466             this.inLink = false;
19467           }
19468           src = src.substring(cap[0].length);
19469           out += this.options.sanitize
19470             ? this.options.sanitizer
19471               ? this.options.sanitizer(cap[0])
19472               : escape(cap[0])
19473             : cap[0];
19474           continue;
19475         }
19476     
19477         // link
19478         if (cap = this.rules.link.exec(src)) {
19479           src = src.substring(cap[0].length);
19480           this.inLink = true;
19481           out += this.outputLink(cap, {
19482             href: cap[2],
19483             title: cap[3]
19484           });
19485           this.inLink = false;
19486           continue;
19487         }
19488     
19489         // reflink, nolink
19490         if ((cap = this.rules.reflink.exec(src))
19491             || (cap = this.rules.nolink.exec(src))) {
19492           src = src.substring(cap[0].length);
19493           link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
19494           link = this.links[link.toLowerCase()];
19495           if (!link || !link.href) {
19496             out += cap[0].charAt(0);
19497             src = cap[0].substring(1) + src;
19498             continue;
19499           }
19500           this.inLink = true;
19501           out += this.outputLink(cap, link);
19502           this.inLink = false;
19503           continue;
19504         }
19505     
19506         // strong
19507         if (cap = this.rules.strong.exec(src)) {
19508           src = src.substring(cap[0].length);
19509           out += this.renderer.strong(this.output(cap[2] || cap[1]));
19510           continue;
19511         }
19512     
19513         // em
19514         if (cap = this.rules.em.exec(src)) {
19515           src = src.substring(cap[0].length);
19516           out += this.renderer.em(this.output(cap[2] || cap[1]));
19517           continue;
19518         }
19519     
19520         // code
19521         if (cap = this.rules.code.exec(src)) {
19522           src = src.substring(cap[0].length);
19523           out += this.renderer.codespan(escape(cap[2], true));
19524           continue;
19525         }
19526     
19527         // br
19528         if (cap = this.rules.br.exec(src)) {
19529           src = src.substring(cap[0].length);
19530           out += this.renderer.br();
19531           continue;
19532         }
19533     
19534         // del (gfm)
19535         if (cap = this.rules.del.exec(src)) {
19536           src = src.substring(cap[0].length);
19537           out += this.renderer.del(this.output(cap[1]));
19538           continue;
19539         }
19540     
19541         // text
19542         if (cap = this.rules.text.exec(src)) {
19543           src = src.substring(cap[0].length);
19544           out += this.renderer.text(escape(this.smartypants(cap[0])));
19545           continue;
19546         }
19547     
19548         if (src) {
19549           throw new
19550             Error('Infinite loop on byte: ' + src.charCodeAt(0));
19551         }
19552       }
19553     
19554       return out;
19555     };
19556     
19557     /**
19558      * Compile Link
19559      */
19560     
19561     InlineLexer.prototype.outputLink = function(cap, link) {
19562       var href = escape(link.href)
19563         , title = link.title ? escape(link.title) : null;
19564     
19565       return cap[0].charAt(0) !== '!'
19566         ? this.renderer.link(href, title, this.output(cap[1]))
19567         : this.renderer.image(href, title, escape(cap[1]));
19568     };
19569     
19570     /**
19571      * Smartypants Transformations
19572      */
19573     
19574     InlineLexer.prototype.smartypants = function(text) {
19575       if (!this.options.smartypants)  { return text; }
19576       return text
19577         // em-dashes
19578         .replace(/---/g, '\u2014')
19579         // en-dashes
19580         .replace(/--/g, '\u2013')
19581         // opening singles
19582         .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
19583         // closing singles & apostrophes
19584         .replace(/'/g, '\u2019')
19585         // opening doubles
19586         .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
19587         // closing doubles
19588         .replace(/"/g, '\u201d')
19589         // ellipses
19590         .replace(/\.{3}/g, '\u2026');
19591     };
19592     
19593     /**
19594      * Mangle Links
19595      */
19596     
19597     InlineLexer.prototype.mangle = function(text) {
19598       if (!this.options.mangle) { return text; }
19599       var out = ''
19600         , l = text.length
19601         , i = 0
19602         , ch;
19603     
19604       for (; i < l; i++) {
19605         ch = text.charCodeAt(i);
19606         if (Math.random() > 0.5) {
19607           ch = 'x' + ch.toString(16);
19608         }
19609         out += '&#' + ch + ';';
19610       }
19611     
19612       return out;
19613     };
19614     
19615     /**
19616      * Renderer
19617      */
19618     
19619      /**
19620          * eval:var:Renderer
19621     */
19622     
19623     var Renderer   = function (options) {
19624       this.options = options || {};
19625     }
19626     
19627     Renderer.prototype.code = function(code, lang, escaped) {
19628       if (this.options.highlight) {
19629         var out = this.options.highlight(code, lang);
19630         if (out != null && out !== code) {
19631           escaped = true;
19632           code = out;
19633         }
19634       } else {
19635             // hack!!! - it's already escapeD?
19636             escaped = true;
19637       }
19638     
19639       if (!lang) {
19640         return '<pre><code>'
19641           + (escaped ? code : escape(code, true))
19642           + '\n</code></pre>';
19643       }
19644     
19645       return '<pre><code class="'
19646         + this.options.langPrefix
19647         + escape(lang, true)
19648         + '">'
19649         + (escaped ? code : escape(code, true))
19650         + '\n</code></pre>\n';
19651     };
19652     
19653     Renderer.prototype.blockquote = function(quote) {
19654       return '<blockquote>\n' + quote + '</blockquote>\n';
19655     };
19656     
19657     Renderer.prototype.html = function(html) {
19658       return html;
19659     };
19660     
19661     Renderer.prototype.heading = function(text, level, raw) {
19662       return '<h'
19663         + level
19664         + ' id="'
19665         + this.options.headerPrefix
19666         + raw.toLowerCase().replace(/[^\w]+/g, '-')
19667         + '">'
19668         + text
19669         + '</h'
19670         + level
19671         + '>\n';
19672     };
19673     
19674     Renderer.prototype.hr = function() {
19675       return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
19676     };
19677     
19678     Renderer.prototype.list = function(body, ordered) {
19679       var type = ordered ? 'ol' : 'ul';
19680       return '<' + type + '>\n' + body + '</' + type + '>\n';
19681     };
19682     
19683     Renderer.prototype.listitem = function(text) {
19684       return '<li>' + text + '</li>\n';
19685     };
19686     
19687     Renderer.prototype.paragraph = function(text) {
19688       return '<p>' + text + '</p>\n';
19689     };
19690     
19691     Renderer.prototype.table = function(header, body) {
19692       return '<table class="table table-striped">\n'
19693         + '<thead>\n'
19694         + header
19695         + '</thead>\n'
19696         + '<tbody>\n'
19697         + body
19698         + '</tbody>\n'
19699         + '</table>\n';
19700     };
19701     
19702     Renderer.prototype.tablerow = function(content) {
19703       return '<tr>\n' + content + '</tr>\n';
19704     };
19705     
19706     Renderer.prototype.tablecell = function(content, flags) {
19707       var type = flags.header ? 'th' : 'td';
19708       var tag = flags.align
19709         ? '<' + type + ' style="text-align:' + flags.align + '">'
19710         : '<' + type + '>';
19711       return tag + content + '</' + type + '>\n';
19712     };
19713     
19714     // span level renderer
19715     Renderer.prototype.strong = function(text) {
19716       return '<strong>' + text + '</strong>';
19717     };
19718     
19719     Renderer.prototype.em = function(text) {
19720       return '<em>' + text + '</em>';
19721     };
19722     
19723     Renderer.prototype.codespan = function(text) {
19724       return '<code>' + text + '</code>';
19725     };
19726     
19727     Renderer.prototype.br = function() {
19728       return this.options.xhtml ? '<br/>' : '<br>';
19729     };
19730     
19731     Renderer.prototype.del = function(text) {
19732       return '<del>' + text + '</del>';
19733     };
19734     
19735     Renderer.prototype.link = function(href, title, text) {
19736       if (this.options.sanitize) {
19737         try {
19738           var prot = decodeURIComponent(unescape(href))
19739             .replace(/[^\w:]/g, '')
19740             .toLowerCase();
19741         } catch (e) {
19742           return '';
19743         }
19744         if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
19745           return '';
19746         }
19747       }
19748       var out = '<a href="' + href + '"';
19749       if (title) {
19750         out += ' title="' + title + '"';
19751       }
19752       out += '>' + text + '</a>';
19753       return out;
19754     };
19755     
19756     Renderer.prototype.image = function(href, title, text) {
19757       var out = '<img src="' + href + '" alt="' + text + '"';
19758       if (title) {
19759         out += ' title="' + title + '"';
19760       }
19761       out += this.options.xhtml ? '/>' : '>';
19762       return out;
19763     };
19764     
19765     Renderer.prototype.text = function(text) {
19766       return text;
19767     };
19768     
19769     /**
19770      * Parsing & Compiling
19771      */
19772          /**
19773          * eval:var:Parser
19774     */
19775     
19776     var Parser= function (options) {
19777       this.tokens = [];
19778       this.token = null;
19779       this.options = options || marked.defaults;
19780       this.options.renderer = this.options.renderer || new Renderer;
19781       this.renderer = this.options.renderer;
19782       this.renderer.options = this.options;
19783     }
19784     
19785     /**
19786      * Static Parse Method
19787      */
19788     
19789     Parser.parse = function(src, options, renderer) {
19790       var parser = new Parser(options, renderer);
19791       return parser.parse(src);
19792     };
19793     
19794     /**
19795      * Parse Loop
19796      */
19797     
19798     Parser.prototype.parse = function(src) {
19799       this.inline = new InlineLexer(src.links, this.options, this.renderer);
19800       this.tokens = src.reverse();
19801     
19802       var out = '';
19803       while (this.next()) {
19804         out += this.tok();
19805       }
19806     
19807       return out;
19808     };
19809     
19810     /**
19811      * Next Token
19812      */
19813     
19814     Parser.prototype.next = function() {
19815       return this.token = this.tokens.pop();
19816     };
19817     
19818     /**
19819      * Preview Next Token
19820      */
19821     
19822     Parser.prototype.peek = function() {
19823       return this.tokens[this.tokens.length - 1] || 0;
19824     };
19825     
19826     /**
19827      * Parse Text Tokens
19828      */
19829     
19830     Parser.prototype.parseText = function() {
19831       var body = this.token.text;
19832     
19833       while (this.peek().type === 'text') {
19834         body += '\n' + this.next().text;
19835       }
19836     
19837       return this.inline.output(body);
19838     };
19839     
19840     /**
19841      * Parse Current Token
19842      */
19843     
19844     Parser.prototype.tok = function() {
19845       switch (this.token.type) {
19846         case 'space': {
19847           return '';
19848         }
19849         case 'hr': {
19850           return this.renderer.hr();
19851         }
19852         case 'heading': {
19853           return this.renderer.heading(
19854             this.inline.output(this.token.text),
19855             this.token.depth,
19856             this.token.text);
19857         }
19858         case 'code': {
19859           return this.renderer.code(this.token.text,
19860             this.token.lang,
19861             this.token.escaped);
19862         }
19863         case 'table': {
19864           var header = ''
19865             , body = ''
19866             , i
19867             , row
19868             , cell
19869             , flags
19870             , j;
19871     
19872           // header
19873           cell = '';
19874           for (i = 0; i < this.token.header.length; i++) {
19875             flags = { header: true, align: this.token.align[i] };
19876             cell += this.renderer.tablecell(
19877               this.inline.output(this.token.header[i]),
19878               { header: true, align: this.token.align[i] }
19879             );
19880           }
19881           header += this.renderer.tablerow(cell);
19882     
19883           for (i = 0; i < this.token.cells.length; i++) {
19884             row = this.token.cells[i];
19885     
19886             cell = '';
19887             for (j = 0; j < row.length; j++) {
19888               cell += this.renderer.tablecell(
19889                 this.inline.output(row[j]),
19890                 { header: false, align: this.token.align[j] }
19891               );
19892             }
19893     
19894             body += this.renderer.tablerow(cell);
19895           }
19896           return this.renderer.table(header, body);
19897         }
19898         case 'blockquote_start': {
19899           var body = '';
19900     
19901           while (this.next().type !== 'blockquote_end') {
19902             body += this.tok();
19903           }
19904     
19905           return this.renderer.blockquote(body);
19906         }
19907         case 'list_start': {
19908           var body = ''
19909             , ordered = this.token.ordered;
19910     
19911           while (this.next().type !== 'list_end') {
19912             body += this.tok();
19913           }
19914     
19915           return this.renderer.list(body, ordered);
19916         }
19917         case 'list_item_start': {
19918           var body = '';
19919     
19920           while (this.next().type !== 'list_item_end') {
19921             body += this.token.type === 'text'
19922               ? this.parseText()
19923               : this.tok();
19924           }
19925     
19926           return this.renderer.listitem(body);
19927         }
19928         case 'loose_item_start': {
19929           var body = '';
19930     
19931           while (this.next().type !== 'list_item_end') {
19932             body += this.tok();
19933           }
19934     
19935           return this.renderer.listitem(body);
19936         }
19937         case 'html': {
19938           var html = !this.token.pre && !this.options.pedantic
19939             ? this.inline.output(this.token.text)
19940             : this.token.text;
19941           return this.renderer.html(html);
19942         }
19943         case 'paragraph': {
19944           return this.renderer.paragraph(this.inline.output(this.token.text));
19945         }
19946         case 'text': {
19947           return this.renderer.paragraph(this.parseText());
19948         }
19949       }
19950     };
19951   
19952     
19953     /**
19954      * Marked
19955      */
19956          /**
19957          * eval:var:marked
19958     */
19959     var marked = function (src, opt, callback) {
19960       if (callback || typeof opt === 'function') {
19961         if (!callback) {
19962           callback = opt;
19963           opt = null;
19964         }
19965     
19966         opt = merge({}, marked.defaults, opt || {});
19967     
19968         var highlight = opt.highlight
19969           , tokens
19970           , pending
19971           , i = 0;
19972     
19973         try {
19974           tokens = Lexer.lex(src, opt)
19975         } catch (e) {
19976           return callback(e);
19977         }
19978     
19979         pending = tokens.length;
19980          /**
19981          * eval:var:done
19982     */
19983         var done = function(err) {
19984           if (err) {
19985             opt.highlight = highlight;
19986             return callback(err);
19987           }
19988     
19989           var out;
19990     
19991           try {
19992             out = Parser.parse(tokens, opt);
19993           } catch (e) {
19994             err = e;
19995           }
19996     
19997           opt.highlight = highlight;
19998     
19999           return err
20000             ? callback(err)
20001             : callback(null, out);
20002         };
20003     
20004         if (!highlight || highlight.length < 3) {
20005           return done();
20006         }
20007     
20008         delete opt.highlight;
20009     
20010         if (!pending) { return done(); }
20011     
20012         for (; i < tokens.length; i++) {
20013           (function(token) {
20014             if (token.type !== 'code') {
20015               return --pending || done();
20016             }
20017             return highlight(token.text, token.lang, function(err, code) {
20018               if (err) { return done(err); }
20019               if (code == null || code === token.text) {
20020                 return --pending || done();
20021               }
20022               token.text = code;
20023               token.escaped = true;
20024               --pending || done();
20025             });
20026           })(tokens[i]);
20027         }
20028     
20029         return;
20030       }
20031       try {
20032         if (opt) { opt = merge({}, marked.defaults, opt); }
20033         return Parser.parse(Lexer.lex(src, opt), opt);
20034       } catch (e) {
20035         e.message += '\nPlease report this to https://github.com/chjj/marked.';
20036         if ((opt || marked.defaults).silent) {
20037           return '<p>An error occured:</p><pre>'
20038             + escape(e.message + '', true)
20039             + '</pre>';
20040         }
20041         throw e;
20042       }
20043     }
20044     
20045     /**
20046      * Options
20047      */
20048     
20049     marked.options =
20050     marked.setOptions = function(opt) {
20051       merge(marked.defaults, opt);
20052       return marked;
20053     };
20054     
20055     marked.defaults = {
20056       gfm: true,
20057       tables: true,
20058       breaks: false,
20059       pedantic: false,
20060       sanitize: false,
20061       sanitizer: null,
20062       mangle: true,
20063       smartLists: false,
20064       silent: false,
20065       highlight: null,
20066       langPrefix: 'lang-',
20067       smartypants: false,
20068       headerPrefix: '',
20069       renderer: new Renderer,
20070       xhtml: false
20071     };
20072     
20073     /**
20074      * Expose
20075      */
20076     
20077     marked.Parser = Parser;
20078     marked.parser = Parser.parse;
20079     
20080     marked.Renderer = Renderer;
20081     
20082     marked.Lexer = Lexer;
20083     marked.lexer = Lexer.lex;
20084     
20085     marked.InlineLexer = InlineLexer;
20086     marked.inlineLexer = InlineLexer.output;
20087     
20088     marked.parse = marked;
20089     
20090     Roo.Markdown.marked = marked;
20091
20092 })();/*
20093  * Based on:
20094  * Ext JS Library 1.1.1
20095  * Copyright(c) 2006-2007, Ext JS, LLC.
20096  *
20097  * Originally Released Under LGPL - original licence link has changed is not relivant.
20098  *
20099  * Fork - LGPL
20100  * <script type="text/javascript">
20101  */
20102
20103
20104
20105 /*
20106  * These classes are derivatives of the similarly named classes in the YUI Library.
20107  * The original license:
20108  * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
20109  * Code licensed under the BSD License:
20110  * http://developer.yahoo.net/yui/license.txt
20111  */
20112
20113 (function() {
20114
20115 var Event=Roo.EventManager;
20116 var Dom=Roo.lib.Dom;
20117
20118 /**
20119  * @class Roo.dd.DragDrop
20120  * @extends Roo.util.Observable
20121  * Defines the interface and base operation of items that that can be
20122  * dragged or can be drop targets.  It was designed to be extended, overriding
20123  * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
20124  * Up to three html elements can be associated with a DragDrop instance:
20125  * <ul>
20126  * <li>linked element: the element that is passed into the constructor.
20127  * This is the element which defines the boundaries for interaction with
20128  * other DragDrop objects.</li>
20129  * <li>handle element(s): The drag operation only occurs if the element that
20130  * was clicked matches a handle element.  By default this is the linked
20131  * element, but there are times that you will want only a portion of the
20132  * linked element to initiate the drag operation, and the setHandleElId()
20133  * method provides a way to define this.</li>
20134  * <li>drag element: this represents the element that would be moved along
20135  * with the cursor during a drag operation.  By default, this is the linked
20136  * element itself as in {@link Roo.dd.DD}.  setDragElId() lets you define
20137  * a separate element that would be moved, as in {@link Roo.dd.DDProxy}.
20138  * </li>
20139  * </ul>
20140  * This class should not be instantiated until the onload event to ensure that
20141  * the associated elements are available.
20142  * The following would define a DragDrop obj that would interact with any
20143  * other DragDrop obj in the "group1" group:
20144  * <pre>
20145  *  dd = new Roo.dd.DragDrop("div1", "group1");
20146  * </pre>
20147  * Since none of the event handlers have been implemented, nothing would
20148  * actually happen if you were to run the code above.  Normally you would
20149  * override this class or one of the default implementations, but you can
20150  * also override the methods you want on an instance of the class...
20151  * <pre>
20152  *  dd.onDragDrop = function(e, id) {
20153  *  &nbsp;&nbsp;alert("dd was dropped on " + id);
20154  *  }
20155  * </pre>
20156  * @constructor
20157  * @param {String} id of the element that is linked to this instance
20158  * @param {String} sGroup the group of related DragDrop objects
20159  * @param {object} config an object containing configurable attributes
20160  *                Valid properties for DragDrop:
20161  *                    padding, isTarget, maintainOffset, primaryButtonOnly
20162  */
20163 Roo.dd.DragDrop = function(id, sGroup, config) {
20164     if (id) {
20165         this.init(id, sGroup, config);
20166     }
20167     
20168 };
20169
20170 Roo.extend(Roo.dd.DragDrop, Roo.util.Observable , {
20171
20172     /**
20173      * The id of the element associated with this object.  This is what we
20174      * refer to as the "linked element" because the size and position of
20175      * this element is used to determine when the drag and drop objects have
20176      * interacted.
20177      * @property id
20178      * @type String
20179      */
20180     id: null,
20181
20182     /**
20183      * Configuration attributes passed into the constructor
20184      * @property config
20185      * @type object
20186      */
20187     config: null,
20188
20189     /**
20190      * The id of the element that will be dragged.  By default this is same
20191      * as the linked element , but could be changed to another element. Ex:
20192      * Roo.dd.DDProxy
20193      * @property dragElId
20194      * @type String
20195      * @private
20196      */
20197     dragElId: null,
20198
20199     /**
20200      * the id of the element that initiates the drag operation.  By default
20201      * this is the linked element, but could be changed to be a child of this
20202      * element.  This lets us do things like only starting the drag when the
20203      * header element within the linked html element is clicked.
20204      * @property handleElId
20205      * @type String
20206      * @private
20207      */
20208     handleElId: null,
20209
20210     /**
20211      * An associative array of HTML tags that will be ignored if clicked.
20212      * @property invalidHandleTypes
20213      * @type {string: string}
20214      */
20215     invalidHandleTypes: null,
20216
20217     /**
20218      * An associative array of ids for elements that will be ignored if clicked
20219      * @property invalidHandleIds
20220      * @type {string: string}
20221      */
20222     invalidHandleIds: null,
20223
20224     /**
20225      * An indexted array of css class names for elements that will be ignored
20226      * if clicked.
20227      * @property invalidHandleClasses
20228      * @type string[]
20229      */
20230     invalidHandleClasses: null,
20231
20232     /**
20233      * The linked element's absolute X position at the time the drag was
20234      * started
20235      * @property startPageX
20236      * @type int
20237      * @private
20238      */
20239     startPageX: 0,
20240
20241     /**
20242      * The linked element's absolute X position at the time the drag was
20243      * started
20244      * @property startPageY
20245      * @type int
20246      * @private
20247      */
20248     startPageY: 0,
20249
20250     /**
20251      * The group defines a logical collection of DragDrop objects that are
20252      * related.  Instances only get events when interacting with other
20253      * DragDrop object in the same group.  This lets us define multiple
20254      * groups using a single DragDrop subclass if we want.
20255      * @property groups
20256      * @type {string: string}
20257      */
20258     groups: null,
20259
20260     /**
20261      * Individual drag/drop instances can be locked.  This will prevent
20262      * onmousedown start drag.
20263      * @property locked
20264      * @type boolean
20265      * @private
20266      */
20267     locked: false,
20268
20269     /**
20270      * Lock this instance
20271      * @method lock
20272      */
20273     lock: function() { this.locked = true; },
20274
20275     /**
20276      * Unlock this instace
20277      * @method unlock
20278      */
20279     unlock: function() { this.locked = false; },
20280
20281     /**
20282      * By default, all insances can be a drop target.  This can be disabled by
20283      * setting isTarget to false.
20284      * @method isTarget
20285      * @type boolean
20286      */
20287     isTarget: true,
20288
20289     /**
20290      * The padding configured for this drag and drop object for calculating
20291      * the drop zone intersection with this object.
20292      * @method padding
20293      * @type int[]
20294      */
20295     padding: null,
20296
20297     /**
20298      * Cached reference to the linked element
20299      * @property _domRef
20300      * @private
20301      */
20302     _domRef: null,
20303
20304     /**
20305      * Internal typeof flag
20306      * @property __ygDragDrop
20307      * @private
20308      */
20309     __ygDragDrop: true,
20310
20311     /**
20312      * Set to true when horizontal contraints are applied
20313      * @property constrainX
20314      * @type boolean
20315      * @private
20316      */
20317     constrainX: false,
20318
20319     /**
20320      * Set to true when vertical contraints are applied
20321      * @property constrainY
20322      * @type boolean
20323      * @private
20324      */
20325     constrainY: false,
20326
20327     /**
20328      * The left constraint
20329      * @property minX
20330      * @type int
20331      * @private
20332      */
20333     minX: 0,
20334
20335     /**
20336      * The right constraint
20337      * @property maxX
20338      * @type int
20339      * @private
20340      */
20341     maxX: 0,
20342
20343     /**
20344      * The up constraint
20345      * @property minY
20346      * @type int
20347      * @type int
20348      * @private
20349      */
20350     minY: 0,
20351
20352     /**
20353      * The down constraint
20354      * @property maxY
20355      * @type int
20356      * @private
20357      */
20358     maxY: 0,
20359
20360     /**
20361      * Maintain offsets when we resetconstraints.  Set to true when you want
20362      * the position of the element relative to its parent to stay the same
20363      * when the page changes
20364      *
20365      * @property maintainOffset
20366      * @type boolean
20367      */
20368     maintainOffset: false,
20369
20370     /**
20371      * Array of pixel locations the element will snap to if we specified a
20372      * horizontal graduation/interval.  This array is generated automatically
20373      * when you define a tick interval.
20374      * @property xTicks
20375      * @type int[]
20376      */
20377     xTicks: null,
20378
20379     /**
20380      * Array of pixel locations the element will snap to if we specified a
20381      * vertical graduation/interval.  This array is generated automatically
20382      * when you define a tick interval.
20383      * @property yTicks
20384      * @type int[]
20385      */
20386     yTicks: null,
20387
20388     /**
20389      * By default the drag and drop instance will only respond to the primary
20390      * button click (left button for a right-handed mouse).  Set to true to
20391      * allow drag and drop to start with any mouse click that is propogated
20392      * by the browser
20393      * @property primaryButtonOnly
20394      * @type boolean
20395      */
20396     primaryButtonOnly: true,
20397
20398     /**
20399      * The availabe property is false until the linked dom element is accessible.
20400      * @property available
20401      * @type boolean
20402      */
20403     available: false,
20404
20405     /**
20406      * By default, drags can only be initiated if the mousedown occurs in the
20407      * region the linked element is.  This is done in part to work around a
20408      * bug in some browsers that mis-report the mousedown if the previous
20409      * mouseup happened outside of the window.  This property is set to true
20410      * if outer handles are defined.
20411      *
20412      * @property hasOuterHandles
20413      * @type boolean
20414      * @default false
20415      */
20416     hasOuterHandles: false,
20417
20418     /**
20419      * Code that executes immediately before the startDrag event
20420      * @method b4StartDrag
20421      * @private
20422      */
20423     b4StartDrag: function(x, y) { },
20424
20425     /**
20426      * Abstract method called after a drag/drop object is clicked
20427      * and the drag or mousedown time thresholds have beeen met.
20428      * @method startDrag
20429      * @param {int} X click location
20430      * @param {int} Y click location
20431      */
20432     startDrag: function(x, y) { /* override this */ },
20433
20434     /**
20435      * Code that executes immediately before the onDrag event
20436      * @method b4Drag
20437      * @private
20438      */
20439     b4Drag: function(e) { },
20440
20441     /**
20442      * Abstract method called during the onMouseMove event while dragging an
20443      * object.
20444      * @method onDrag
20445      * @param {Event} e the mousemove event
20446      */
20447     onDrag: function(e) { /* override this */ },
20448
20449     /**
20450      * Abstract method called when this element fist begins hovering over
20451      * another DragDrop obj
20452      * @method onDragEnter
20453      * @param {Event} e the mousemove event
20454      * @param {String|DragDrop[]} id In POINT mode, the element
20455      * id this is hovering over.  In INTERSECT mode, an array of one or more
20456      * dragdrop items being hovered over.
20457      */
20458     onDragEnter: function(e, id) { /* override this */ },
20459
20460     /**
20461      * Code that executes immediately before the onDragOver event
20462      * @method b4DragOver
20463      * @private
20464      */
20465     b4DragOver: function(e) { },
20466
20467     /**
20468      * Abstract method called when this element is hovering over another
20469      * DragDrop obj
20470      * @method onDragOver
20471      * @param {Event} e the mousemove event
20472      * @param {String|DragDrop[]} id In POINT mode, the element
20473      * id this is hovering over.  In INTERSECT mode, an array of dd items
20474      * being hovered over.
20475      */
20476     onDragOver: function(e, id) { /* override this */ },
20477
20478     /**
20479      * Code that executes immediately before the onDragOut event
20480      * @method b4DragOut
20481      * @private
20482      */
20483     b4DragOut: function(e) { },
20484
20485     /**
20486      * Abstract method called when we are no longer hovering over an element
20487      * @method onDragOut
20488      * @param {Event} e the mousemove event
20489      * @param {String|DragDrop[]} id In POINT mode, the element
20490      * id this was hovering over.  In INTERSECT mode, an array of dd items
20491      * that the mouse is no longer over.
20492      */
20493     onDragOut: function(e, id) { /* override this */ },
20494
20495     /**
20496      * Code that executes immediately before the onDragDrop event
20497      * @method b4DragDrop
20498      * @private
20499      */
20500     b4DragDrop: function(e) { },
20501
20502     /**
20503      * Abstract method called when this item is dropped on another DragDrop
20504      * obj
20505      * @method onDragDrop
20506      * @param {Event} e the mouseup event
20507      * @param {String|DragDrop[]} id In POINT mode, the element
20508      * id this was dropped on.  In INTERSECT mode, an array of dd items this
20509      * was dropped on.
20510      */
20511     onDragDrop: function(e, id) { /* override this */ },
20512
20513     /**
20514      * Abstract method called when this item is dropped on an area with no
20515      * drop target
20516      * @method onInvalidDrop
20517      * @param {Event} e the mouseup event
20518      */
20519     onInvalidDrop: function(e) { /* override this */ },
20520
20521     /**
20522      * Code that executes immediately before the endDrag event
20523      * @method b4EndDrag
20524      * @private
20525      */
20526     b4EndDrag: function(e) { },
20527
20528     /**
20529      * Fired when we are done dragging the object
20530      * @method endDrag
20531      * @param {Event} e the mouseup event
20532      */
20533     endDrag: function(e) { /* override this */ },
20534
20535     /**
20536      * Code executed immediately before the onMouseDown event
20537      * @method b4MouseDown
20538      * @param {Event} e the mousedown event
20539      * @private
20540      */
20541     b4MouseDown: function(e) {  },
20542
20543     /**
20544      * Event handler that fires when a drag/drop obj gets a mousedown
20545      * @method onMouseDown
20546      * @param {Event} e the mousedown event
20547      */
20548     onMouseDown: function(e) { /* override this */ },
20549
20550     /**
20551      * Event handler that fires when a drag/drop obj gets a mouseup
20552      * @method onMouseUp
20553      * @param {Event} e the mouseup event
20554      */
20555     onMouseUp: function(e) { /* override this */ },
20556
20557     /**
20558      * Override the onAvailable method to do what is needed after the initial
20559      * position was determined.
20560      * @method onAvailable
20561      */
20562     onAvailable: function () {
20563     },
20564
20565     /*
20566      * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
20567      * @type Object
20568      */
20569     defaultPadding : {left:0, right:0, top:0, bottom:0},
20570
20571     /*
20572      * Initializes the drag drop object's constraints to restrict movement to a certain element.
20573  *
20574  * Usage:
20575  <pre><code>
20576  var dd = new Roo.dd.DDProxy("dragDiv1", "proxytest",
20577                 { dragElId: "existingProxyDiv" });
20578  dd.startDrag = function(){
20579      this.constrainTo("parent-id");
20580  };
20581  </code></pre>
20582  * Or you can initalize it using the {@link Roo.Element} object:
20583  <pre><code>
20584  Roo.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
20585      startDrag : function(){
20586          this.constrainTo("parent-id");
20587      }
20588  });
20589  </code></pre>
20590      * @param {String/HTMLElement/Element} constrainTo The element to constrain to.
20591      * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
20592      * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
20593      * an object containing the sides to pad. For example: {right:10, bottom:10}
20594      * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
20595      */
20596     constrainTo : function(constrainTo, pad, inContent){
20597         if(typeof pad == "number"){
20598             pad = {left: pad, right:pad, top:pad, bottom:pad};
20599         }
20600         pad = pad || this.defaultPadding;
20601         var b = Roo.get(this.getEl()).getBox();
20602         var ce = Roo.get(constrainTo);
20603         var s = ce.getScroll();
20604         var c, cd = ce.dom;
20605         if(cd == document.body){
20606             c = { x: s.left, y: s.top, width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
20607         }else{
20608             xy = ce.getXY();
20609             c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
20610         }
20611
20612
20613         var topSpace = b.y - c.y;
20614         var leftSpace = b.x - c.x;
20615
20616         this.resetConstraints();
20617         this.setXConstraint(leftSpace - (pad.left||0), // left
20618                 c.width - leftSpace - b.width - (pad.right||0) //right
20619         );
20620         this.setYConstraint(topSpace - (pad.top||0), //top
20621                 c.height - topSpace - b.height - (pad.bottom||0) //bottom
20622         );
20623     },
20624
20625     /**
20626      * Returns a reference to the linked element
20627      * @method getEl
20628      * @return {HTMLElement} the html element
20629      */
20630     getEl: function() {
20631         if (!this._domRef) {
20632             this._domRef = Roo.getDom(this.id);
20633         }
20634
20635         return this._domRef;
20636     },
20637
20638     /**
20639      * Returns a reference to the actual element to drag.  By default this is
20640      * the same as the html element, but it can be assigned to another
20641      * element. An example of this can be found in Roo.dd.DDProxy
20642      * @method getDragEl
20643      * @return {HTMLElement} the html element
20644      */
20645     getDragEl: function() {
20646         return Roo.getDom(this.dragElId);
20647     },
20648
20649     /**
20650      * Sets up the DragDrop object.  Must be called in the constructor of any
20651      * Roo.dd.DragDrop subclass
20652      * @method init
20653      * @param id the id of the linked element
20654      * @param {String} sGroup the group of related items
20655      * @param {object} config configuration attributes
20656      */
20657     init: function(id, sGroup, config) {
20658         this.initTarget(id, sGroup, config);
20659         if (!Roo.isTouch) {
20660             Event.on(this.id, "mousedown", this.handleMouseDown, this);
20661         }
20662         Event.on(this.id, "touchstart", this.handleMouseDown, this);
20663         // Event.on(this.id, "selectstart", Event.preventDefault);
20664     },
20665
20666     /**
20667      * Initializes Targeting functionality only... the object does not
20668      * get a mousedown handler.
20669      * @method initTarget
20670      * @param id the id of the linked element
20671      * @param {String} sGroup the group of related items
20672      * @param {object} config configuration attributes
20673      */
20674     initTarget: function(id, sGroup, config) {
20675
20676         // configuration attributes
20677         this.config = config || {};
20678
20679         // create a local reference to the drag and drop manager
20680         this.DDM = Roo.dd.DDM;
20681         // initialize the groups array
20682         this.groups = {};
20683
20684         // assume that we have an element reference instead of an id if the
20685         // parameter is not a string
20686         if (typeof id !== "string") {
20687             id = Roo.id(id);
20688         }
20689
20690         // set the id
20691         this.id = id;
20692
20693         // add to an interaction group
20694         this.addToGroup((sGroup) ? sGroup : "default");
20695
20696         // We don't want to register this as the handle with the manager
20697         // so we just set the id rather than calling the setter.
20698         this.handleElId = id;
20699
20700         // the linked element is the element that gets dragged by default
20701         this.setDragElId(id);
20702
20703         // by default, clicked anchors will not start drag operations.
20704         this.invalidHandleTypes = { A: "A" };
20705         this.invalidHandleIds = {};
20706         this.invalidHandleClasses = [];
20707
20708         this.applyConfig();
20709
20710         this.handleOnAvailable();
20711     },
20712
20713     /**
20714      * Applies the configuration parameters that were passed into the constructor.
20715      * This is supposed to happen at each level through the inheritance chain.  So
20716      * a DDProxy implentation will execute apply config on DDProxy, DD, and
20717      * DragDrop in order to get all of the parameters that are available in
20718      * each object.
20719      * @method applyConfig
20720      */
20721     applyConfig: function() {
20722
20723         // configurable properties:
20724         //    padding, isTarget, maintainOffset, primaryButtonOnly
20725         this.padding           = this.config.padding || [0, 0, 0, 0];
20726         this.isTarget          = (this.config.isTarget !== false);
20727         this.maintainOffset    = (this.config.maintainOffset);
20728         this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
20729
20730     },
20731
20732     /**
20733      * Executed when the linked element is available
20734      * @method handleOnAvailable
20735      * @private
20736      */
20737     handleOnAvailable: function() {
20738         this.available = true;
20739         this.resetConstraints();
20740         this.onAvailable();
20741     },
20742
20743      /**
20744      * Configures the padding for the target zone in px.  Effectively expands
20745      * (or reduces) the virtual object size for targeting calculations.
20746      * Supports css-style shorthand; if only one parameter is passed, all sides
20747      * will have that padding, and if only two are passed, the top and bottom
20748      * will have the first param, the left and right the second.
20749      * @method setPadding
20750      * @param {int} iTop    Top pad
20751      * @param {int} iRight  Right pad
20752      * @param {int} iBot    Bot pad
20753      * @param {int} iLeft   Left pad
20754      */
20755     setPadding: function(iTop, iRight, iBot, iLeft) {
20756         // this.padding = [iLeft, iRight, iTop, iBot];
20757         if (!iRight && 0 !== iRight) {
20758             this.padding = [iTop, iTop, iTop, iTop];
20759         } else if (!iBot && 0 !== iBot) {
20760             this.padding = [iTop, iRight, iTop, iRight];
20761         } else {
20762             this.padding = [iTop, iRight, iBot, iLeft];
20763         }
20764     },
20765
20766     /**
20767      * Stores the initial placement of the linked element.
20768      * @method setInitialPosition
20769      * @param {int} diffX   the X offset, default 0
20770      * @param {int} diffY   the Y offset, default 0
20771      */
20772     setInitPosition: function(diffX, diffY) {
20773         var el = this.getEl();
20774
20775         if (!this.DDM.verifyEl(el)) {
20776             return;
20777         }
20778
20779         var dx = diffX || 0;
20780         var dy = diffY || 0;
20781
20782         var p = Dom.getXY( el );
20783
20784         this.initPageX = p[0] - dx;
20785         this.initPageY = p[1] - dy;
20786
20787         this.lastPageX = p[0];
20788         this.lastPageY = p[1];
20789
20790
20791         this.setStartPosition(p);
20792     },
20793
20794     /**
20795      * Sets the start position of the element.  This is set when the obj
20796      * is initialized, the reset when a drag is started.
20797      * @method setStartPosition
20798      * @param pos current position (from previous lookup)
20799      * @private
20800      */
20801     setStartPosition: function(pos) {
20802         var p = pos || Dom.getXY( this.getEl() );
20803         this.deltaSetXY = null;
20804
20805         this.startPageX = p[0];
20806         this.startPageY = p[1];
20807     },
20808
20809     /**
20810      * Add this instance to a group of related drag/drop objects.  All
20811      * instances belong to at least one group, and can belong to as many
20812      * groups as needed.
20813      * @method addToGroup
20814      * @param sGroup {string} the name of the group
20815      */
20816     addToGroup: function(sGroup) {
20817         this.groups[sGroup] = true;
20818         this.DDM.regDragDrop(this, sGroup);
20819     },
20820
20821     /**
20822      * Remove's this instance from the supplied interaction group
20823      * @method removeFromGroup
20824      * @param {string}  sGroup  The group to drop
20825      */
20826     removeFromGroup: function(sGroup) {
20827         if (this.groups[sGroup]) {
20828             delete this.groups[sGroup];
20829         }
20830
20831         this.DDM.removeDDFromGroup(this, sGroup);
20832     },
20833
20834     /**
20835      * Allows you to specify that an element other than the linked element
20836      * will be moved with the cursor during a drag
20837      * @method setDragElId
20838      * @param id {string} the id of the element that will be used to initiate the drag
20839      */
20840     setDragElId: function(id) {
20841         this.dragElId = id;
20842     },
20843
20844     /**
20845      * Allows you to specify a child of the linked element that should be
20846      * used to initiate the drag operation.  An example of this would be if
20847      * you have a content div with text and links.  Clicking anywhere in the
20848      * content area would normally start the drag operation.  Use this method
20849      * to specify that an element inside of the content div is the element
20850      * that starts the drag operation.
20851      * @method setHandleElId
20852      * @param id {string} the id of the element that will be used to
20853      * initiate the drag.
20854      */
20855     setHandleElId: function(id) {
20856         if (typeof id !== "string") {
20857             id = Roo.id(id);
20858         }
20859         this.handleElId = id;
20860         this.DDM.regHandle(this.id, id);
20861     },
20862
20863     /**
20864      * Allows you to set an element outside of the linked element as a drag
20865      * handle
20866      * @method setOuterHandleElId
20867      * @param id the id of the element that will be used to initiate the drag
20868      */
20869     setOuterHandleElId: function(id) {
20870         if (typeof id !== "string") {
20871             id = Roo.id(id);
20872         }
20873         Event.on(id, "mousedown",
20874                 this.handleMouseDown, this);
20875         this.setHandleElId(id);
20876
20877         this.hasOuterHandles = true;
20878     },
20879
20880     /**
20881      * Remove all drag and drop hooks for this element
20882      * @method unreg
20883      */
20884     unreg: function() {
20885         Event.un(this.id, "mousedown",
20886                 this.handleMouseDown);
20887         Event.un(this.id, "touchstart",
20888                 this.handleMouseDown);
20889         this._domRef = null;
20890         this.DDM._remove(this);
20891     },
20892
20893     destroy : function(){
20894         this.unreg();
20895     },
20896
20897     /**
20898      * Returns true if this instance is locked, or the drag drop mgr is locked
20899      * (meaning that all drag/drop is disabled on the page.)
20900      * @method isLocked
20901      * @return {boolean} true if this obj or all drag/drop is locked, else
20902      * false
20903      */
20904     isLocked: function() {
20905         return (this.DDM.isLocked() || this.locked);
20906     },
20907
20908     /**
20909      * Fired when this object is clicked
20910      * @method handleMouseDown
20911      * @param {Event} e
20912      * @param {Roo.dd.DragDrop} oDD the clicked dd object (this dd obj)
20913      * @private
20914      */
20915     handleMouseDown: function(e, oDD){
20916      
20917         if (!Roo.isTouch && this.primaryButtonOnly && e.button != 0) {
20918             //Roo.log('not touch/ button !=0');
20919             return;
20920         }
20921         if (e.browserEvent.touches && e.browserEvent.touches.length != 1) {
20922             return; // double touch..
20923         }
20924         
20925
20926         if (this.isLocked()) {
20927             //Roo.log('locked');
20928             return;
20929         }
20930
20931         this.DDM.refreshCache(this.groups);
20932 //        Roo.log([Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e)]);
20933         var pt = new Roo.lib.Point(Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e));
20934         if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) )  {
20935             //Roo.log('no outer handes or not over target');
20936                 // do nothing.
20937         } else {
20938 //            Roo.log('check validator');
20939             if (this.clickValidator(e)) {
20940 //                Roo.log('validate success');
20941                 // set the initial element position
20942                 this.setStartPosition();
20943
20944
20945                 this.b4MouseDown(e);
20946                 this.onMouseDown(e);
20947
20948                 this.DDM.handleMouseDown(e, this);
20949
20950                 this.DDM.stopEvent(e);
20951             } else {
20952
20953
20954             }
20955         }
20956     },
20957
20958     clickValidator: function(e) {
20959         var target = e.getTarget();
20960         return ( this.isValidHandleChild(target) &&
20961                     (this.id == this.handleElId ||
20962                         this.DDM.handleWasClicked(target, this.id)) );
20963     },
20964
20965     /**
20966      * Allows you to specify a tag name that should not start a drag operation
20967      * when clicked.  This is designed to facilitate embedding links within a
20968      * drag handle that do something other than start the drag.
20969      * @method addInvalidHandleType
20970      * @param {string} tagName the type of element to exclude
20971      */
20972     addInvalidHandleType: function(tagName) {
20973         var type = tagName.toUpperCase();
20974         this.invalidHandleTypes[type] = type;
20975     },
20976
20977     /**
20978      * Lets you to specify an element id for a child of a drag handle
20979      * that should not initiate a drag
20980      * @method addInvalidHandleId
20981      * @param {string} id the element id of the element you wish to ignore
20982      */
20983     addInvalidHandleId: function(id) {
20984         if (typeof id !== "string") {
20985             id = Roo.id(id);
20986         }
20987         this.invalidHandleIds[id] = id;
20988     },
20989
20990     /**
20991      * Lets you specify a css class of elements that will not initiate a drag
20992      * @method addInvalidHandleClass
20993      * @param {string} cssClass the class of the elements you wish to ignore
20994      */
20995     addInvalidHandleClass: function(cssClass) {
20996         this.invalidHandleClasses.push(cssClass);
20997     },
20998
20999     /**
21000      * Unsets an excluded tag name set by addInvalidHandleType
21001      * @method removeInvalidHandleType
21002      * @param {string} tagName the type of element to unexclude
21003      */
21004     removeInvalidHandleType: function(tagName) {
21005         var type = tagName.toUpperCase();
21006         // this.invalidHandleTypes[type] = null;
21007         delete this.invalidHandleTypes[type];
21008     },
21009
21010     /**
21011      * Unsets an invalid handle id
21012      * @method removeInvalidHandleId
21013      * @param {string} id the id of the element to re-enable
21014      */
21015     removeInvalidHandleId: function(id) {
21016         if (typeof id !== "string") {
21017             id = Roo.id(id);
21018         }
21019         delete this.invalidHandleIds[id];
21020     },
21021
21022     /**
21023      * Unsets an invalid css class
21024      * @method removeInvalidHandleClass
21025      * @param {string} cssClass the class of the element(s) you wish to
21026      * re-enable
21027      */
21028     removeInvalidHandleClass: function(cssClass) {
21029         for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
21030             if (this.invalidHandleClasses[i] == cssClass) {
21031                 delete this.invalidHandleClasses[i];
21032             }
21033         }
21034     },
21035
21036     /**
21037      * Checks the tag exclusion list to see if this click should be ignored
21038      * @method isValidHandleChild
21039      * @param {HTMLElement} node the HTMLElement to evaluate
21040      * @return {boolean} true if this is a valid tag type, false if not
21041      */
21042     isValidHandleChild: function(node) {
21043
21044         var valid = true;
21045         // var n = (node.nodeName == "#text") ? node.parentNode : node;
21046         var nodeName;
21047         try {
21048             nodeName = node.nodeName.toUpperCase();
21049         } catch(e) {
21050             nodeName = node.nodeName;
21051         }
21052         valid = valid && !this.invalidHandleTypes[nodeName];
21053         valid = valid && !this.invalidHandleIds[node.id];
21054
21055         for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
21056             valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
21057         }
21058
21059
21060         return valid;
21061
21062     },
21063
21064     /**
21065      * Create the array of horizontal tick marks if an interval was specified
21066      * in setXConstraint().
21067      * @method setXTicks
21068      * @private
21069      */
21070     setXTicks: function(iStartX, iTickSize) {
21071         this.xTicks = [];
21072         this.xTickSize = iTickSize;
21073
21074         var tickMap = {};
21075
21076         for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
21077             if (!tickMap[i]) {
21078                 this.xTicks[this.xTicks.length] = i;
21079                 tickMap[i] = true;
21080             }
21081         }
21082
21083         for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
21084             if (!tickMap[i]) {
21085                 this.xTicks[this.xTicks.length] = i;
21086                 tickMap[i] = true;
21087             }
21088         }
21089
21090         this.xTicks.sort(this.DDM.numericSort) ;
21091     },
21092
21093     /**
21094      * Create the array of vertical tick marks if an interval was specified in
21095      * setYConstraint().
21096      * @method setYTicks
21097      * @private
21098      */
21099     setYTicks: function(iStartY, iTickSize) {
21100         this.yTicks = [];
21101         this.yTickSize = iTickSize;
21102
21103         var tickMap = {};
21104
21105         for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
21106             if (!tickMap[i]) {
21107                 this.yTicks[this.yTicks.length] = i;
21108                 tickMap[i] = true;
21109             }
21110         }
21111
21112         for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
21113             if (!tickMap[i]) {
21114                 this.yTicks[this.yTicks.length] = i;
21115                 tickMap[i] = true;
21116             }
21117         }
21118
21119         this.yTicks.sort(this.DDM.numericSort) ;
21120     },
21121
21122     /**
21123      * By default, the element can be dragged any place on the screen.  Use
21124      * this method to limit the horizontal travel of the element.  Pass in
21125      * 0,0 for the parameters if you want to lock the drag to the y axis.
21126      * @method setXConstraint
21127      * @param {int} iLeft the number of pixels the element can move to the left
21128      * @param {int} iRight the number of pixels the element can move to the
21129      * right
21130      * @param {int} iTickSize optional parameter for specifying that the
21131      * element
21132      * should move iTickSize pixels at a time.
21133      */
21134     setXConstraint: function(iLeft, iRight, iTickSize) {
21135         this.leftConstraint = iLeft;
21136         this.rightConstraint = iRight;
21137
21138         this.minX = this.initPageX - iLeft;
21139         this.maxX = this.initPageX + iRight;
21140         if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
21141
21142         this.constrainX = true;
21143     },
21144
21145     /**
21146      * Clears any constraints applied to this instance.  Also clears ticks
21147      * since they can't exist independent of a constraint at this time.
21148      * @method clearConstraints
21149      */
21150     clearConstraints: function() {
21151         this.constrainX = false;
21152         this.constrainY = false;
21153         this.clearTicks();
21154     },
21155
21156     /**
21157      * Clears any tick interval defined for this instance
21158      * @method clearTicks
21159      */
21160     clearTicks: function() {
21161         this.xTicks = null;
21162         this.yTicks = null;
21163         this.xTickSize = 0;
21164         this.yTickSize = 0;
21165     },
21166
21167     /**
21168      * By default, the element can be dragged any place on the screen.  Set
21169      * this to limit the vertical travel of the element.  Pass in 0,0 for the
21170      * parameters if you want to lock the drag to the x axis.
21171      * @method setYConstraint
21172      * @param {int} iUp the number of pixels the element can move up
21173      * @param {int} iDown the number of pixels the element can move down
21174      * @param {int} iTickSize optional parameter for specifying that the
21175      * element should move iTickSize pixels at a time.
21176      */
21177     setYConstraint: function(iUp, iDown, iTickSize) {
21178         this.topConstraint = iUp;
21179         this.bottomConstraint = iDown;
21180
21181         this.minY = this.initPageY - iUp;
21182         this.maxY = this.initPageY + iDown;
21183         if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
21184
21185         this.constrainY = true;
21186
21187     },
21188
21189     /**
21190      * resetConstraints must be called if you manually reposition a dd element.
21191      * @method resetConstraints
21192      * @param {boolean} maintainOffset
21193      */
21194     resetConstraints: function() {
21195
21196
21197         // Maintain offsets if necessary
21198         if (this.initPageX || this.initPageX === 0) {
21199             // figure out how much this thing has moved
21200             var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
21201             var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
21202
21203             this.setInitPosition(dx, dy);
21204
21205         // This is the first time we have detected the element's position
21206         } else {
21207             this.setInitPosition();
21208         }
21209
21210         if (this.constrainX) {
21211             this.setXConstraint( this.leftConstraint,
21212                                  this.rightConstraint,
21213                                  this.xTickSize        );
21214         }
21215
21216         if (this.constrainY) {
21217             this.setYConstraint( this.topConstraint,
21218                                  this.bottomConstraint,
21219                                  this.yTickSize         );
21220         }
21221     },
21222
21223     /**
21224      * Normally the drag element is moved pixel by pixel, but we can specify
21225      * that it move a number of pixels at a time.  This method resolves the
21226      * location when we have it set up like this.
21227      * @method getTick
21228      * @param {int} val where we want to place the object
21229      * @param {int[]} tickArray sorted array of valid points
21230      * @return {int} the closest tick
21231      * @private
21232      */
21233     getTick: function(val, tickArray) {
21234
21235         if (!tickArray) {
21236             // If tick interval is not defined, it is effectively 1 pixel,
21237             // so we return the value passed to us.
21238             return val;
21239         } else if (tickArray[0] >= val) {
21240             // The value is lower than the first tick, so we return the first
21241             // tick.
21242             return tickArray[0];
21243         } else {
21244             for (var i=0, len=tickArray.length; i<len; ++i) {
21245                 var next = i + 1;
21246                 if (tickArray[next] && tickArray[next] >= val) {
21247                     var diff1 = val - tickArray[i];
21248                     var diff2 = tickArray[next] - val;
21249                     return (diff2 > diff1) ? tickArray[i] : tickArray[next];
21250                 }
21251             }
21252
21253             // The value is larger than the last tick, so we return the last
21254             // tick.
21255             return tickArray[tickArray.length - 1];
21256         }
21257     },
21258
21259     /**
21260      * toString method
21261      * @method toString
21262      * @return {string} string representation of the dd obj
21263      */
21264     toString: function() {
21265         return ("DragDrop " + this.id);
21266     }
21267
21268 });
21269
21270 })();
21271 /*
21272  * Based on:
21273  * Ext JS Library 1.1.1
21274  * Copyright(c) 2006-2007, Ext JS, LLC.
21275  *
21276  * Originally Released Under LGPL - original licence link has changed is not relivant.
21277  *
21278  * Fork - LGPL
21279  * <script type="text/javascript">
21280  */
21281
21282
21283 /**
21284  * The drag and drop utility provides a framework for building drag and drop
21285  * applications.  In addition to enabling drag and drop for specific elements,
21286  * the drag and drop elements are tracked by the manager class, and the
21287  * interactions between the various elements are tracked during the drag and
21288  * the implementing code is notified about these important moments.
21289  */
21290
21291 // Only load the library once.  Rewriting the manager class would orphan
21292 // existing drag and drop instances.
21293 if (!Roo.dd.DragDropMgr) {
21294
21295 /**
21296  * @class Roo.dd.DragDropMgr
21297  * DragDropMgr is a singleton that tracks the element interaction for
21298  * all DragDrop items in the window.  Generally, you will not call
21299  * this class directly, but it does have helper methods that could
21300  * be useful in your DragDrop implementations.
21301  * @static
21302  */
21303 Roo.dd.DragDropMgr = function() {
21304
21305     var Event = Roo.EventManager;
21306
21307     return {
21308
21309         /**
21310          * Two dimensional Array of registered DragDrop objects.  The first
21311          * dimension is the DragDrop item group, the second the DragDrop
21312          * object.
21313          * @property ids
21314          * @type {string: string}
21315          * @private
21316          * @static
21317          */
21318         ids: {},
21319
21320         /**
21321          * Array of element ids defined as drag handles.  Used to determine
21322          * if the element that generated the mousedown event is actually the
21323          * handle and not the html element itself.
21324          * @property handleIds
21325          * @type {string: string}
21326          * @private
21327          * @static
21328          */
21329         handleIds: {},
21330
21331         /**
21332          * the DragDrop object that is currently being dragged
21333          * @property dragCurrent
21334          * @type DragDrop
21335          * @private
21336          * @static
21337          **/
21338         dragCurrent: null,
21339
21340         /**
21341          * the DragDrop object(s) that are being hovered over
21342          * @property dragOvers
21343          * @type Array
21344          * @private
21345          * @static
21346          */
21347         dragOvers: {},
21348
21349         /**
21350          * the X distance between the cursor and the object being dragged
21351          * @property deltaX
21352          * @type int
21353          * @private
21354          * @static
21355          */
21356         deltaX: 0,
21357
21358         /**
21359          * the Y distance between the cursor and the object being dragged
21360          * @property deltaY
21361          * @type int
21362          * @private
21363          * @static
21364          */
21365         deltaY: 0,
21366
21367         /**
21368          * Flag to determine if we should prevent the default behavior of the
21369          * events we define. By default this is true, but this can be set to
21370          * false if you need the default behavior (not recommended)
21371          * @property preventDefault
21372          * @type boolean
21373          * @static
21374          */
21375         preventDefault: true,
21376
21377         /**
21378          * Flag to determine if we should stop the propagation of the events
21379          * we generate. This is true by default but you may want to set it to
21380          * false if the html element contains other features that require the
21381          * mouse click.
21382          * @property stopPropagation
21383          * @type boolean
21384          * @static
21385          */
21386         stopPropagation: true,
21387
21388         /**
21389          * Internal flag that is set to true when drag and drop has been
21390          * intialized
21391          * @property initialized
21392          * @private
21393          * @static
21394          */
21395         initalized: false,
21396
21397         /**
21398          * All drag and drop can be disabled.
21399          * @property locked
21400          * @private
21401          * @static
21402          */
21403         locked: false,
21404
21405         /**
21406          * Called the first time an element is registered.
21407          * @method init
21408          * @private
21409          * @static
21410          */
21411         init: function() {
21412             this.initialized = true;
21413         },
21414
21415         /**
21416          * In point mode, drag and drop interaction is defined by the
21417          * location of the cursor during the drag/drop
21418          * @property POINT
21419          * @type int
21420          * @static
21421          */
21422         POINT: 0,
21423
21424         /**
21425          * In intersect mode, drag and drop interactio nis defined by the
21426          * overlap of two or more drag and drop objects.
21427          * @property INTERSECT
21428          * @type int
21429          * @static
21430          */
21431         INTERSECT: 1,
21432
21433         /**
21434          * The current drag and drop mode.  Default: POINT
21435          * @property mode
21436          * @type int
21437          * @static
21438          */
21439         mode: 0,
21440
21441         /**
21442          * Runs method on all drag and drop objects
21443          * @method _execOnAll
21444          * @private
21445          * @static
21446          */
21447         _execOnAll: function(sMethod, args) {
21448             for (var i in this.ids) {
21449                 for (var j in this.ids[i]) {
21450                     var oDD = this.ids[i][j];
21451                     if (! this.isTypeOfDD(oDD)) {
21452                         continue;
21453                     }
21454                     oDD[sMethod].apply(oDD, args);
21455                 }
21456             }
21457         },
21458
21459         /**
21460          * Drag and drop initialization.  Sets up the global event handlers
21461          * @method _onLoad
21462          * @private
21463          * @static
21464          */
21465         _onLoad: function() {
21466
21467             this.init();
21468
21469             if (!Roo.isTouch) {
21470                 Event.on(document, "mouseup",   this.handleMouseUp, this, true);
21471                 Event.on(document, "mousemove", this.handleMouseMove, this, true);
21472             }
21473             Event.on(document, "touchend",   this.handleMouseUp, this, true);
21474             Event.on(document, "touchmove", this.handleMouseMove, this, true);
21475             
21476             Event.on(window,   "unload",    this._onUnload, this, true);
21477             Event.on(window,   "resize",    this._onResize, this, true);
21478             // Event.on(window,   "mouseout",    this._test);
21479
21480         },
21481
21482         /**
21483          * Reset constraints on all drag and drop objs
21484          * @method _onResize
21485          * @private
21486          * @static
21487          */
21488         _onResize: function(e) {
21489             this._execOnAll("resetConstraints", []);
21490         },
21491
21492         /**
21493          * Lock all drag and drop functionality
21494          * @method lock
21495          * @static
21496          */
21497         lock: function() { this.locked = true; },
21498
21499         /**
21500          * Unlock all drag and drop functionality
21501          * @method unlock
21502          * @static
21503          */
21504         unlock: function() { this.locked = false; },
21505
21506         /**
21507          * Is drag and drop locked?
21508          * @method isLocked
21509          * @return {boolean} True if drag and drop is locked, false otherwise.
21510          * @static
21511          */
21512         isLocked: function() { return this.locked; },
21513
21514         /**
21515          * Location cache that is set for all drag drop objects when a drag is
21516          * initiated, cleared when the drag is finished.
21517          * @property locationCache
21518          * @private
21519          * @static
21520          */
21521         locationCache: {},
21522
21523         /**
21524          * Set useCache to false if you want to force object the lookup of each
21525          * drag and drop linked element constantly during a drag.
21526          * @property useCache
21527          * @type boolean
21528          * @static
21529          */
21530         useCache: true,
21531
21532         /**
21533          * The number of pixels that the mouse needs to move after the
21534          * mousedown before the drag is initiated.  Default=3;
21535          * @property clickPixelThresh
21536          * @type int
21537          * @static
21538          */
21539         clickPixelThresh: 3,
21540
21541         /**
21542          * The number of milliseconds after the mousedown event to initiate the
21543          * drag if we don't get a mouseup event. Default=1000
21544          * @property clickTimeThresh
21545          * @type int
21546          * @static
21547          */
21548         clickTimeThresh: 350,
21549
21550         /**
21551          * Flag that indicates that either the drag pixel threshold or the
21552          * mousdown time threshold has been met
21553          * @property dragThreshMet
21554          * @type boolean
21555          * @private
21556          * @static
21557          */
21558         dragThreshMet: false,
21559
21560         /**
21561          * Timeout used for the click time threshold
21562          * @property clickTimeout
21563          * @type Object
21564          * @private
21565          * @static
21566          */
21567         clickTimeout: null,
21568
21569         /**
21570          * The X position of the mousedown event stored for later use when a
21571          * drag threshold is met.
21572          * @property startX
21573          * @type int
21574          * @private
21575          * @static
21576          */
21577         startX: 0,
21578
21579         /**
21580          * The Y position of the mousedown event stored for later use when a
21581          * drag threshold is met.
21582          * @property startY
21583          * @type int
21584          * @private
21585          * @static
21586          */
21587         startY: 0,
21588
21589         /**
21590          * Each DragDrop instance must be registered with the DragDropMgr.
21591          * This is executed in DragDrop.init()
21592          * @method regDragDrop
21593          * @param {DragDrop} oDD the DragDrop object to register
21594          * @param {String} sGroup the name of the group this element belongs to
21595          * @static
21596          */
21597         regDragDrop: function(oDD, sGroup) {
21598             if (!this.initialized) { this.init(); }
21599
21600             if (!this.ids[sGroup]) {
21601                 this.ids[sGroup] = {};
21602             }
21603             this.ids[sGroup][oDD.id] = oDD;
21604         },
21605
21606         /**
21607          * Removes the supplied dd instance from the supplied group. Executed
21608          * by DragDrop.removeFromGroup, so don't call this function directly.
21609          * @method removeDDFromGroup
21610          * @private
21611          * @static
21612          */
21613         removeDDFromGroup: function(oDD, sGroup) {
21614             if (!this.ids[sGroup]) {
21615                 this.ids[sGroup] = {};
21616             }
21617
21618             var obj = this.ids[sGroup];
21619             if (obj && obj[oDD.id]) {
21620                 delete obj[oDD.id];
21621             }
21622         },
21623
21624         /**
21625          * Unregisters a drag and drop item.  This is executed in
21626          * DragDrop.unreg, use that method instead of calling this directly.
21627          * @method _remove
21628          * @private
21629          * @static
21630          */
21631         _remove: function(oDD) {
21632             for (var g in oDD.groups) {
21633                 if (g && this.ids[g][oDD.id]) {
21634                     delete this.ids[g][oDD.id];
21635                 }
21636             }
21637             delete this.handleIds[oDD.id];
21638         },
21639
21640         /**
21641          * Each DragDrop handle element must be registered.  This is done
21642          * automatically when executing DragDrop.setHandleElId()
21643          * @method regHandle
21644          * @param {String} sDDId the DragDrop id this element is a handle for
21645          * @param {String} sHandleId the id of the element that is the drag
21646          * handle
21647          * @static
21648          */
21649         regHandle: function(sDDId, sHandleId) {
21650             if (!this.handleIds[sDDId]) {
21651                 this.handleIds[sDDId] = {};
21652             }
21653             this.handleIds[sDDId][sHandleId] = sHandleId;
21654         },
21655
21656         /**
21657          * Utility function to determine if a given element has been
21658          * registered as a drag drop item.
21659          * @method isDragDrop
21660          * @param {String} id the element id to check
21661          * @return {boolean} true if this element is a DragDrop item,
21662          * false otherwise
21663          * @static
21664          */
21665         isDragDrop: function(id) {
21666             return ( this.getDDById(id) ) ? true : false;
21667         },
21668
21669         /**
21670          * Returns the drag and drop instances that are in all groups the
21671          * passed in instance belongs to.
21672          * @method getRelated
21673          * @param {DragDrop} p_oDD the obj to get related data for
21674          * @param {boolean} bTargetsOnly if true, only return targetable objs
21675          * @return {DragDrop[]} the related instances
21676          * @static
21677          */
21678         getRelated: function(p_oDD, bTargetsOnly) {
21679             var oDDs = [];
21680             for (var i in p_oDD.groups) {
21681                 for (j in this.ids[i]) {
21682                     var dd = this.ids[i][j];
21683                     if (! this.isTypeOfDD(dd)) {
21684                         continue;
21685                     }
21686                     if (!bTargetsOnly || dd.isTarget) {
21687                         oDDs[oDDs.length] = dd;
21688                     }
21689                 }
21690             }
21691
21692             return oDDs;
21693         },
21694
21695         /**
21696          * Returns true if the specified dd target is a legal target for
21697          * the specifice drag obj
21698          * @method isLegalTarget
21699          * @param {DragDrop} the drag obj
21700          * @param {DragDrop} the target
21701          * @return {boolean} true if the target is a legal target for the
21702          * dd obj
21703          * @static
21704          */
21705         isLegalTarget: function (oDD, oTargetDD) {
21706             var targets = this.getRelated(oDD, true);
21707             for (var i=0, len=targets.length;i<len;++i) {
21708                 if (targets[i].id == oTargetDD.id) {
21709                     return true;
21710                 }
21711             }
21712
21713             return false;
21714         },
21715
21716         /**
21717          * My goal is to be able to transparently determine if an object is
21718          * typeof DragDrop, and the exact subclass of DragDrop.  typeof
21719          * returns "object", oDD.constructor.toString() always returns
21720          * "DragDrop" and not the name of the subclass.  So for now it just
21721          * evaluates a well-known variable in DragDrop.
21722          * @method isTypeOfDD
21723          * @param {Object} the object to evaluate
21724          * @return {boolean} true if typeof oDD = DragDrop
21725          * @static
21726          */
21727         isTypeOfDD: function (oDD) {
21728             return (oDD && oDD.__ygDragDrop);
21729         },
21730
21731         /**
21732          * Utility function to determine if a given element has been
21733          * registered as a drag drop handle for the given Drag Drop object.
21734          * @method isHandle
21735          * @param {String} id the element id to check
21736          * @return {boolean} true if this element is a DragDrop handle, false
21737          * otherwise
21738          * @static
21739          */
21740         isHandle: function(sDDId, sHandleId) {
21741             return ( this.handleIds[sDDId] &&
21742                             this.handleIds[sDDId][sHandleId] );
21743         },
21744
21745         /**
21746          * Returns the DragDrop instance for a given id
21747          * @method getDDById
21748          * @param {String} id the id of the DragDrop object
21749          * @return {DragDrop} the drag drop object, null if it is not found
21750          * @static
21751          */
21752         getDDById: function(id) {
21753             for (var i in this.ids) {
21754                 if (this.ids[i][id]) {
21755                     return this.ids[i][id];
21756                 }
21757             }
21758             return null;
21759         },
21760
21761         /**
21762          * Fired after a registered DragDrop object gets the mousedown event.
21763          * Sets up the events required to track the object being dragged
21764          * @method handleMouseDown
21765          * @param {Event} e the event
21766          * @param oDD the DragDrop object being dragged
21767          * @private
21768          * @static
21769          */
21770         handleMouseDown: function(e, oDD) {
21771             if(Roo.QuickTips){
21772                 Roo.QuickTips.disable();
21773             }
21774             this.currentTarget = e.getTarget();
21775
21776             this.dragCurrent = oDD;
21777
21778             var el = oDD.getEl();
21779
21780             // track start position
21781             this.startX = e.getPageX();
21782             this.startY = e.getPageY();
21783
21784             this.deltaX = this.startX - el.offsetLeft;
21785             this.deltaY = this.startY - el.offsetTop;
21786
21787             this.dragThreshMet = false;
21788
21789             this.clickTimeout = setTimeout(
21790                     function() {
21791                         var DDM = Roo.dd.DDM;
21792                         DDM.startDrag(DDM.startX, DDM.startY);
21793                     },
21794                     this.clickTimeThresh );
21795         },
21796
21797         /**
21798          * Fired when either the drag pixel threshol or the mousedown hold
21799          * time threshold has been met.
21800          * @method startDrag
21801          * @param x {int} the X position of the original mousedown
21802          * @param y {int} the Y position of the original mousedown
21803          * @static
21804          */
21805         startDrag: function(x, y) {
21806             clearTimeout(this.clickTimeout);
21807             if (this.dragCurrent) {
21808                 this.dragCurrent.b4StartDrag(x, y);
21809                 this.dragCurrent.startDrag(x, y);
21810             }
21811             this.dragThreshMet = true;
21812         },
21813
21814         /**
21815          * Internal function to handle the mouseup event.  Will be invoked
21816          * from the context of the document.
21817          * @method handleMouseUp
21818          * @param {Event} e the event
21819          * @private
21820          * @static
21821          */
21822         handleMouseUp: function(e) {
21823
21824             if(Roo.QuickTips){
21825                 Roo.QuickTips.enable();
21826             }
21827             if (! this.dragCurrent) {
21828                 return;
21829             }
21830
21831             clearTimeout(this.clickTimeout);
21832
21833             if (this.dragThreshMet) {
21834                 this.fireEvents(e, true);
21835             } else {
21836             }
21837
21838             this.stopDrag(e);
21839
21840             this.stopEvent(e);
21841         },
21842
21843         /**
21844          * Utility to stop event propagation and event default, if these
21845          * features are turned on.
21846          * @method stopEvent
21847          * @param {Event} e the event as returned by this.getEvent()
21848          * @static
21849          */
21850         stopEvent: function(e){
21851             if(this.stopPropagation) {
21852                 e.stopPropagation();
21853             }
21854
21855             if (this.preventDefault) {
21856                 e.preventDefault();
21857             }
21858         },
21859
21860         /**
21861          * Internal function to clean up event handlers after the drag
21862          * operation is complete
21863          * @method stopDrag
21864          * @param {Event} e the event
21865          * @private
21866          * @static
21867          */
21868         stopDrag: function(e) {
21869             // Fire the drag end event for the item that was dragged
21870             if (this.dragCurrent) {
21871                 if (this.dragThreshMet) {
21872                     this.dragCurrent.b4EndDrag(e);
21873                     this.dragCurrent.endDrag(e);
21874                 }
21875
21876                 this.dragCurrent.onMouseUp(e);
21877             }
21878
21879             this.dragCurrent = null;
21880             this.dragOvers = {};
21881         },
21882
21883         /**
21884          * Internal function to handle the mousemove event.  Will be invoked
21885          * from the context of the html element.
21886          *
21887          * @TODO figure out what we can do about mouse events lost when the
21888          * user drags objects beyond the window boundary.  Currently we can
21889          * detect this in internet explorer by verifying that the mouse is
21890          * down during the mousemove event.  Firefox doesn't give us the
21891          * button state on the mousemove event.
21892          * @method handleMouseMove
21893          * @param {Event} e the event
21894          * @private
21895          * @static
21896          */
21897         handleMouseMove: function(e) {
21898             if (! this.dragCurrent) {
21899                 return true;
21900             }
21901
21902             // var button = e.which || e.button;
21903
21904             // check for IE mouseup outside of page boundary
21905             if (Roo.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
21906                 this.stopEvent(e);
21907                 return this.handleMouseUp(e);
21908             }
21909
21910             if (!this.dragThreshMet) {
21911                 var diffX = Math.abs(this.startX - e.getPageX());
21912                 var diffY = Math.abs(this.startY - e.getPageY());
21913                 if (diffX > this.clickPixelThresh ||
21914                             diffY > this.clickPixelThresh) {
21915                     this.startDrag(this.startX, this.startY);
21916                 }
21917             }
21918
21919             if (this.dragThreshMet) {
21920                 this.dragCurrent.b4Drag(e);
21921                 this.dragCurrent.onDrag(e);
21922                 if(!this.dragCurrent.moveOnly){
21923                     this.fireEvents(e, false);
21924                 }
21925             }
21926
21927             this.stopEvent(e);
21928
21929             return true;
21930         },
21931
21932         /**
21933          * Iterates over all of the DragDrop elements to find ones we are
21934          * hovering over or dropping on
21935          * @method fireEvents
21936          * @param {Event} e the event
21937          * @param {boolean} isDrop is this a drop op or a mouseover op?
21938          * @private
21939          * @static
21940          */
21941         fireEvents: function(e, isDrop) {
21942             var dc = this.dragCurrent;
21943
21944             // If the user did the mouse up outside of the window, we could
21945             // get here even though we have ended the drag.
21946             if (!dc || dc.isLocked()) {
21947                 return;
21948             }
21949
21950             var pt = e.getPoint();
21951
21952             // cache the previous dragOver array
21953             var oldOvers = [];
21954
21955             var outEvts   = [];
21956             var overEvts  = [];
21957             var dropEvts  = [];
21958             var enterEvts = [];
21959
21960             // Check to see if the object(s) we were hovering over is no longer
21961             // being hovered over so we can fire the onDragOut event
21962             for (var i in this.dragOvers) {
21963
21964                 var ddo = this.dragOvers[i];
21965
21966                 if (! this.isTypeOfDD(ddo)) {
21967                     continue;
21968                 }
21969
21970                 if (! this.isOverTarget(pt, ddo, this.mode)) {
21971                     outEvts.push( ddo );
21972                 }
21973
21974                 oldOvers[i] = true;
21975                 delete this.dragOvers[i];
21976             }
21977
21978             for (var sGroup in dc.groups) {
21979
21980                 if ("string" != typeof sGroup) {
21981                     continue;
21982                 }
21983
21984                 for (i in this.ids[sGroup]) {
21985                     var oDD = this.ids[sGroup][i];
21986                     if (! this.isTypeOfDD(oDD)) {
21987                         continue;
21988                     }
21989
21990                     if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
21991                         if (this.isOverTarget(pt, oDD, this.mode)) {
21992                             // look for drop interactions
21993                             if (isDrop) {
21994                                 dropEvts.push( oDD );
21995                             // look for drag enter and drag over interactions
21996                             } else {
21997
21998                                 // initial drag over: dragEnter fires
21999                                 if (!oldOvers[oDD.id]) {
22000                                     enterEvts.push( oDD );
22001                                 // subsequent drag overs: dragOver fires
22002                                 } else {
22003                                     overEvts.push( oDD );
22004                                 }
22005
22006                                 this.dragOvers[oDD.id] = oDD;
22007                             }
22008                         }
22009                     }
22010                 }
22011             }
22012
22013             if (this.mode) {
22014                 if (outEvts.length) {
22015                     dc.b4DragOut(e, outEvts);
22016                     dc.onDragOut(e, outEvts);
22017                 }
22018
22019                 if (enterEvts.length) {
22020                     dc.onDragEnter(e, enterEvts);
22021                 }
22022
22023                 if (overEvts.length) {
22024                     dc.b4DragOver(e, overEvts);
22025                     dc.onDragOver(e, overEvts);
22026                 }
22027
22028                 if (dropEvts.length) {
22029                     dc.b4DragDrop(e, dropEvts);
22030                     dc.onDragDrop(e, dropEvts);
22031                 }
22032
22033             } else {
22034                 // fire dragout events
22035                 var len = 0;
22036                 for (i=0, len=outEvts.length; i<len; ++i) {
22037                     dc.b4DragOut(e, outEvts[i].id);
22038                     dc.onDragOut(e, outEvts[i].id);
22039                 }
22040
22041                 // fire enter events
22042                 for (i=0,len=enterEvts.length; i<len; ++i) {
22043                     // dc.b4DragEnter(e, oDD.id);
22044                     dc.onDragEnter(e, enterEvts[i].id);
22045                 }
22046
22047                 // fire over events
22048                 for (i=0,len=overEvts.length; i<len; ++i) {
22049                     dc.b4DragOver(e, overEvts[i].id);
22050                     dc.onDragOver(e, overEvts[i].id);
22051                 }
22052
22053                 // fire drop events
22054                 for (i=0, len=dropEvts.length; i<len; ++i) {
22055                     dc.b4DragDrop(e, dropEvts[i].id);
22056                     dc.onDragDrop(e, dropEvts[i].id);
22057                 }
22058
22059             }
22060
22061             // notify about a drop that did not find a target
22062             if (isDrop && !dropEvts.length) {
22063                 dc.onInvalidDrop(e);
22064             }
22065
22066         },
22067
22068         /**
22069          * Helper function for getting the best match from the list of drag
22070          * and drop objects returned by the drag and drop events when we are
22071          * in INTERSECT mode.  It returns either the first object that the
22072          * cursor is over, or the object that has the greatest overlap with
22073          * the dragged element.
22074          * @method getBestMatch
22075          * @param  {DragDrop[]} dds The array of drag and drop objects
22076          * targeted
22077          * @return {DragDrop}       The best single match
22078          * @static
22079          */
22080         getBestMatch: function(dds) {
22081             var winner = null;
22082             // Return null if the input is not what we expect
22083             //if (!dds || !dds.length || dds.length == 0) {
22084                // winner = null;
22085             // If there is only one item, it wins
22086             //} else if (dds.length == 1) {
22087
22088             var len = dds.length;
22089
22090             if (len == 1) {
22091                 winner = dds[0];
22092             } else {
22093                 // Loop through the targeted items
22094                 for (var i=0; i<len; ++i) {
22095                     var dd = dds[i];
22096                     // If the cursor is over the object, it wins.  If the
22097                     // cursor is over multiple matches, the first one we come
22098                     // to wins.
22099                     if (dd.cursorIsOver) {
22100                         winner = dd;
22101                         break;
22102                     // Otherwise the object with the most overlap wins
22103                     } else {
22104                         if (!winner ||
22105                             winner.overlap.getArea() < dd.overlap.getArea()) {
22106                             winner = dd;
22107                         }
22108                     }
22109                 }
22110             }
22111
22112             return winner;
22113         },
22114
22115         /**
22116          * Refreshes the cache of the top-left and bottom-right points of the
22117          * drag and drop objects in the specified group(s).  This is in the
22118          * format that is stored in the drag and drop instance, so typical
22119          * usage is:
22120          * <code>
22121          * Roo.dd.DragDropMgr.refreshCache(ddinstance.groups);
22122          * </code>
22123          * Alternatively:
22124          * <code>
22125          * Roo.dd.DragDropMgr.refreshCache({group1:true, group2:true});
22126          * </code>
22127          * @TODO this really should be an indexed array.  Alternatively this
22128          * method could accept both.
22129          * @method refreshCache
22130          * @param {Object} groups an associative array of groups to refresh
22131          * @static
22132          */
22133         refreshCache: function(groups) {
22134             for (var sGroup in groups) {
22135                 if ("string" != typeof sGroup) {
22136                     continue;
22137                 }
22138                 for (var i in this.ids[sGroup]) {
22139                     var oDD = this.ids[sGroup][i];
22140
22141                     if (this.isTypeOfDD(oDD)) {
22142                     // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
22143                         var loc = this.getLocation(oDD);
22144                         if (loc) {
22145                             this.locationCache[oDD.id] = loc;
22146                         } else {
22147                             delete this.locationCache[oDD.id];
22148                             // this will unregister the drag and drop object if
22149                             // the element is not in a usable state
22150                             // oDD.unreg();
22151                         }
22152                     }
22153                 }
22154             }
22155         },
22156
22157         /**
22158          * This checks to make sure an element exists and is in the DOM.  The
22159          * main purpose is to handle cases where innerHTML is used to remove
22160          * drag and drop objects from the DOM.  IE provides an 'unspecified
22161          * error' when trying to access the offsetParent of such an element
22162          * @method verifyEl
22163          * @param {HTMLElement} el the element to check
22164          * @return {boolean} true if the element looks usable
22165          * @static
22166          */
22167         verifyEl: function(el) {
22168             if (el) {
22169                 var parent;
22170                 if(Roo.isIE){
22171                     try{
22172                         parent = el.offsetParent;
22173                     }catch(e){}
22174                 }else{
22175                     parent = el.offsetParent;
22176                 }
22177                 if (parent) {
22178                     return true;
22179                 }
22180             }
22181
22182             return false;
22183         },
22184
22185         /**
22186          * Returns a Region object containing the drag and drop element's position
22187          * and size, including the padding configured for it
22188          * @method getLocation
22189          * @param {DragDrop} oDD the drag and drop object to get the
22190          *                       location for
22191          * @return {Roo.lib.Region} a Region object representing the total area
22192          *                             the element occupies, including any padding
22193          *                             the instance is configured for.
22194          * @static
22195          */
22196         getLocation: function(oDD) {
22197             if (! this.isTypeOfDD(oDD)) {
22198                 return null;
22199             }
22200
22201             var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
22202
22203             try {
22204                 pos= Roo.lib.Dom.getXY(el);
22205             } catch (e) { }
22206
22207             if (!pos) {
22208                 return null;
22209             }
22210
22211             x1 = pos[0];
22212             x2 = x1 + el.offsetWidth;
22213             y1 = pos[1];
22214             y2 = y1 + el.offsetHeight;
22215
22216             t = y1 - oDD.padding[0];
22217             r = x2 + oDD.padding[1];
22218             b = y2 + oDD.padding[2];
22219             l = x1 - oDD.padding[3];
22220
22221             return new Roo.lib.Region( t, r, b, l );
22222         },
22223
22224         /**
22225          * Checks the cursor location to see if it over the target
22226          * @method isOverTarget
22227          * @param {Roo.lib.Point} pt The point to evaluate
22228          * @param {DragDrop} oTarget the DragDrop object we are inspecting
22229          * @return {boolean} true if the mouse is over the target
22230          * @private
22231          * @static
22232          */
22233         isOverTarget: function(pt, oTarget, intersect) {
22234             // use cache if available
22235             var loc = this.locationCache[oTarget.id];
22236             if (!loc || !this.useCache) {
22237                 loc = this.getLocation(oTarget);
22238                 this.locationCache[oTarget.id] = loc;
22239
22240             }
22241
22242             if (!loc) {
22243                 return false;
22244             }
22245
22246             oTarget.cursorIsOver = loc.contains( pt );
22247
22248             // DragDrop is using this as a sanity check for the initial mousedown
22249             // in this case we are done.  In POINT mode, if the drag obj has no
22250             // contraints, we are also done. Otherwise we need to evaluate the
22251             // location of the target as related to the actual location of the
22252             // dragged element.
22253             var dc = this.dragCurrent;
22254             if (!dc || !dc.getTargetCoord ||
22255                     (!intersect && !dc.constrainX && !dc.constrainY)) {
22256                 return oTarget.cursorIsOver;
22257             }
22258
22259             oTarget.overlap = null;
22260
22261             // Get the current location of the drag element, this is the
22262             // location of the mouse event less the delta that represents
22263             // where the original mousedown happened on the element.  We
22264             // need to consider constraints and ticks as well.
22265             var pos = dc.getTargetCoord(pt.x, pt.y);
22266
22267             var el = dc.getDragEl();
22268             var curRegion = new Roo.lib.Region( pos.y,
22269                                                    pos.x + el.offsetWidth,
22270                                                    pos.y + el.offsetHeight,
22271                                                    pos.x );
22272
22273             var overlap = curRegion.intersect(loc);
22274
22275             if (overlap) {
22276                 oTarget.overlap = overlap;
22277                 return (intersect) ? true : oTarget.cursorIsOver;
22278             } else {
22279                 return false;
22280             }
22281         },
22282
22283         /**
22284          * unload event handler
22285          * @method _onUnload
22286          * @private
22287          * @static
22288          */
22289         _onUnload: function(e, me) {
22290             Roo.dd.DragDropMgr.unregAll();
22291         },
22292
22293         /**
22294          * Cleans up the drag and drop events and objects.
22295          * @method unregAll
22296          * @private
22297          * @static
22298          */
22299         unregAll: function() {
22300
22301             if (this.dragCurrent) {
22302                 this.stopDrag();
22303                 this.dragCurrent = null;
22304             }
22305
22306             this._execOnAll("unreg", []);
22307
22308             for (i in this.elementCache) {
22309                 delete this.elementCache[i];
22310             }
22311
22312             this.elementCache = {};
22313             this.ids = {};
22314         },
22315
22316         /**
22317          * A cache of DOM elements
22318          * @property elementCache
22319          * @private
22320          * @static
22321          */
22322         elementCache: {},
22323
22324         /**
22325          * Get the wrapper for the DOM element specified
22326          * @method getElWrapper
22327          * @param {String} id the id of the element to get
22328          * @return {Roo.dd.DDM.ElementWrapper} the wrapped element
22329          * @private
22330          * @deprecated This wrapper isn't that useful
22331          * @static
22332          */
22333         getElWrapper: function(id) {
22334             var oWrapper = this.elementCache[id];
22335             if (!oWrapper || !oWrapper.el) {
22336                 oWrapper = this.elementCache[id] =
22337                     new this.ElementWrapper(Roo.getDom(id));
22338             }
22339             return oWrapper;
22340         },
22341
22342         /**
22343          * Returns the actual DOM element
22344          * @method getElement
22345          * @param {String} id the id of the elment to get
22346          * @return {Object} The element
22347          * @deprecated use Roo.getDom instead
22348          * @static
22349          */
22350         getElement: function(id) {
22351             return Roo.getDom(id);
22352         },
22353
22354         /**
22355          * Returns the style property for the DOM element (i.e.,
22356          * document.getElById(id).style)
22357          * @method getCss
22358          * @param {String} id the id of the elment to get
22359          * @return {Object} The style property of the element
22360          * @deprecated use Roo.getDom instead
22361          * @static
22362          */
22363         getCss: function(id) {
22364             var el = Roo.getDom(id);
22365             return (el) ? el.style : null;
22366         },
22367
22368         /**
22369          * Inner class for cached elements
22370          * @class DragDropMgr.ElementWrapper
22371          * @for DragDropMgr
22372          * @private
22373          * @deprecated
22374          */
22375         ElementWrapper: function(el) {
22376                 /**
22377                  * The element
22378                  * @property el
22379                  */
22380                 this.el = el || null;
22381                 /**
22382                  * The element id
22383                  * @property id
22384                  */
22385                 this.id = this.el && el.id;
22386                 /**
22387                  * A reference to the style property
22388                  * @property css
22389                  */
22390                 this.css = this.el && el.style;
22391             },
22392
22393         /**
22394          * Returns the X position of an html element
22395          * @method getPosX
22396          * @param el the element for which to get the position
22397          * @return {int} the X coordinate
22398          * @for DragDropMgr
22399          * @deprecated use Roo.lib.Dom.getX instead
22400          * @static
22401          */
22402         getPosX: function(el) {
22403             return Roo.lib.Dom.getX(el);
22404         },
22405
22406         /**
22407          * Returns the Y position of an html element
22408          * @method getPosY
22409          * @param el the element for which to get the position
22410          * @return {int} the Y coordinate
22411          * @deprecated use Roo.lib.Dom.getY instead
22412          * @static
22413          */
22414         getPosY: function(el) {
22415             return Roo.lib.Dom.getY(el);
22416         },
22417
22418         /**
22419          * Swap two nodes.  In IE, we use the native method, for others we
22420          * emulate the IE behavior
22421          * @method swapNode
22422          * @param n1 the first node to swap
22423          * @param n2 the other node to swap
22424          * @static
22425          */
22426         swapNode: function(n1, n2) {
22427             if (n1.swapNode) {
22428                 n1.swapNode(n2);
22429             } else {
22430                 var p = n2.parentNode;
22431                 var s = n2.nextSibling;
22432
22433                 if (s == n1) {
22434                     p.insertBefore(n1, n2);
22435                 } else if (n2 == n1.nextSibling) {
22436                     p.insertBefore(n2, n1);
22437                 } else {
22438                     n1.parentNode.replaceChild(n2, n1);
22439                     p.insertBefore(n1, s);
22440                 }
22441             }
22442         },
22443
22444         /**
22445          * Returns the current scroll position
22446          * @method getScroll
22447          * @private
22448          * @static
22449          */
22450         getScroll: function () {
22451             var t, l, dde=document.documentElement, db=document.body;
22452             if (dde && (dde.scrollTop || dde.scrollLeft)) {
22453                 t = dde.scrollTop;
22454                 l = dde.scrollLeft;
22455             } else if (db) {
22456                 t = db.scrollTop;
22457                 l = db.scrollLeft;
22458             } else {
22459
22460             }
22461             return { top: t, left: l };
22462         },
22463
22464         /**
22465          * Returns the specified element style property
22466          * @method getStyle
22467          * @param {HTMLElement} el          the element
22468          * @param {string}      styleProp   the style property
22469          * @return {string} The value of the style property
22470          * @deprecated use Roo.lib.Dom.getStyle
22471          * @static
22472          */
22473         getStyle: function(el, styleProp) {
22474             return Roo.fly(el).getStyle(styleProp);
22475         },
22476
22477         /**
22478          * Gets the scrollTop
22479          * @method getScrollTop
22480          * @return {int} the document's scrollTop
22481          * @static
22482          */
22483         getScrollTop: function () { return this.getScroll().top; },
22484
22485         /**
22486          * Gets the scrollLeft
22487          * @method getScrollLeft
22488          * @return {int} the document's scrollTop
22489          * @static
22490          */
22491         getScrollLeft: function () { return this.getScroll().left; },
22492
22493         /**
22494          * Sets the x/y position of an element to the location of the
22495          * target element.
22496          * @method moveToEl
22497          * @param {HTMLElement} moveEl      The element to move
22498          * @param {HTMLElement} targetEl    The position reference element
22499          * @static
22500          */
22501         moveToEl: function (moveEl, targetEl) {
22502             var aCoord = Roo.lib.Dom.getXY(targetEl);
22503             Roo.lib.Dom.setXY(moveEl, aCoord);
22504         },
22505
22506         /**
22507          * Numeric array sort function
22508          * @method numericSort
22509          * @static
22510          */
22511         numericSort: function(a, b) { return (a - b); },
22512
22513         /**
22514          * Internal counter
22515          * @property _timeoutCount
22516          * @private
22517          * @static
22518          */
22519         _timeoutCount: 0,
22520
22521         /**
22522          * Trying to make the load order less important.  Without this we get
22523          * an error if this file is loaded before the Event Utility.
22524          * @method _addListeners
22525          * @private
22526          * @static
22527          */
22528         _addListeners: function() {
22529             var DDM = Roo.dd.DDM;
22530             if ( Roo.lib.Event && document ) {
22531                 DDM._onLoad();
22532             } else {
22533                 if (DDM._timeoutCount > 2000) {
22534                 } else {
22535                     setTimeout(DDM._addListeners, 10);
22536                     if (document && document.body) {
22537                         DDM._timeoutCount += 1;
22538                     }
22539                 }
22540             }
22541         },
22542
22543         /**
22544          * Recursively searches the immediate parent and all child nodes for
22545          * the handle element in order to determine wheter or not it was
22546          * clicked.
22547          * @method handleWasClicked
22548          * @param node the html element to inspect
22549          * @static
22550          */
22551         handleWasClicked: function(node, id) {
22552             if (this.isHandle(id, node.id)) {
22553                 return true;
22554             } else {
22555                 // check to see if this is a text node child of the one we want
22556                 var p = node.parentNode;
22557
22558                 while (p) {
22559                     if (this.isHandle(id, p.id)) {
22560                         return true;
22561                     } else {
22562                         p = p.parentNode;
22563                     }
22564                 }
22565             }
22566
22567             return false;
22568         }
22569
22570     };
22571
22572 }();
22573
22574 // shorter alias, save a few bytes
22575 Roo.dd.DDM = Roo.dd.DragDropMgr;
22576 Roo.dd.DDM._addListeners();
22577
22578 }/*
22579  * Based on:
22580  * Ext JS Library 1.1.1
22581  * Copyright(c) 2006-2007, Ext JS, LLC.
22582  *
22583  * Originally Released Under LGPL - original licence link has changed is not relivant.
22584  *
22585  * Fork - LGPL
22586  * <script type="text/javascript">
22587  */
22588
22589 /**
22590  * @class Roo.dd.DD
22591  * A DragDrop implementation where the linked element follows the
22592  * mouse cursor during a drag.
22593  * @extends Roo.dd.DragDrop
22594  * @constructor
22595  * @param {String} id the id of the linked element
22596  * @param {String} sGroup the group of related DragDrop items
22597  * @param {object} config an object containing configurable attributes
22598  *                Valid properties for DD:
22599  *                    scroll
22600  */
22601 Roo.dd.DD = function(id, sGroup, config) {
22602     if (id) {
22603         this.init(id, sGroup, config);
22604     }
22605 };
22606
22607 Roo.extend(Roo.dd.DD, Roo.dd.DragDrop, {
22608
22609     /**
22610      * When set to true, the utility automatically tries to scroll the browser
22611      * window wehn a drag and drop element is dragged near the viewport boundary.
22612      * Defaults to true.
22613      * @property scroll
22614      * @type boolean
22615      */
22616     scroll: true,
22617
22618     /**
22619      * Sets the pointer offset to the distance between the linked element's top
22620      * left corner and the location the element was clicked
22621      * @method autoOffset
22622      * @param {int} iPageX the X coordinate of the click
22623      * @param {int} iPageY the Y coordinate of the click
22624      */
22625     autoOffset: function(iPageX, iPageY) {
22626         var x = iPageX - this.startPageX;
22627         var y = iPageY - this.startPageY;
22628         this.setDelta(x, y);
22629     },
22630
22631     /**
22632      * Sets the pointer offset.  You can call this directly to force the
22633      * offset to be in a particular location (e.g., pass in 0,0 to set it
22634      * to the center of the object)
22635      * @method setDelta
22636      * @param {int} iDeltaX the distance from the left
22637      * @param {int} iDeltaY the distance from the top
22638      */
22639     setDelta: function(iDeltaX, iDeltaY) {
22640         this.deltaX = iDeltaX;
22641         this.deltaY = iDeltaY;
22642     },
22643
22644     /**
22645      * Sets the drag element to the location of the mousedown or click event,
22646      * maintaining the cursor location relative to the location on the element
22647      * that was clicked.  Override this if you want to place the element in a
22648      * location other than where the cursor is.
22649      * @method setDragElPos
22650      * @param {int} iPageX the X coordinate of the mousedown or drag event
22651      * @param {int} iPageY the Y coordinate of the mousedown or drag event
22652      */
22653     setDragElPos: function(iPageX, iPageY) {
22654         // the first time we do this, we are going to check to make sure
22655         // the element has css positioning
22656
22657         var el = this.getDragEl();
22658         this.alignElWithMouse(el, iPageX, iPageY);
22659     },
22660
22661     /**
22662      * Sets the element to the location of the mousedown or click event,
22663      * maintaining the cursor location relative to the location on the element
22664      * that was clicked.  Override this if you want to place the element in a
22665      * location other than where the cursor is.
22666      * @method alignElWithMouse
22667      * @param {HTMLElement} el the element to move
22668      * @param {int} iPageX the X coordinate of the mousedown or drag event
22669      * @param {int} iPageY the Y coordinate of the mousedown or drag event
22670      */
22671     alignElWithMouse: function(el, iPageX, iPageY) {
22672         var oCoord = this.getTargetCoord(iPageX, iPageY);
22673         var fly = el.dom ? el : Roo.fly(el);
22674         if (!this.deltaSetXY) {
22675             var aCoord = [oCoord.x, oCoord.y];
22676             fly.setXY(aCoord);
22677             var newLeft = fly.getLeft(true);
22678             var newTop  = fly.getTop(true);
22679             this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
22680         } else {
22681             fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
22682         }
22683
22684         this.cachePosition(oCoord.x, oCoord.y);
22685         this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
22686         return oCoord;
22687     },
22688
22689     /**
22690      * Saves the most recent position so that we can reset the constraints and
22691      * tick marks on-demand.  We need to know this so that we can calculate the
22692      * number of pixels the element is offset from its original position.
22693      * @method cachePosition
22694      * @param iPageX the current x position (optional, this just makes it so we
22695      * don't have to look it up again)
22696      * @param iPageY the current y position (optional, this just makes it so we
22697      * don't have to look it up again)
22698      */
22699     cachePosition: function(iPageX, iPageY) {
22700         if (iPageX) {
22701             this.lastPageX = iPageX;
22702             this.lastPageY = iPageY;
22703         } else {
22704             var aCoord = Roo.lib.Dom.getXY(this.getEl());
22705             this.lastPageX = aCoord[0];
22706             this.lastPageY = aCoord[1];
22707         }
22708     },
22709
22710     /**
22711      * Auto-scroll the window if the dragged object has been moved beyond the
22712      * visible window boundary.
22713      * @method autoScroll
22714      * @param {int} x the drag element's x position
22715      * @param {int} y the drag element's y position
22716      * @param {int} h the height of the drag element
22717      * @param {int} w the width of the drag element
22718      * @private
22719      */
22720     autoScroll: function(x, y, h, w) {
22721
22722         if (this.scroll) {
22723             // The client height
22724             var clientH = Roo.lib.Dom.getViewWidth();
22725
22726             // The client width
22727             var clientW = Roo.lib.Dom.getViewHeight();
22728
22729             // The amt scrolled down
22730             var st = this.DDM.getScrollTop();
22731
22732             // The amt scrolled right
22733             var sl = this.DDM.getScrollLeft();
22734
22735             // Location of the bottom of the element
22736             var bot = h + y;
22737
22738             // Location of the right of the element
22739             var right = w + x;
22740
22741             // The distance from the cursor to the bottom of the visible area,
22742             // adjusted so that we don't scroll if the cursor is beyond the
22743             // element drag constraints
22744             var toBot = (clientH + st - y - this.deltaY);
22745
22746             // The distance from the cursor to the right of the visible area
22747             var toRight = (clientW + sl - x - this.deltaX);
22748
22749
22750             // How close to the edge the cursor must be before we scroll
22751             // var thresh = (document.all) ? 100 : 40;
22752             var thresh = 40;
22753
22754             // How many pixels to scroll per autoscroll op.  This helps to reduce
22755             // clunky scrolling. IE is more sensitive about this ... it needs this
22756             // value to be higher.
22757             var scrAmt = (document.all) ? 80 : 30;
22758
22759             // Scroll down if we are near the bottom of the visible page and the
22760             // obj extends below the crease
22761             if ( bot > clientH && toBot < thresh ) {
22762                 window.scrollTo(sl, st + scrAmt);
22763             }
22764
22765             // Scroll up if the window is scrolled down and the top of the object
22766             // goes above the top border
22767             if ( y < st && st > 0 && y - st < thresh ) {
22768                 window.scrollTo(sl, st - scrAmt);
22769             }
22770
22771             // Scroll right if the obj is beyond the right border and the cursor is
22772             // near the border.
22773             if ( right > clientW && toRight < thresh ) {
22774                 window.scrollTo(sl + scrAmt, st);
22775             }
22776
22777             // Scroll left if the window has been scrolled to the right and the obj
22778             // extends past the left border
22779             if ( x < sl && sl > 0 && x - sl < thresh ) {
22780                 window.scrollTo(sl - scrAmt, st);
22781             }
22782         }
22783     },
22784
22785     /**
22786      * Finds the location the element should be placed if we want to move
22787      * it to where the mouse location less the click offset would place us.
22788      * @method getTargetCoord
22789      * @param {int} iPageX the X coordinate of the click
22790      * @param {int} iPageY the Y coordinate of the click
22791      * @return an object that contains the coordinates (Object.x and Object.y)
22792      * @private
22793      */
22794     getTargetCoord: function(iPageX, iPageY) {
22795
22796
22797         var x = iPageX - this.deltaX;
22798         var y = iPageY - this.deltaY;
22799
22800         if (this.constrainX) {
22801             if (x < this.minX) { x = this.minX; }
22802             if (x > this.maxX) { x = this.maxX; }
22803         }
22804
22805         if (this.constrainY) {
22806             if (y < this.minY) { y = this.minY; }
22807             if (y > this.maxY) { y = this.maxY; }
22808         }
22809
22810         x = this.getTick(x, this.xTicks);
22811         y = this.getTick(y, this.yTicks);
22812
22813
22814         return {x:x, y:y};
22815     },
22816
22817     /*
22818      * Sets up config options specific to this class. Overrides
22819      * Roo.dd.DragDrop, but all versions of this method through the
22820      * inheritance chain are called
22821      */
22822     applyConfig: function() {
22823         Roo.dd.DD.superclass.applyConfig.call(this);
22824         this.scroll = (this.config.scroll !== false);
22825     },
22826
22827     /*
22828      * Event that fires prior to the onMouseDown event.  Overrides
22829      * Roo.dd.DragDrop.
22830      */
22831     b4MouseDown: function(e) {
22832         // this.resetConstraints();
22833         this.autoOffset(e.getPageX(),
22834                             e.getPageY());
22835     },
22836
22837     /*
22838      * Event that fires prior to the onDrag event.  Overrides
22839      * Roo.dd.DragDrop.
22840      */
22841     b4Drag: function(e) {
22842         this.setDragElPos(e.getPageX(),
22843                             e.getPageY());
22844     },
22845
22846     toString: function() {
22847         return ("DD " + this.id);
22848     }
22849
22850     //////////////////////////////////////////////////////////////////////////
22851     // Debugging ygDragDrop events that can be overridden
22852     //////////////////////////////////////////////////////////////////////////
22853     /*
22854     startDrag: function(x, y) {
22855     },
22856
22857     onDrag: function(e) {
22858     },
22859
22860     onDragEnter: function(e, id) {
22861     },
22862
22863     onDragOver: function(e, id) {
22864     },
22865
22866     onDragOut: function(e, id) {
22867     },
22868
22869     onDragDrop: function(e, id) {
22870     },
22871
22872     endDrag: function(e) {
22873     }
22874
22875     */
22876
22877 });/*
22878  * Based on:
22879  * Ext JS Library 1.1.1
22880  * Copyright(c) 2006-2007, Ext JS, LLC.
22881  *
22882  * Originally Released Under LGPL - original licence link has changed is not relivant.
22883  *
22884  * Fork - LGPL
22885  * <script type="text/javascript">
22886  */
22887
22888 /**
22889  * @class Roo.dd.DDProxy
22890  * A DragDrop implementation that inserts an empty, bordered div into
22891  * the document that follows the cursor during drag operations.  At the time of
22892  * the click, the frame div is resized to the dimensions of the linked html
22893  * element, and moved to the exact location of the linked element.
22894  *
22895  * References to the "frame" element refer to the single proxy element that
22896  * was created to be dragged in place of all DDProxy elements on the
22897  * page.
22898  *
22899  * @extends Roo.dd.DD
22900  * @constructor
22901  * @param {String} id the id of the linked html element
22902  * @param {String} sGroup the group of related DragDrop objects
22903  * @param {object} config an object containing configurable attributes
22904  *                Valid properties for DDProxy in addition to those in DragDrop:
22905  *                   resizeFrame, centerFrame, dragElId
22906  */
22907 Roo.dd.DDProxy = function(id, sGroup, config) {
22908     if (id) {
22909         this.init(id, sGroup, config);
22910         this.initFrame();
22911     }
22912 };
22913
22914 /**
22915  * The default drag frame div id
22916  * @property Roo.dd.DDProxy.dragElId
22917  * @type String
22918  * @static
22919  */
22920 Roo.dd.DDProxy.dragElId = "ygddfdiv";
22921
22922 Roo.extend(Roo.dd.DDProxy, Roo.dd.DD, {
22923
22924     /**
22925      * By default we resize the drag frame to be the same size as the element
22926      * we want to drag (this is to get the frame effect).  We can turn it off
22927      * if we want a different behavior.
22928      * @property resizeFrame
22929      * @type boolean
22930      */
22931     resizeFrame: true,
22932
22933     /**
22934      * By default the frame is positioned exactly where the drag element is, so
22935      * we use the cursor offset provided by Roo.dd.DD.  Another option that works only if
22936      * you do not have constraints on the obj is to have the drag frame centered
22937      * around the cursor.  Set centerFrame to true for this effect.
22938      * @property centerFrame
22939      * @type boolean
22940      */
22941     centerFrame: false,
22942
22943     /**
22944      * Creates the proxy element if it does not yet exist
22945      * @method createFrame
22946      */
22947     createFrame: function() {
22948         var self = this;
22949         var body = document.body;
22950
22951         if (!body || !body.firstChild) {
22952             setTimeout( function() { self.createFrame(); }, 50 );
22953             return;
22954         }
22955
22956         var div = this.getDragEl();
22957
22958         if (!div) {
22959             div    = document.createElement("div");
22960             div.id = this.dragElId;
22961             var s  = div.style;
22962
22963             s.position   = "absolute";
22964             s.visibility = "hidden";
22965             s.cursor     = "move";
22966             s.border     = "2px solid #aaa";
22967             s.zIndex     = 999;
22968
22969             // appendChild can blow up IE if invoked prior to the window load event
22970             // while rendering a table.  It is possible there are other scenarios
22971             // that would cause this to happen as well.
22972             body.insertBefore(div, body.firstChild);
22973         }
22974     },
22975
22976     /**
22977      * Initialization for the drag frame element.  Must be called in the
22978      * constructor of all subclasses
22979      * @method initFrame
22980      */
22981     initFrame: function() {
22982         this.createFrame();
22983     },
22984
22985     applyConfig: function() {
22986         Roo.dd.DDProxy.superclass.applyConfig.call(this);
22987
22988         this.resizeFrame = (this.config.resizeFrame !== false);
22989         this.centerFrame = (this.config.centerFrame);
22990         this.setDragElId(this.config.dragElId || Roo.dd.DDProxy.dragElId);
22991     },
22992
22993     /**
22994      * Resizes the drag frame to the dimensions of the clicked object, positions
22995      * it over the object, and finally displays it
22996      * @method showFrame
22997      * @param {int} iPageX X click position
22998      * @param {int} iPageY Y click position
22999      * @private
23000      */
23001     showFrame: function(iPageX, iPageY) {
23002         var el = this.getEl();
23003         var dragEl = this.getDragEl();
23004         var s = dragEl.style;
23005
23006         this._resizeProxy();
23007
23008         if (this.centerFrame) {
23009             this.setDelta( Math.round(parseInt(s.width,  10)/2),
23010                            Math.round(parseInt(s.height, 10)/2) );
23011         }
23012
23013         this.setDragElPos(iPageX, iPageY);
23014
23015         Roo.fly(dragEl).show();
23016     },
23017
23018     /**
23019      * The proxy is automatically resized to the dimensions of the linked
23020      * element when a drag is initiated, unless resizeFrame is set to false
23021      * @method _resizeProxy
23022      * @private
23023      */
23024     _resizeProxy: function() {
23025         if (this.resizeFrame) {
23026             var el = this.getEl();
23027             Roo.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
23028         }
23029     },
23030
23031     // overrides Roo.dd.DragDrop
23032     b4MouseDown: function(e) {
23033         var x = e.getPageX();
23034         var y = e.getPageY();
23035         this.autoOffset(x, y);
23036         this.setDragElPos(x, y);
23037     },
23038
23039     // overrides Roo.dd.DragDrop
23040     b4StartDrag: function(x, y) {
23041         // show the drag frame
23042         this.showFrame(x, y);
23043     },
23044
23045     // overrides Roo.dd.DragDrop
23046     b4EndDrag: function(e) {
23047         Roo.fly(this.getDragEl()).hide();
23048     },
23049
23050     // overrides Roo.dd.DragDrop
23051     // By default we try to move the element to the last location of the frame.
23052     // This is so that the default behavior mirrors that of Roo.dd.DD.
23053     endDrag: function(e) {
23054
23055         var lel = this.getEl();
23056         var del = this.getDragEl();
23057
23058         // Show the drag frame briefly so we can get its position
23059         del.style.visibility = "";
23060
23061         this.beforeMove();
23062         // Hide the linked element before the move to get around a Safari
23063         // rendering bug.
23064         lel.style.visibility = "hidden";
23065         Roo.dd.DDM.moveToEl(lel, del);
23066         del.style.visibility = "hidden";
23067         lel.style.visibility = "";
23068
23069         this.afterDrag();
23070     },
23071
23072     beforeMove : function(){
23073
23074     },
23075
23076     afterDrag : function(){
23077
23078     },
23079
23080     toString: function() {
23081         return ("DDProxy " + this.id);
23082     }
23083
23084 });
23085 /*
23086  * Based on:
23087  * Ext JS Library 1.1.1
23088  * Copyright(c) 2006-2007, Ext JS, LLC.
23089  *
23090  * Originally Released Under LGPL - original licence link has changed is not relivant.
23091  *
23092  * Fork - LGPL
23093  * <script type="text/javascript">
23094  */
23095
23096  /**
23097  * @class Roo.dd.DDTarget
23098  * A DragDrop implementation that does not move, but can be a drop
23099  * target.  You would get the same result by simply omitting implementation
23100  * for the event callbacks, but this way we reduce the processing cost of the
23101  * event listener and the callbacks.
23102  * @extends Roo.dd.DragDrop
23103  * @constructor
23104  * @param {String} id the id of the element that is a drop target
23105  * @param {String} sGroup the group of related DragDrop objects
23106  * @param {object} config an object containing configurable attributes
23107  *                 Valid properties for DDTarget in addition to those in
23108  *                 DragDrop:
23109  *                    none
23110  */
23111 Roo.dd.DDTarget = function(id, sGroup, config) {
23112     if (id) {
23113         this.initTarget(id, sGroup, config);
23114     }
23115     if (config && (config.listeners || config.events)) { 
23116         Roo.dd.DragDrop.superclass.constructor.call(this,  { 
23117             listeners : config.listeners || {}, 
23118             events : config.events || {} 
23119         });    
23120     }
23121 };
23122
23123 // Roo.dd.DDTarget.prototype = new Roo.dd.DragDrop();
23124 Roo.extend(Roo.dd.DDTarget, Roo.dd.DragDrop, {
23125     toString: function() {
23126         return ("DDTarget " + this.id);
23127     }
23128 });
23129 /*
23130  * Based on:
23131  * Ext JS Library 1.1.1
23132  * Copyright(c) 2006-2007, Ext JS, LLC.
23133  *
23134  * Originally Released Under LGPL - original licence link has changed is not relivant.
23135  *
23136  * Fork - LGPL
23137  * <script type="text/javascript">
23138  */
23139  
23140
23141 /**
23142  * @class Roo.dd.ScrollManager
23143  * Provides automatic scrolling of overflow regions in the page during drag operations.<br><br>
23144  * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
23145  * @static
23146  */
23147 Roo.dd.ScrollManager = function(){
23148     var ddm = Roo.dd.DragDropMgr;
23149     var els = {};
23150     var dragEl = null;
23151     var proc = {};
23152     
23153     
23154     
23155     var onStop = function(e){
23156         dragEl = null;
23157         clearProc();
23158     };
23159     
23160     var triggerRefresh = function(){
23161         if(ddm.dragCurrent){
23162              ddm.refreshCache(ddm.dragCurrent.groups);
23163         }
23164     };
23165     
23166     var doScroll = function(){
23167         if(ddm.dragCurrent){
23168             var dds = Roo.dd.ScrollManager;
23169             if(!dds.animate){
23170                 if(proc.el.scroll(proc.dir, dds.increment)){
23171                     triggerRefresh();
23172                 }
23173             }else{
23174                 proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
23175             }
23176         }
23177     };
23178     
23179     var clearProc = function(){
23180         if(proc.id){
23181             clearInterval(proc.id);
23182         }
23183         proc.id = 0;
23184         proc.el = null;
23185         proc.dir = "";
23186     };
23187     
23188     var startProc = function(el, dir){
23189          Roo.log('scroll startproc');
23190         clearProc();
23191         proc.el = el;
23192         proc.dir = dir;
23193         proc.id = setInterval(doScroll, Roo.dd.ScrollManager.frequency);
23194     };
23195     
23196     var onFire = function(e, isDrop){
23197        
23198         if(isDrop || !ddm.dragCurrent){ return; }
23199         var dds = Roo.dd.ScrollManager;
23200         if(!dragEl || dragEl != ddm.dragCurrent){
23201             dragEl = ddm.dragCurrent;
23202             // refresh regions on drag start
23203             dds.refreshCache();
23204         }
23205         
23206         var xy = Roo.lib.Event.getXY(e);
23207         var pt = new Roo.lib.Point(xy[0], xy[1]);
23208         for(var id in els){
23209             var el = els[id], r = el._region;
23210             if(r && r.contains(pt) && el.isScrollable()){
23211                 if(r.bottom - pt.y <= dds.thresh){
23212                     if(proc.el != el){
23213                         startProc(el, "down");
23214                     }
23215                     return;
23216                 }else if(r.right - pt.x <= dds.thresh){
23217                     if(proc.el != el){
23218                         startProc(el, "left");
23219                     }
23220                     return;
23221                 }else if(pt.y - r.top <= dds.thresh){
23222                     if(proc.el != el){
23223                         startProc(el, "up");
23224                     }
23225                     return;
23226                 }else if(pt.x - r.left <= dds.thresh){
23227                     if(proc.el != el){
23228                         startProc(el, "right");
23229                     }
23230                     return;
23231                 }
23232             }
23233         }
23234         clearProc();
23235     };
23236     
23237     ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
23238     ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
23239     
23240     return {
23241         /**
23242          * Registers new overflow element(s) to auto scroll
23243          * @param {String/HTMLElement/Element/Array} el The id of or the element to be scrolled or an array of either
23244          */
23245         register : function(el){
23246             if(el instanceof Array){
23247                 for(var i = 0, len = el.length; i < len; i++) {
23248                         this.register(el[i]);
23249                 }
23250             }else{
23251                 el = Roo.get(el);
23252                 els[el.id] = el;
23253             }
23254             Roo.dd.ScrollManager.els = els;
23255         },
23256         
23257         /**
23258          * Unregisters overflow element(s) so they are no longer scrolled
23259          * @param {String/HTMLElement/Element/Array} el The id of or the element to be removed or an array of either
23260          */
23261         unregister : function(el){
23262             if(el instanceof Array){
23263                 for(var i = 0, len = el.length; i < len; i++) {
23264                         this.unregister(el[i]);
23265                 }
23266             }else{
23267                 el = Roo.get(el);
23268                 delete els[el.id];
23269             }
23270         },
23271         
23272         /**
23273          * The number of pixels from the edge of a container the pointer needs to be to 
23274          * trigger scrolling (defaults to 25)
23275          * @type Number
23276          */
23277         thresh : 25,
23278         
23279         /**
23280          * The number of pixels to scroll in each scroll increment (defaults to 50)
23281          * @type Number
23282          */
23283         increment : 100,
23284         
23285         /**
23286          * The frequency of scrolls in milliseconds (defaults to 500)
23287          * @type Number
23288          */
23289         frequency : 500,
23290         
23291         /**
23292          * True to animate the scroll (defaults to true)
23293          * @type Boolean
23294          */
23295         animate: true,
23296         
23297         /**
23298          * The animation duration in seconds - 
23299          * MUST BE less than Roo.dd.ScrollManager.frequency! (defaults to .4)
23300          * @type Number
23301          */
23302         animDuration: .4,
23303         
23304         /**
23305          * Manually trigger a cache refresh.
23306          */
23307         refreshCache : function(){
23308             for(var id in els){
23309                 if(typeof els[id] == 'object'){ // for people extending the object prototype
23310                     els[id]._region = els[id].getRegion();
23311                 }
23312             }
23313         }
23314     };
23315 }();/*
23316  * Based on:
23317  * Ext JS Library 1.1.1
23318  * Copyright(c) 2006-2007, Ext JS, LLC.
23319  *
23320  * Originally Released Under LGPL - original licence link has changed is not relivant.
23321  *
23322  * Fork - LGPL
23323  * <script type="text/javascript">
23324  */
23325  
23326
23327 /**
23328  * @class Roo.dd.Registry
23329  * Provides easy access to all drag drop components that are registered on a page.  Items can be retrieved either
23330  * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
23331  * @static
23332  */
23333 Roo.dd.Registry = function(){
23334     var elements = {}; 
23335     var handles = {}; 
23336     var autoIdSeed = 0;
23337
23338     var getId = function(el, autogen){
23339         if(typeof el == "string"){
23340             return el;
23341         }
23342         var id = el.id;
23343         if(!id && autogen !== false){
23344             id = "roodd-" + (++autoIdSeed);
23345             el.id = id;
23346         }
23347         return id;
23348     };
23349     
23350     return {
23351     /**
23352      * Register a drag drop element
23353      * @param {String|HTMLElement} element The id or DOM node to register
23354      * @param {Object} data (optional) A custom data object that will be passed between the elements that are involved
23355      * in drag drop operations.  You can populate this object with any arbitrary properties that your own code
23356      * knows how to interpret, plus there are some specific properties known to the Registry that should be
23357      * populated in the data object (if applicable):
23358      * <pre>
23359 Value      Description<br />
23360 ---------  ------------------------------------------<br />
23361 handles    Array of DOM nodes that trigger dragging<br />
23362            for the element being registered<br />
23363 isHandle   True if the element passed in triggers<br />
23364            dragging itself, else false
23365 </pre>
23366      */
23367         register : function(el, data){
23368             data = data || {};
23369             if(typeof el == "string"){
23370                 el = document.getElementById(el);
23371             }
23372             data.ddel = el;
23373             elements[getId(el)] = data;
23374             if(data.isHandle !== false){
23375                 handles[data.ddel.id] = data;
23376             }
23377             if(data.handles){
23378                 var hs = data.handles;
23379                 for(var i = 0, len = hs.length; i < len; i++){
23380                         handles[getId(hs[i])] = data;
23381                 }
23382             }
23383         },
23384
23385     /**
23386      * Unregister a drag drop element
23387      * @param {String|HTMLElement}  element The id or DOM node to unregister
23388      */
23389         unregister : function(el){
23390             var id = getId(el, false);
23391             var data = elements[id];
23392             if(data){
23393                 delete elements[id];
23394                 if(data.handles){
23395                     var hs = data.handles;
23396                     for(var i = 0, len = hs.length; i < len; i++){
23397                         delete handles[getId(hs[i], false)];
23398                     }
23399                 }
23400             }
23401         },
23402
23403     /**
23404      * Returns the handle registered for a DOM Node by id
23405      * @param {String|HTMLElement} id The DOM node or id to look up
23406      * @return {Object} handle The custom handle data
23407      */
23408         getHandle : function(id){
23409             if(typeof id != "string"){ // must be element?
23410                 id = id.id;
23411             }
23412             return handles[id];
23413         },
23414
23415     /**
23416      * Returns the handle that is registered for the DOM node that is the target of the event
23417      * @param {Event} e The event
23418      * @return {Object} handle The custom handle data
23419      */
23420         getHandleFromEvent : function(e){
23421             var t = Roo.lib.Event.getTarget(e);
23422             return t ? handles[t.id] : null;
23423         },
23424
23425     /**
23426      * Returns a custom data object that is registered for a DOM node by id
23427      * @param {String|HTMLElement} id The DOM node or id to look up
23428      * @return {Object} data The custom data
23429      */
23430         getTarget : function(id){
23431             if(typeof id != "string"){ // must be element?
23432                 id = id.id;
23433             }
23434             return elements[id];
23435         },
23436
23437     /**
23438      * Returns a custom data object that is registered for the DOM node that is the target of the event
23439      * @param {Event} e The event
23440      * @return {Object} data The custom data
23441      */
23442         getTargetFromEvent : function(e){
23443             var t = Roo.lib.Event.getTarget(e);
23444             return t ? elements[t.id] || handles[t.id] : null;
23445         }
23446     };
23447 }();/*
23448  * Based on:
23449  * Ext JS Library 1.1.1
23450  * Copyright(c) 2006-2007, Ext JS, LLC.
23451  *
23452  * Originally Released Under LGPL - original licence link has changed is not relivant.
23453  *
23454  * Fork - LGPL
23455  * <script type="text/javascript">
23456  */
23457  
23458
23459 /**
23460  * @class Roo.dd.StatusProxy
23461  * A specialized drag proxy that supports a drop status icon, {@link Roo.Layer} styles and auto-repair.  This is the
23462  * default drag proxy used by all Roo.dd components.
23463  * @constructor
23464  * @param {Object} config
23465  */
23466 Roo.dd.StatusProxy = function(config){
23467     Roo.apply(this, config);
23468     this.id = this.id || Roo.id();
23469     this.el = new Roo.Layer({
23470         dh: {
23471             id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
23472                 {tag: "div", cls: "x-dd-drop-icon"},
23473                 {tag: "div", cls: "x-dd-drag-ghost"}
23474             ]
23475         }, 
23476         shadow: !config || config.shadow !== false
23477     });
23478     this.ghost = Roo.get(this.el.dom.childNodes[1]);
23479     this.dropStatus = this.dropNotAllowed;
23480 };
23481
23482 Roo.dd.StatusProxy.prototype = {
23483     /**
23484      * @cfg {String} dropAllowed
23485      * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
23486      */
23487     dropAllowed : "x-dd-drop-ok",
23488     /**
23489      * @cfg {String} dropNotAllowed
23490      * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
23491      */
23492     dropNotAllowed : "x-dd-drop-nodrop",
23493
23494     /**
23495      * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
23496      * over the current target element.
23497      * @param {String} cssClass The css class for the new drop status indicator image
23498      */
23499     setStatus : function(cssClass){
23500         cssClass = cssClass || this.dropNotAllowed;
23501         if(this.dropStatus != cssClass){
23502             this.el.replaceClass(this.dropStatus, cssClass);
23503             this.dropStatus = cssClass;
23504         }
23505     },
23506
23507     /**
23508      * Resets the status indicator to the default dropNotAllowed value
23509      * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
23510      */
23511     reset : function(clearGhost){
23512         this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
23513         this.dropStatus = this.dropNotAllowed;
23514         if(clearGhost){
23515             this.ghost.update("");
23516         }
23517     },
23518
23519     /**
23520      * Updates the contents of the ghost element
23521      * @param {String} html The html that will replace the current innerHTML of the ghost element
23522      */
23523     update : function(html){
23524         if(typeof html == "string"){
23525             this.ghost.update(html);
23526         }else{
23527             this.ghost.update("");
23528             html.style.margin = "0";
23529             this.ghost.dom.appendChild(html);
23530         }
23531         // ensure float = none set?? cant remember why though.
23532         var el = this.ghost.dom.firstChild;
23533                 if(el){
23534                         Roo.fly(el).setStyle('float', 'none');
23535                 }
23536     },
23537     
23538     /**
23539      * Returns the underlying proxy {@link Roo.Layer}
23540      * @return {Roo.Layer} el
23541     */
23542     getEl : function(){
23543         return this.el;
23544     },
23545
23546     /**
23547      * Returns the ghost element
23548      * @return {Roo.Element} el
23549      */
23550     getGhost : function(){
23551         return this.ghost;
23552     },
23553
23554     /**
23555      * Hides the proxy
23556      * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
23557      */
23558     hide : function(clear){
23559         this.el.hide();
23560         if(clear){
23561             this.reset(true);
23562         }
23563     },
23564
23565     /**
23566      * Stops the repair animation if it's currently running
23567      */
23568     stop : function(){
23569         if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
23570             this.anim.stop();
23571         }
23572     },
23573
23574     /**
23575      * Displays this proxy
23576      */
23577     show : function(){
23578         this.el.show();
23579     },
23580
23581     /**
23582      * Force the Layer to sync its shadow and shim positions to the element
23583      */
23584     sync : function(){
23585         this.el.sync();
23586     },
23587
23588     /**
23589      * Causes the proxy to return to its position of origin via an animation.  Should be called after an
23590      * invalid drop operation by the item being dragged.
23591      * @param {Array} xy The XY position of the element ([x, y])
23592      * @param {Function} callback The function to call after the repair is complete
23593      * @param {Object} scope The scope in which to execute the callback
23594      */
23595     repair : function(xy, callback, scope){
23596         this.callback = callback;
23597         this.scope = scope;
23598         if(xy && this.animRepair !== false){
23599             this.el.addClass("x-dd-drag-repair");
23600             this.el.hideUnders(true);
23601             this.anim = this.el.shift({
23602                 duration: this.repairDuration || .5,
23603                 easing: 'easeOut',
23604                 xy: xy,
23605                 stopFx: true,
23606                 callback: this.afterRepair,
23607                 scope: this
23608             });
23609         }else{
23610             this.afterRepair();
23611         }
23612     },
23613
23614     // private
23615     afterRepair : function(){
23616         this.hide(true);
23617         if(typeof this.callback == "function"){
23618             this.callback.call(this.scope || this);
23619         }
23620         this.callback = null;
23621         this.scope = null;
23622     }
23623 };/*
23624  * Based on:
23625  * Ext JS Library 1.1.1
23626  * Copyright(c) 2006-2007, Ext JS, LLC.
23627  *
23628  * Originally Released Under LGPL - original licence link has changed is not relivant.
23629  *
23630  * Fork - LGPL
23631  * <script type="text/javascript">
23632  */
23633
23634 /**
23635  * @class Roo.dd.DragSource
23636  * @extends Roo.dd.DDProxy
23637  * A simple class that provides the basic implementation needed to make any element draggable.
23638  * @constructor
23639  * @param {String/HTMLElement/Element} el The container element
23640  * @param {Object} config
23641  */
23642 Roo.dd.DragSource = function(el, config){
23643     this.el = Roo.get(el);
23644     this.dragData = {};
23645     
23646     Roo.apply(this, config);
23647     
23648     if(!this.proxy){
23649         this.proxy = new Roo.dd.StatusProxy();
23650     }
23651
23652     Roo.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
23653           {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
23654     
23655     this.dragging = false;
23656 };
23657
23658 Roo.extend(Roo.dd.DragSource, Roo.dd.DDProxy, {
23659     /**
23660      * @cfg {String} dropAllowed
23661      * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
23662      */
23663     dropAllowed : "x-dd-drop-ok",
23664     /**
23665      * @cfg {String} dropNotAllowed
23666      * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
23667      */
23668     dropNotAllowed : "x-dd-drop-nodrop",
23669
23670     /**
23671      * Returns the data object associated with this drag source
23672      * @return {Object} data An object containing arbitrary data
23673      */
23674     getDragData : function(e){
23675         return this.dragData;
23676     },
23677
23678     // private
23679     onDragEnter : function(e, id){
23680         var target = Roo.dd.DragDropMgr.getDDById(id);
23681         this.cachedTarget = target;
23682         if(this.beforeDragEnter(target, e, id) !== false){
23683             if(target.isNotifyTarget){
23684                 var status = target.notifyEnter(this, e, this.dragData);
23685                 this.proxy.setStatus(status);
23686             }else{
23687                 this.proxy.setStatus(this.dropAllowed);
23688             }
23689             
23690             if(this.afterDragEnter){
23691                 /**
23692                  * An empty function by default, but provided so that you can perform a custom action
23693                  * when the dragged item enters the drop target by providing an implementation.
23694                  * @param {Roo.dd.DragDrop} target The drop target
23695                  * @param {Event} e The event object
23696                  * @param {String} id The id of the dragged element
23697                  * @method afterDragEnter
23698                  */
23699                 this.afterDragEnter(target, e, id);
23700             }
23701         }
23702     },
23703
23704     /**
23705      * An empty function by default, but provided so that you can perform a custom action
23706      * before the dragged item enters the drop target and optionally cancel the onDragEnter.
23707      * @param {Roo.dd.DragDrop} target The drop target
23708      * @param {Event} e The event object
23709      * @param {String} id The id of the dragged element
23710      * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23711      */
23712     beforeDragEnter : function(target, e, id){
23713         return true;
23714     },
23715
23716     // private
23717     alignElWithMouse: function() {
23718         Roo.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
23719         this.proxy.sync();
23720     },
23721
23722     // private
23723     onDragOver : function(e, id){
23724         var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23725         if(this.beforeDragOver(target, e, id) !== false){
23726             if(target.isNotifyTarget){
23727                 var status = target.notifyOver(this, e, this.dragData);
23728                 this.proxy.setStatus(status);
23729             }
23730
23731             if(this.afterDragOver){
23732                 /**
23733                  * An empty function by default, but provided so that you can perform a custom action
23734                  * while the dragged item is over the drop target by providing an implementation.
23735                  * @param {Roo.dd.DragDrop} target The drop target
23736                  * @param {Event} e The event object
23737                  * @param {String} id The id of the dragged element
23738                  * @method afterDragOver
23739                  */
23740                 this.afterDragOver(target, e, id);
23741             }
23742         }
23743     },
23744
23745     /**
23746      * An empty function by default, but provided so that you can perform a custom action
23747      * while the dragged item is over the drop target and optionally cancel the onDragOver.
23748      * @param {Roo.dd.DragDrop} target The drop target
23749      * @param {Event} e The event object
23750      * @param {String} id The id of the dragged element
23751      * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23752      */
23753     beforeDragOver : function(target, e, id){
23754         return true;
23755     },
23756
23757     // private
23758     onDragOut : function(e, id){
23759         var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23760         if(this.beforeDragOut(target, e, id) !== false){
23761             if(target.isNotifyTarget){
23762                 target.notifyOut(this, e, this.dragData);
23763             }
23764             this.proxy.reset();
23765             if(this.afterDragOut){
23766                 /**
23767                  * An empty function by default, but provided so that you can perform a custom action
23768                  * after the dragged item is dragged out of the target without dropping.
23769                  * @param {Roo.dd.DragDrop} target The drop target
23770                  * @param {Event} e The event object
23771                  * @param {String} id The id of the dragged element
23772                  * @method afterDragOut
23773                  */
23774                 this.afterDragOut(target, e, id);
23775             }
23776         }
23777         this.cachedTarget = null;
23778     },
23779
23780     /**
23781      * An empty function by default, but provided so that you can perform a custom action before the dragged
23782      * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
23783      * @param {Roo.dd.DragDrop} target The drop target
23784      * @param {Event} e The event object
23785      * @param {String} id The id of the dragged element
23786      * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23787      */
23788     beforeDragOut : function(target, e, id){
23789         return true;
23790     },
23791     
23792     // private
23793     onDragDrop : function(e, id){
23794         var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23795         if(this.beforeDragDrop(target, e, id) !== false){
23796             if(target.isNotifyTarget){
23797                 if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
23798                     this.onValidDrop(target, e, id);
23799                 }else{
23800                     this.onInvalidDrop(target, e, id);
23801                 }
23802             }else{
23803                 this.onValidDrop(target, e, id);
23804             }
23805             
23806             if(this.afterDragDrop){
23807                 /**
23808                  * An empty function by default, but provided so that you can perform a custom action
23809                  * after a valid drag drop has occurred by providing an implementation.
23810                  * @param {Roo.dd.DragDrop} target The drop target
23811                  * @param {Event} e The event object
23812                  * @param {String} id The id of the dropped element
23813                  * @method afterDragDrop
23814                  */
23815                 this.afterDragDrop(target, e, id);
23816             }
23817         }
23818         delete this.cachedTarget;
23819     },
23820
23821     /**
23822      * An empty function by default, but provided so that you can perform a custom action before the dragged
23823      * item is dropped onto the target and optionally cancel the onDragDrop.
23824      * @param {Roo.dd.DragDrop} target The drop target
23825      * @param {Event} e The event object
23826      * @param {String} id The id of the dragged element
23827      * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
23828      */
23829     beforeDragDrop : function(target, e, id){
23830         return true;
23831     },
23832
23833     // private
23834     onValidDrop : function(target, e, id){
23835         this.hideProxy();
23836         if(this.afterValidDrop){
23837             /**
23838              * An empty function by default, but provided so that you can perform a custom action
23839              * after a valid drop has occurred by providing an implementation.
23840              * @param {Object} target The target DD 
23841              * @param {Event} e The event object
23842              * @param {String} id The id of the dropped element
23843              * @method afterInvalidDrop
23844              */
23845             this.afterValidDrop(target, e, id);
23846         }
23847     },
23848
23849     // private
23850     getRepairXY : function(e, data){
23851         return this.el.getXY();  
23852     },
23853
23854     // private
23855     onInvalidDrop : function(target, e, id){
23856         this.beforeInvalidDrop(target, e, id);
23857         if(this.cachedTarget){
23858             if(this.cachedTarget.isNotifyTarget){
23859                 this.cachedTarget.notifyOut(this, e, this.dragData);
23860             }
23861             this.cacheTarget = null;
23862         }
23863         this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
23864
23865         if(this.afterInvalidDrop){
23866             /**
23867              * An empty function by default, but provided so that you can perform a custom action
23868              * after an invalid drop has occurred by providing an implementation.
23869              * @param {Event} e The event object
23870              * @param {String} id The id of the dropped element
23871              * @method afterInvalidDrop
23872              */
23873             this.afterInvalidDrop(e, id);
23874         }
23875     },
23876
23877     // private
23878     afterRepair : function(){
23879         if(Roo.enableFx){
23880             this.el.highlight(this.hlColor || "c3daf9");
23881         }
23882         this.dragging = false;
23883     },
23884
23885     /**
23886      * An empty function by default, but provided so that you can perform a custom action after an invalid
23887      * drop has occurred.
23888      * @param {Roo.dd.DragDrop} target The drop target
23889      * @param {Event} e The event object
23890      * @param {String} id The id of the dragged element
23891      * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
23892      */
23893     beforeInvalidDrop : function(target, e, id){
23894         return true;
23895     },
23896
23897     // private
23898     handleMouseDown : function(e){
23899         if(this.dragging) {
23900             return;
23901         }
23902         var data = this.getDragData(e);
23903         if(data && this.onBeforeDrag(data, e) !== false){
23904             this.dragData = data;
23905             this.proxy.stop();
23906             Roo.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
23907         } 
23908     },
23909
23910     /**
23911      * An empty function by default, but provided so that you can perform a custom action before the initial
23912      * drag event begins and optionally cancel it.
23913      * @param {Object} data An object containing arbitrary data to be shared with drop targets
23914      * @param {Event} e The event object
23915      * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23916      */
23917     onBeforeDrag : function(data, e){
23918         return true;
23919     },
23920
23921     /**
23922      * An empty function by default, but provided so that you can perform a custom action once the initial
23923      * drag event has begun.  The drag cannot be canceled from this function.
23924      * @param {Number} x The x position of the click on the dragged object
23925      * @param {Number} y The y position of the click on the dragged object
23926      */
23927     onStartDrag : Roo.emptyFn,
23928
23929     // private - YUI override
23930     startDrag : function(x, y){
23931         this.proxy.reset();
23932         this.dragging = true;
23933         this.proxy.update("");
23934         this.onInitDrag(x, y);
23935         this.proxy.show();
23936     },
23937
23938     // private
23939     onInitDrag : function(x, y){
23940         var clone = this.el.dom.cloneNode(true);
23941         clone.id = Roo.id(); // prevent duplicate ids
23942         this.proxy.update(clone);
23943         this.onStartDrag(x, y);
23944         return true;
23945     },
23946
23947     /**
23948      * Returns the drag source's underlying {@link Roo.dd.StatusProxy}
23949      * @return {Roo.dd.StatusProxy} proxy The StatusProxy
23950      */
23951     getProxy : function(){
23952         return this.proxy;  
23953     },
23954
23955     /**
23956      * Hides the drag source's {@link Roo.dd.StatusProxy}
23957      */
23958     hideProxy : function(){
23959         this.proxy.hide();  
23960         this.proxy.reset(true);
23961         this.dragging = false;
23962     },
23963
23964     // private
23965     triggerCacheRefresh : function(){
23966         Roo.dd.DDM.refreshCache(this.groups);
23967     },
23968
23969     // private - override to prevent hiding
23970     b4EndDrag: function(e) {
23971     },
23972
23973     // private - override to prevent moving
23974     endDrag : function(e){
23975         this.onEndDrag(this.dragData, e);
23976     },
23977
23978     // private
23979     onEndDrag : function(data, e){
23980     },
23981     
23982     // private - pin to cursor
23983     autoOffset : function(x, y) {
23984         this.setDelta(-12, -20);
23985     }    
23986 });/*
23987  * Based on:
23988  * Ext JS Library 1.1.1
23989  * Copyright(c) 2006-2007, Ext JS, LLC.
23990  *
23991  * Originally Released Under LGPL - original licence link has changed is not relivant.
23992  *
23993  * Fork - LGPL
23994  * <script type="text/javascript">
23995  */
23996
23997
23998 /**
23999  * @class Roo.dd.DropTarget
24000  * @extends Roo.dd.DDTarget
24001  * A simple class that provides the basic implementation needed to make any element a drop target that can have
24002  * draggable items dropped onto it.  The drop has no effect until an implementation of notifyDrop is provided.
24003  * @constructor
24004  * @param {String/HTMLElement/Element} el The container element
24005  * @param {Object} config
24006  */
24007 Roo.dd.DropTarget = function(el, config){
24008     this.el = Roo.get(el);
24009     
24010     var listeners = false; ;
24011     if (config && config.listeners) {
24012         listeners= config.listeners;
24013         delete config.listeners;
24014     }
24015     Roo.apply(this, config);
24016     
24017     if(this.containerScroll){
24018         Roo.dd.ScrollManager.register(this.el);
24019     }
24020     this.addEvents( {
24021          /**
24022          * @scope Roo.dd.DropTarget
24023          */
24024          
24025          /**
24026          * @event enter
24027          * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source is now over the
24028          * target.  This default implementation adds the CSS class specified by overClass (if any) to the drop element
24029          * and returns the dropAllowed config value.  This method should be overridden if drop validation is required.
24030          * 
24031          * IMPORTANT : it should set  this.valid to true|false
24032          * 
24033          * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
24034          * @param {Event} e The event
24035          * @param {Object} data An object containing arbitrary data supplied by the drag source
24036          */
24037         "enter" : true,
24038         
24039          /**
24040          * @event over
24041          * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the target.
24042          * This method will be called on every mouse movement while the drag source is over the drop target.
24043          * This default implementation simply returns the dropAllowed config value.
24044          * 
24045          * IMPORTANT : it should set  this.valid to true|false
24046          * 
24047          * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
24048          * @param {Event} e The event
24049          * @param {Object} data An object containing arbitrary data supplied by the drag source
24050          
24051          */
24052         "over" : true,
24053         /**
24054          * @event out
24055          * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source has been dragged
24056          * out of the target without dropping.  This default implementation simply removes the CSS class specified by
24057          * overClass (if any) from the drop element.
24058          * 
24059          * 
24060          * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
24061          * @param {Event} e The event
24062          * @param {Object} data An object containing arbitrary data supplied by the drag source
24063          */
24064          "out" : true,
24065          
24066         /**
24067          * @event drop
24068          * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the dragged item has
24069          * been dropped on it.  This method has no default implementation and returns false, so you must provide an
24070          * implementation that does something to process the drop event and returns true so that the drag source's
24071          * repair action does not run.
24072          * 
24073          * IMPORTANT : it should set this.success
24074          * 
24075          * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
24076          * @param {Event} e The event
24077          * @param {Object} data An object containing arbitrary data supplied by the drag source
24078         */
24079          "drop" : true
24080     });
24081             
24082      
24083     Roo.dd.DropTarget.superclass.constructor.call(  this, 
24084         this.el.dom, 
24085         this.ddGroup || this.group,
24086         {
24087             isTarget: true,
24088             listeners : listeners || {} 
24089            
24090         
24091         }
24092     );
24093
24094 };
24095
24096 Roo.extend(Roo.dd.DropTarget, Roo.dd.DDTarget, {
24097     /**
24098      * @cfg {String} overClass
24099      * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
24100      */
24101      /**
24102      * @cfg {String} ddGroup
24103      * The drag drop group to handle drop events for
24104      */
24105      
24106     /**
24107      * @cfg {String} dropAllowed
24108      * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
24109      */
24110     dropAllowed : "x-dd-drop-ok",
24111     /**
24112      * @cfg {String} dropNotAllowed
24113      * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
24114      */
24115     dropNotAllowed : "x-dd-drop-nodrop",
24116     /**
24117      * @cfg {boolean} success
24118      * set this after drop listener.. 
24119      */
24120     success : false,
24121     /**
24122      * @cfg {boolean|String} valid true/false or string (ok-add/ok-sub/ok/nodrop)
24123      * if the drop point is valid for over/enter..
24124      */
24125     valid : false,
24126     // private
24127     isTarget : true,
24128
24129     // private
24130     isNotifyTarget : true,
24131     
24132     /**
24133      * @hide
24134      */
24135     notifyEnter : function(dd, e, data)
24136     {
24137         this.valid = true;
24138         this.fireEvent('enter', dd, e, data);
24139         if(this.overClass){
24140             this.el.addClass(this.overClass);
24141         }
24142         return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
24143             this.valid ? this.dropAllowed : this.dropNotAllowed
24144         );
24145     },
24146
24147     /**
24148      * @hide
24149      */
24150     notifyOver : function(dd, e, data)
24151     {
24152         this.valid = true;
24153         this.fireEvent('over', dd, e, data);
24154         return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
24155             this.valid ? this.dropAllowed : this.dropNotAllowed
24156         );
24157     },
24158
24159     /**
24160      * @hide
24161      */
24162     notifyOut : function(dd, e, data)
24163     {
24164         this.fireEvent('out', dd, e, data);
24165         if(this.overClass){
24166             this.el.removeClass(this.overClass);
24167         }
24168     },
24169
24170     /**
24171      * @hide
24172      */
24173     notifyDrop : function(dd, e, data)
24174     {
24175         this.success = false;
24176         this.fireEvent('drop', dd, e, data);
24177         return this.success;
24178     }
24179 });/*
24180  * Based on:
24181  * Ext JS Library 1.1.1
24182  * Copyright(c) 2006-2007, Ext JS, LLC.
24183  *
24184  * Originally Released Under LGPL - original licence link has changed is not relivant.
24185  *
24186  * Fork - LGPL
24187  * <script type="text/javascript">
24188  */
24189
24190
24191 /**
24192  * @class Roo.dd.DragZone
24193  * @extends Roo.dd.DragSource
24194  * This class provides a container DD instance that proxies for multiple child node sources.<br />
24195  * By default, this class requires that draggable child nodes are registered with {@link Roo.dd.Registry}.
24196  * @constructor
24197  * @param {String/HTMLElement/Element} el The container element
24198  * @param {Object} config
24199  */
24200 Roo.dd.DragZone = function(el, config){
24201     Roo.dd.DragZone.superclass.constructor.call(this, el, config);
24202     if(this.containerScroll){
24203         Roo.dd.ScrollManager.register(this.el);
24204     }
24205 };
24206
24207 Roo.extend(Roo.dd.DragZone, Roo.dd.DragSource, {
24208     /**
24209      * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
24210      * for auto scrolling during drag operations.
24211      */
24212     /**
24213      * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
24214      * method after a failed drop (defaults to "c3daf9" - light blue)
24215      */
24216
24217     /**
24218      * Called when a mousedown occurs in this container. Looks in {@link Roo.dd.Registry}
24219      * for a valid target to drag based on the mouse down. Override this method
24220      * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
24221      * object has a "ddel" attribute (with an HTML Element) for other functions to work.
24222      * @param {EventObject} e The mouse down event
24223      * @return {Object} The dragData
24224      */
24225     getDragData : function(e){
24226         return Roo.dd.Registry.getHandleFromEvent(e);
24227     },
24228     
24229     /**
24230      * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
24231      * this.dragData.ddel
24232      * @param {Number} x The x position of the click on the dragged object
24233      * @param {Number} y The y position of the click on the dragged object
24234      * @return {Boolean} true to continue the drag, false to cancel
24235      */
24236     onInitDrag : function(x, y){
24237         this.proxy.update(this.dragData.ddel.cloneNode(true));
24238         this.onStartDrag(x, y);
24239         return true;
24240     },
24241     
24242     /**
24243      * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel 
24244      */
24245     afterRepair : function(){
24246         if(Roo.enableFx){
24247             Roo.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
24248         }
24249         this.dragging = false;
24250     },
24251
24252     /**
24253      * Called before a repair of an invalid drop to get the XY to animate to. By default returns
24254      * the XY of this.dragData.ddel
24255      * @param {EventObject} e The mouse up event
24256      * @return {Array} The xy location (e.g. [100, 200])
24257      */
24258     getRepairXY : function(e){
24259         return Roo.Element.fly(this.dragData.ddel).getXY();  
24260     }
24261 });/*
24262  * Based on:
24263  * Ext JS Library 1.1.1
24264  * Copyright(c) 2006-2007, Ext JS, LLC.
24265  *
24266  * Originally Released Under LGPL - original licence link has changed is not relivant.
24267  *
24268  * Fork - LGPL
24269  * <script type="text/javascript">
24270  */
24271 /**
24272  * @class Roo.dd.DropZone
24273  * @extends Roo.dd.DropTarget
24274  * This class provides a container DD instance that proxies for multiple child node targets.<br />
24275  * By default, this class requires that child nodes accepting drop are registered with {@link Roo.dd.Registry}.
24276  * @constructor
24277  * @param {String/HTMLElement/Element} el The container element
24278  * @param {Object} config
24279  */
24280 Roo.dd.DropZone = function(el, config){
24281     Roo.dd.DropZone.superclass.constructor.call(this, el, config);
24282 };
24283
24284 Roo.extend(Roo.dd.DropZone, Roo.dd.DropTarget, {
24285     /**
24286      * Returns a custom data object associated with the DOM node that is the target of the event.  By default
24287      * this looks up the event target in the {@link Roo.dd.Registry}, although you can override this method to
24288      * provide your own custom lookup.
24289      * @param {Event} e The event
24290      * @return {Object} data The custom data
24291      */
24292     getTargetFromEvent : function(e){
24293         return Roo.dd.Registry.getTargetFromEvent(e);
24294     },
24295
24296     /**
24297      * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has entered a drop node
24298      * that it has registered.  This method has no default implementation and should be overridden to provide
24299      * node-specific processing if necessary.
24300      * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from 
24301      * {@link #getTargetFromEvent} for this node)
24302      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24303      * @param {Event} e The event
24304      * @param {Object} data An object containing arbitrary data supplied by the drag source
24305      */
24306     onNodeEnter : function(n, dd, e, data){
24307         
24308     },
24309
24310     /**
24311      * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is over a drop node
24312      * that it has registered.  The default implementation returns this.dropNotAllowed, so it should be
24313      * overridden to provide the proper feedback.
24314      * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
24315      * {@link #getTargetFromEvent} for this node)
24316      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24317      * @param {Event} e The event
24318      * @param {Object} data An object containing arbitrary data supplied by the drag source
24319      * @return {String} status The CSS class that communicates the drop status back to the source so that the
24320      * underlying {@link Roo.dd.StatusProxy} can be updated
24321      */
24322     onNodeOver : function(n, dd, e, data){
24323         return this.dropAllowed;
24324     },
24325
24326     /**
24327      * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dragged out of
24328      * the drop node without dropping.  This method has no default implementation and should be overridden to provide
24329      * node-specific processing if necessary.
24330      * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
24331      * {@link #getTargetFromEvent} for this node)
24332      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24333      * @param {Event} e The event
24334      * @param {Object} data An object containing arbitrary data supplied by the drag source
24335      */
24336     onNodeOut : function(n, dd, e, data){
24337         
24338     },
24339
24340     /**
24341      * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped onto
24342      * the drop node.  The default implementation returns false, so it should be overridden to provide the
24343      * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
24344      * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
24345      * {@link #getTargetFromEvent} for this node)
24346      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24347      * @param {Event} e The event
24348      * @param {Object} data An object containing arbitrary data supplied by the drag source
24349      * @return {Boolean} True if the drop was valid, else false
24350      */
24351     onNodeDrop : function(n, dd, e, data){
24352         return false;
24353     },
24354
24355     /**
24356      * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is being dragged over it,
24357      * but not over any of its registered drop nodes.  The default implementation returns this.dropNotAllowed, so
24358      * it should be overridden to provide the proper feedback if necessary.
24359      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24360      * @param {Event} e The event
24361      * @param {Object} data An object containing arbitrary data supplied by the drag source
24362      * @return {String} status The CSS class that communicates the drop status back to the source so that the
24363      * underlying {@link Roo.dd.StatusProxy} can be updated
24364      */
24365     onContainerOver : function(dd, e, data){
24366         return this.dropNotAllowed;
24367     },
24368
24369     /**
24370      * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped on it,
24371      * but not on any of its registered drop nodes.  The default implementation returns false, so it should be
24372      * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
24373      * be able to accept drops.  It should return true when valid so that the drag source's repair action does not run.
24374      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24375      * @param {Event} e The event
24376      * @param {Object} data An object containing arbitrary data supplied by the drag source
24377      * @return {Boolean} True if the drop was valid, else false
24378      */
24379     onContainerDrop : function(dd, e, data){
24380         return false;
24381     },
24382
24383     /**
24384      * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source is now over
24385      * the zone.  The default implementation returns this.dropNotAllowed and expects that only registered drop
24386      * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
24387      * you should override this method and provide a custom implementation.
24388      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24389      * @param {Event} e The event
24390      * @param {Object} data An object containing arbitrary data supplied by the drag source
24391      * @return {String} status The CSS class that communicates the drop status back to the source so that the
24392      * underlying {@link Roo.dd.StatusProxy} can be updated
24393      */
24394     notifyEnter : function(dd, e, data){
24395         return this.dropNotAllowed;
24396     },
24397
24398     /**
24399      * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the drop zone.
24400      * This method will be called on every mouse movement while the drag source is over the drop zone.
24401      * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
24402      * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
24403      * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
24404      * registered node, it will call {@link #onContainerOver}.
24405      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24406      * @param {Event} e The event
24407      * @param {Object} data An object containing arbitrary data supplied by the drag source
24408      * @return {String} status The CSS class that communicates the drop status back to the source so that the
24409      * underlying {@link Roo.dd.StatusProxy} can be updated
24410      */
24411     notifyOver : function(dd, e, data){
24412         var n = this.getTargetFromEvent(e);
24413         if(!n){ // not over valid drop target
24414             if(this.lastOverNode){
24415                 this.onNodeOut(this.lastOverNode, dd, e, data);
24416                 this.lastOverNode = null;
24417             }
24418             return this.onContainerOver(dd, e, data);
24419         }
24420         if(this.lastOverNode != n){
24421             if(this.lastOverNode){
24422                 this.onNodeOut(this.lastOverNode, dd, e, data);
24423             }
24424             this.onNodeEnter(n, dd, e, data);
24425             this.lastOverNode = n;
24426         }
24427         return this.onNodeOver(n, dd, e, data);
24428     },
24429
24430     /**
24431      * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source has been dragged
24432      * out of the zone without dropping.  If the drag source is currently over a registered node, the notification
24433      * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
24434      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
24435      * @param {Event} e The event
24436      * @param {Object} data An object containing arbitrary data supplied by the drag zone
24437      */
24438     notifyOut : function(dd, e, data){
24439         if(this.lastOverNode){
24440             this.onNodeOut(this.lastOverNode, dd, e, data);
24441             this.lastOverNode = null;
24442         }
24443     },
24444
24445     /**
24446      * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the dragged item has
24447      * been dropped on it.  The drag zone will look up the target node based on the event passed in, and if there
24448      * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
24449      * otherwise it will call {@link #onContainerDrop}.
24450      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24451      * @param {Event} e The event
24452      * @param {Object} data An object containing arbitrary data supplied by the drag source
24453      * @return {Boolean} True if the drop was valid, else false
24454      */
24455     notifyDrop : function(dd, e, data){
24456         if(this.lastOverNode){
24457             this.onNodeOut(this.lastOverNode, dd, e, data);
24458             this.lastOverNode = null;
24459         }
24460         var n = this.getTargetFromEvent(e);
24461         return n ?
24462             this.onNodeDrop(n, dd, e, data) :
24463             this.onContainerDrop(dd, e, data);
24464     },
24465
24466     // private
24467     triggerCacheRefresh : function(){
24468         Roo.dd.DDM.refreshCache(this.groups);
24469     }  
24470 });/*
24471  * Based on:
24472  * Ext JS Library 1.1.1
24473  * Copyright(c) 2006-2007, Ext JS, LLC.
24474  *
24475  * Originally Released Under LGPL - original licence link has changed is not relivant.
24476  *
24477  * Fork - LGPL
24478  * <script type="text/javascript">
24479  */
24480
24481
24482 /**
24483  * @class Roo.data.SortTypes
24484  * @static
24485  * Defines the default sorting (casting?) comparison functions used when sorting data.
24486  */
24487 Roo.data.SortTypes = {
24488     /**
24489      * Default sort that does nothing
24490      * @param {Mixed} s The value being converted
24491      * @return {Mixed} The comparison value
24492      */
24493     none : function(s){
24494         return s;
24495     },
24496     
24497     /**
24498      * The regular expression used to strip tags
24499      * @type {RegExp}
24500      * @property
24501      */
24502     stripTagsRE : /<\/?[^>]+>/gi,
24503     
24504     /**
24505      * Strips all HTML tags to sort on text only
24506      * @param {Mixed} s The value being converted
24507      * @return {String} The comparison value
24508      */
24509     asText : function(s){
24510         return String(s).replace(this.stripTagsRE, "");
24511     },
24512     
24513     /**
24514      * Strips all HTML tags to sort on text only - Case insensitive
24515      * @param {Mixed} s The value being converted
24516      * @return {String} The comparison value
24517      */
24518     asUCText : function(s){
24519         return String(s).toUpperCase().replace(this.stripTagsRE, "");
24520     },
24521     
24522     /**
24523      * Case insensitive string
24524      * @param {Mixed} s The value being converted
24525      * @return {String} The comparison value
24526      */
24527     asUCString : function(s) {
24528         return String(s).toUpperCase();
24529     },
24530     
24531     /**
24532      * Date sorting
24533      * @param {Mixed} s The value being converted
24534      * @return {Number} The comparison value
24535      */
24536     asDate : function(s) {
24537         if(!s){
24538             return 0;
24539         }
24540         if(s instanceof Date){
24541             return s.getTime();
24542         }
24543         return Date.parse(String(s));
24544     },
24545     
24546     /**
24547      * Float sorting
24548      * @param {Mixed} s The value being converted
24549      * @return {Float} The comparison value
24550      */
24551     asFloat : function(s) {
24552         var val = parseFloat(String(s).replace(/,/g, ""));
24553         if(isNaN(val)) {
24554             val = 0;
24555         }
24556         return val;
24557     },
24558     
24559     /**
24560      * Integer sorting
24561      * @param {Mixed} s The value being converted
24562      * @return {Number} The comparison value
24563      */
24564     asInt : function(s) {
24565         var val = parseInt(String(s).replace(/,/g, ""));
24566         if(isNaN(val)) {
24567             val = 0;
24568         }
24569         return val;
24570     }
24571 };/*
24572  * Based on:
24573  * Ext JS Library 1.1.1
24574  * Copyright(c) 2006-2007, Ext JS, LLC.
24575  *
24576  * Originally Released Under LGPL - original licence link has changed is not relivant.
24577  *
24578  * Fork - LGPL
24579  * <script type="text/javascript">
24580  */
24581
24582 /**
24583 * @class Roo.data.Record
24584  * Instances of this class encapsulate both record <em>definition</em> information, and record
24585  * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
24586  * to access Records cached in an {@link Roo.data.Store} object.<br>
24587  * <p>
24588  * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
24589  * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
24590  * objects.<br>
24591  * <p>
24592  * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
24593  * @constructor
24594  * This constructor should not be used to create Record objects. Instead, use the constructor generated by
24595  * {@link #create}. The parameters are the same.
24596  * @param {Array} data An associative Array of data values keyed by the field name.
24597  * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
24598  * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
24599  * not specified an integer id is generated.
24600  */
24601 Roo.data.Record = function(data, id){
24602     this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
24603     this.data = data;
24604 };
24605
24606 /**
24607  * Generate a constructor for a specific record layout.
24608  * @param {Array} o An Array of field definition objects which specify field names, and optionally,
24609  * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
24610  * Each field definition object may contain the following properties: <ul>
24611  * <li><b>name</b> : String<p style="margin-left:1em">The name by which the field is referenced within the Record. This is referenced by,
24612  * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
24613  * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
24614  * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
24615  * is being used, then this is a string containing the javascript expression to reference the data relative to 
24616  * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
24617  * to the data item relative to the record element. If the mapping expression is the same as the field name,
24618  * this may be omitted.</p></li>
24619  * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
24620  * <ul><li>auto (Default, implies no conversion)</li>
24621  * <li>string</li>
24622  * <li>int</li>
24623  * <li>float</li>
24624  * <li>boolean</li>
24625  * <li>date</li></ul></p></li>
24626  * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
24627  * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
24628  * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
24629  * by the Reader into an object that will be stored in the Record. It is passed the
24630  * following parameters:<ul>
24631  * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
24632  * </ul></p></li>
24633  * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
24634  * </ul>
24635  * <br>usage:<br><pre><code>
24636 var TopicRecord = Roo.data.Record.create(
24637     {name: 'title', mapping: 'topic_title'},
24638     {name: 'author', mapping: 'username'},
24639     {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
24640     {name: 'lastPost', mapping: 'post_time', type: 'date'},
24641     {name: 'lastPoster', mapping: 'user2'},
24642     {name: 'excerpt', mapping: 'post_text'}
24643 );
24644
24645 var myNewRecord = new TopicRecord({
24646     title: 'Do my job please',
24647     author: 'noobie',
24648     totalPosts: 1,
24649     lastPost: new Date(),
24650     lastPoster: 'Animal',
24651     excerpt: 'No way dude!'
24652 });
24653 myStore.add(myNewRecord);
24654 </code></pre>
24655  * @method create
24656  * @static
24657  */
24658 Roo.data.Record.create = function(o){
24659     var f = function(){
24660         f.superclass.constructor.apply(this, arguments);
24661     };
24662     Roo.extend(f, Roo.data.Record);
24663     var p = f.prototype;
24664     p.fields = new Roo.util.MixedCollection(false, function(field){
24665         return field.name;
24666     });
24667     for(var i = 0, len = o.length; i < len; i++){
24668         p.fields.add(new Roo.data.Field(o[i]));
24669     }
24670     f.getField = function(name){
24671         return p.fields.get(name);  
24672     };
24673     return f;
24674 };
24675
24676 Roo.data.Record.AUTO_ID = 1000;
24677 Roo.data.Record.EDIT = 'edit';
24678 Roo.data.Record.REJECT = 'reject';
24679 Roo.data.Record.COMMIT = 'commit';
24680
24681 Roo.data.Record.prototype = {
24682     /**
24683      * Readonly flag - true if this record has been modified.
24684      * @type Boolean
24685      */
24686     dirty : false,
24687     editing : false,
24688     error: null,
24689     modified: null,
24690
24691     // private
24692     join : function(store){
24693         this.store = store;
24694     },
24695
24696     /**
24697      * Set the named field to the specified value.
24698      * @param {String} name The name of the field to set.
24699      * @param {Object} value The value to set the field to.
24700      */
24701     set : function(name, value){
24702         if(this.data[name] == value){
24703             return;
24704         }
24705         this.dirty = true;
24706         if(!this.modified){
24707             this.modified = {};
24708         }
24709         if(typeof this.modified[name] == 'undefined'){
24710             this.modified[name] = this.data[name];
24711         }
24712         this.data[name] = value;
24713         if(!this.editing && this.store){
24714             this.store.afterEdit(this);
24715         }       
24716     },
24717
24718     /**
24719      * Get the value of the named field.
24720      * @param {String} name The name of the field to get the value of.
24721      * @return {Object} The value of the field.
24722      */
24723     get : function(name){
24724         return this.data[name]; 
24725     },
24726
24727     // private
24728     beginEdit : function(){
24729         this.editing = true;
24730         this.modified = {}; 
24731     },
24732
24733     // private
24734     cancelEdit : function(){
24735         this.editing = false;
24736         delete this.modified;
24737     },
24738
24739     // private
24740     endEdit : function(){
24741         this.editing = false;
24742         if(this.dirty && this.store){
24743             this.store.afterEdit(this);
24744         }
24745     },
24746
24747     /**
24748      * Usually called by the {@link Roo.data.Store} which owns the Record.
24749      * Rejects all changes made to the Record since either creation, or the last commit operation.
24750      * Modified fields are reverted to their original values.
24751      * <p>
24752      * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
24753      * of reject operations.
24754      */
24755     reject : function(){
24756         var m = this.modified;
24757         for(var n in m){
24758             if(typeof m[n] != "function"){
24759                 this.data[n] = m[n];
24760             }
24761         }
24762         this.dirty = false;
24763         delete this.modified;
24764         this.editing = false;
24765         if(this.store){
24766             this.store.afterReject(this);
24767         }
24768     },
24769
24770     /**
24771      * Usually called by the {@link Roo.data.Store} which owns the Record.
24772      * Commits all changes made to the Record since either creation, or the last commit operation.
24773      * <p>
24774      * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
24775      * of commit operations.
24776      */
24777     commit : function(){
24778         this.dirty = false;
24779         delete this.modified;
24780         this.editing = false;
24781         if(this.store){
24782             this.store.afterCommit(this);
24783         }
24784     },
24785
24786     // private
24787     hasError : function(){
24788         return this.error != null;
24789     },
24790
24791     // private
24792     clearError : function(){
24793         this.error = null;
24794     },
24795
24796     /**
24797      * Creates a copy of this record.
24798      * @param {String} id (optional) A new record id if you don't want to use this record's id
24799      * @return {Record}
24800      */
24801     copy : function(newId) {
24802         return new this.constructor(Roo.apply({}, this.data), newId || this.id);
24803     }
24804 };/*
24805  * Based on:
24806  * Ext JS Library 1.1.1
24807  * Copyright(c) 2006-2007, Ext JS, LLC.
24808  *
24809  * Originally Released Under LGPL - original licence link has changed is not relivant.
24810  *
24811  * Fork - LGPL
24812  * <script type="text/javascript">
24813  */
24814
24815
24816
24817 /**
24818  * @class Roo.data.Store
24819  * @extends Roo.util.Observable
24820  * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
24821  * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
24822  * <p>
24823  * A Store object uses an implementation of {@link Roo.data.DataProxy} to access a data object unless you call loadData() directly and pass in your data. The Store object
24824  * has no knowledge of the format of the data returned by the Proxy.<br>
24825  * <p>
24826  * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
24827  * instances from the data object. These records are cached and made available through accessor functions.
24828  * @constructor
24829  * Creates a new Store.
24830  * @param {Object} config A config object containing the objects needed for the Store to access data,
24831  * and read the data into Records.
24832  */
24833 Roo.data.Store = function(config){
24834     this.data = new Roo.util.MixedCollection(false);
24835     this.data.getKey = function(o){
24836         return o.id;
24837     };
24838     this.baseParams = {};
24839     // private
24840     this.paramNames = {
24841         "start" : "start",
24842         "limit" : "limit",
24843         "sort" : "sort",
24844         "dir" : "dir",
24845         "multisort" : "_multisort"
24846     };
24847
24848     if(config && config.data){
24849         this.inlineData = config.data;
24850         delete config.data;
24851     }
24852
24853     Roo.apply(this, config);
24854     
24855     if(this.reader){ // reader passed
24856         this.reader = Roo.factory(this.reader, Roo.data);
24857         this.reader.xmodule = this.xmodule || false;
24858         if(!this.recordType){
24859             this.recordType = this.reader.recordType;
24860         }
24861         if(this.reader.onMetaChange){
24862             this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
24863         }
24864     }
24865
24866     if(this.recordType){
24867         this.fields = this.recordType.prototype.fields;
24868     }
24869     this.modified = [];
24870
24871     this.addEvents({
24872         /**
24873          * @event datachanged
24874          * Fires when the data cache has changed, and a widget which is using this Store
24875          * as a Record cache should refresh its view.
24876          * @param {Store} this
24877          */
24878         datachanged : true,
24879         /**
24880          * @event metachange
24881          * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
24882          * @param {Store} this
24883          * @param {Object} meta The JSON metadata
24884          */
24885         metachange : true,
24886         /**
24887          * @event add
24888          * Fires when Records have been added to the Store
24889          * @param {Store} this
24890          * @param {Roo.data.Record[]} records The array of Records added
24891          * @param {Number} index The index at which the record(s) were added
24892          */
24893         add : true,
24894         /**
24895          * @event remove
24896          * Fires when a Record has been removed from the Store
24897          * @param {Store} this
24898          * @param {Roo.data.Record} record The Record that was removed
24899          * @param {Number} index The index at which the record was removed
24900          */
24901         remove : true,
24902         /**
24903          * @event update
24904          * Fires when a Record has been updated
24905          * @param {Store} this
24906          * @param {Roo.data.Record} record The Record that was updated
24907          * @param {String} operation The update operation being performed.  Value may be one of:
24908          * <pre><code>
24909  Roo.data.Record.EDIT
24910  Roo.data.Record.REJECT
24911  Roo.data.Record.COMMIT
24912          * </code></pre>
24913          */
24914         update : true,
24915         /**
24916          * @event clear
24917          * Fires when the data cache has been cleared.
24918          * @param {Store} this
24919          */
24920         clear : true,
24921         /**
24922          * @event beforeload
24923          * Fires before a request is made for a new data object.  If the beforeload handler returns false
24924          * the load action will be canceled.
24925          * @param {Store} this
24926          * @param {Object} options The loading options that were specified (see {@link #load} for details)
24927          */
24928         beforeload : true,
24929         /**
24930          * @event beforeloadadd
24931          * Fires after a new set of Records has been loaded.
24932          * @param {Store} this
24933          * @param {Roo.data.Record[]} records The Records that were loaded
24934          * @param {Object} options The loading options that were specified (see {@link #load} for details)
24935          */
24936         beforeloadadd : true,
24937         /**
24938          * @event load
24939          * Fires after a new set of Records has been loaded, before they are added to the store.
24940          * @param {Store} this
24941          * @param {Roo.data.Record[]} records The Records that were loaded
24942          * @param {Object} options The loading options that were specified (see {@link #load} for details)
24943          * @params {Object} return from reader
24944          */
24945         load : true,
24946         /**
24947          * @event loadexception
24948          * Fires if an exception occurs in the Proxy during loading.
24949          * Called with the signature of the Proxy's "loadexception" event.
24950          * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
24951          * 
24952          * @param {Proxy} 
24953          * @param {Object} return from JsonData.reader() - success, totalRecords, records
24954          * @param {Object} load options 
24955          * @param {Object} jsonData from your request (normally this contains the Exception)
24956          */
24957         loadexception : true
24958     });
24959     
24960     if(this.proxy){
24961         this.proxy = Roo.factory(this.proxy, Roo.data);
24962         this.proxy.xmodule = this.xmodule || false;
24963         this.relayEvents(this.proxy,  ["loadexception"]);
24964     }
24965     this.sortToggle = {};
24966     this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
24967
24968     Roo.data.Store.superclass.constructor.call(this);
24969
24970     if(this.inlineData){
24971         this.loadData(this.inlineData);
24972         delete this.inlineData;
24973     }
24974 };
24975
24976 Roo.extend(Roo.data.Store, Roo.util.Observable, {
24977      /**
24978     * @cfg {boolean} isLocal   flag if data is locally available (and can be always looked up
24979     * without a remote query - used by combo/forms at present.
24980     */
24981     
24982     /**
24983     * @cfg {Roo.data.DataProxy} proxy [required] The Proxy object which provides access to a data object.
24984     */
24985     /**
24986     * @cfg {Array} data Inline data to be loaded when the store is initialized.
24987     */
24988     /**
24989     * @cfg {Roo.data.DataReader} reader [required]  The Reader object which processes the data object and returns
24990     * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
24991     */
24992     /**
24993     * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
24994     * on any HTTP request
24995     */
24996     /**
24997     * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
24998     */
24999     /**
25000     * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
25001     */
25002     multiSort: false,
25003     /**
25004     * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
25005     * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
25006     */
25007     remoteSort : false,
25008
25009     /**
25010     * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
25011      * loaded or when a record is removed. (defaults to false).
25012     */
25013     pruneModifiedRecords : false,
25014
25015     // private
25016     lastOptions : null,
25017
25018     /**
25019      * Add Records to the Store and fires the add event.
25020      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
25021      */
25022     add : function(records){
25023         records = [].concat(records);
25024         for(var i = 0, len = records.length; i < len; i++){
25025             records[i].join(this);
25026         }
25027         var index = this.data.length;
25028         this.data.addAll(records);
25029         this.fireEvent("add", this, records, index);
25030     },
25031
25032     /**
25033      * Remove a Record from the Store and fires the remove event.
25034      * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
25035      */
25036     remove : function(record){
25037         var index = this.data.indexOf(record);
25038         this.data.removeAt(index);
25039  
25040         if(this.pruneModifiedRecords){
25041             this.modified.remove(record);
25042         }
25043         this.fireEvent("remove", this, record, index);
25044     },
25045
25046     /**
25047      * Remove all Records from the Store and fires the clear event.
25048      */
25049     removeAll : function(){
25050         this.data.clear();
25051         if(this.pruneModifiedRecords){
25052             this.modified = [];
25053         }
25054         this.fireEvent("clear", this);
25055     },
25056
25057     /**
25058      * Inserts Records to the Store at the given index and fires the add event.
25059      * @param {Number} index The start index at which to insert the passed Records.
25060      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
25061      */
25062     insert : function(index, records){
25063         records = [].concat(records);
25064         for(var i = 0, len = records.length; i < len; i++){
25065             this.data.insert(index, records[i]);
25066             records[i].join(this);
25067         }
25068         this.fireEvent("add", this, records, index);
25069     },
25070
25071     /**
25072      * Get the index within the cache of the passed Record.
25073      * @param {Roo.data.Record} record The Roo.data.Record object to to find.
25074      * @return {Number} The index of the passed Record. Returns -1 if not found.
25075      */
25076     indexOf : function(record){
25077         return this.data.indexOf(record);
25078     },
25079
25080     /**
25081      * Get the index within the cache of the Record with the passed id.
25082      * @param {String} id The id of the Record to find.
25083      * @return {Number} The index of the Record. Returns -1 if not found.
25084      */
25085     indexOfId : function(id){
25086         return this.data.indexOfKey(id);
25087     },
25088
25089     /**
25090      * Get the Record with the specified id.
25091      * @param {String} id The id of the Record to find.
25092      * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
25093      */
25094     getById : function(id){
25095         return this.data.key(id);
25096     },
25097
25098     /**
25099      * Get the Record at the specified index.
25100      * @param {Number} index The index of the Record to find.
25101      * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
25102      */
25103     getAt : function(index){
25104         return this.data.itemAt(index);
25105     },
25106
25107     /**
25108      * Returns a range of Records between specified indices.
25109      * @param {Number} startIndex (optional) The starting index (defaults to 0)
25110      * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
25111      * @return {Roo.data.Record[]} An array of Records
25112      */
25113     getRange : function(start, end){
25114         return this.data.getRange(start, end);
25115     },
25116
25117     // private
25118     storeOptions : function(o){
25119         o = Roo.apply({}, o);
25120         delete o.callback;
25121         delete o.scope;
25122         this.lastOptions = o;
25123     },
25124
25125     /**
25126      * Loads the Record cache from the configured Proxy using the configured Reader.
25127      * <p>
25128      * If using remote paging, then the first load call must specify the <em>start</em>
25129      * and <em>limit</em> properties in the options.params property to establish the initial
25130      * position within the dataset, and the number of Records to cache on each read from the Proxy.
25131      * <p>
25132      * <strong>It is important to note that for remote data sources, loading is asynchronous,
25133      * and this call will return before the new data has been loaded. Perform any post-processing
25134      * in a callback function, or in a "load" event handler.</strong>
25135      * <p>
25136      * @param {Object} options An object containing properties which control loading options:<ul>
25137      * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
25138      * <li>params.data {Object} if you are using a MemoryProxy / JsonReader, use this as the data to load stuff..
25139      * <pre>
25140                 {
25141                     data : data,  // array of key=>value data like JsonReader
25142                     total : data.length,
25143                     success : true
25144                     
25145                 }
25146         </pre>
25147             }.</li>
25148      * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
25149      * passed the following arguments:<ul>
25150      * <li>r : Roo.data.Record[]</li>
25151      * <li>options: Options object from the load call</li>
25152      * <li>success: Boolean success indicator</li></ul></li>
25153      * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
25154      * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
25155      * </ul>
25156      */
25157     load : function(options){
25158         options = options || {};
25159         if(this.fireEvent("beforeload", this, options) !== false){
25160             this.storeOptions(options);
25161             var p = Roo.apply(options.params || {}, this.baseParams);
25162             // if meta was not loaded from remote source.. try requesting it.
25163             if (!this.reader.metaFromRemote) {
25164                 p._requestMeta = 1;
25165             }
25166             if(this.sortInfo && this.remoteSort){
25167                 var pn = this.paramNames;
25168                 p[pn["sort"]] = this.sortInfo.field;
25169                 p[pn["dir"]] = this.sortInfo.direction;
25170             }
25171             if (this.multiSort) {
25172                 var pn = this.paramNames;
25173                 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
25174             }
25175             
25176             this.proxy.load(p, this.reader, this.loadRecords, this, options);
25177         }
25178     },
25179
25180     /**
25181      * Reloads the Record cache from the configured Proxy using the configured Reader and
25182      * the options from the last load operation performed.
25183      * @param {Object} options (optional) An object containing properties which may override the options
25184      * used in the last load operation. See {@link #load} for details (defaults to null, in which case
25185      * the most recently used options are reused).
25186      */
25187     reload : function(options){
25188         this.load(Roo.applyIf(options||{}, this.lastOptions));
25189     },
25190
25191     // private
25192     // Called as a callback by the Reader during a load operation.
25193     loadRecords : function(o, options, success){
25194          
25195         if(!o){
25196             if(success !== false){
25197                 this.fireEvent("load", this, [], options, o);
25198             }
25199             if(options.callback){
25200                 options.callback.call(options.scope || this, [], options, false);
25201             }
25202             return;
25203         }
25204         // if data returned failure - throw an exception.
25205         if (o.success === false) {
25206             // show a message if no listener is registered.
25207             if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
25208                     Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
25209             }
25210             // loadmask wil be hooked into this..
25211             this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
25212             return;
25213         }
25214         var r = o.records, t = o.totalRecords || r.length;
25215         
25216         this.fireEvent("beforeloadadd", this, r, options, o);
25217         
25218         if(!options || options.add !== true){
25219             if(this.pruneModifiedRecords){
25220                 this.modified = [];
25221             }
25222             for(var i = 0, len = r.length; i < len; i++){
25223                 r[i].join(this);
25224             }
25225             if(this.snapshot){
25226                 this.data = this.snapshot;
25227                 delete this.snapshot;
25228             }
25229             this.data.clear();
25230             this.data.addAll(r);
25231             this.totalLength = t;
25232             this.applySort();
25233             this.fireEvent("datachanged", this);
25234         }else{
25235             this.totalLength = Math.max(t, this.data.length+r.length);
25236             this.add(r);
25237         }
25238         
25239         if(this.parent && !Roo.isIOS && !this.useNativeIOS && this.parent.emptyTitle.length) {
25240                 
25241             var e = new Roo.data.Record({});
25242
25243             e.set(this.parent.displayField, this.parent.emptyTitle);
25244             e.set(this.parent.valueField, '');
25245
25246             this.insert(0, e);
25247         }
25248             
25249         this.fireEvent("load", this, r, options, o);
25250         if(options.callback){
25251             options.callback.call(options.scope || this, r, options, true);
25252         }
25253     },
25254
25255
25256     /**
25257      * Loads data from a passed data block. A Reader which understands the format of the data
25258      * must have been configured in the constructor.
25259      * @param {Object} data The data block from which to read the Records.  The format of the data expected
25260      * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
25261      * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
25262      */
25263     loadData : function(o, append){
25264         var r = this.reader.readRecords(o);
25265         this.loadRecords(r, {add: append}, true);
25266     },
25267     
25268      /**
25269      * using 'cn' the nested child reader read the child array into it's child stores.
25270      * @param {Object} rec The record with a 'children array
25271      */
25272     loadDataFromChildren : function(rec)
25273     {
25274         this.loadData(this.reader.toLoadData(rec));
25275     },
25276     
25277
25278     /**
25279      * Gets the number of cached records.
25280      * <p>
25281      * <em>If using paging, this may not be the total size of the dataset. If the data object
25282      * used by the Reader contains the dataset size, then the getTotalCount() function returns
25283      * the data set size</em>
25284      */
25285     getCount : function(){
25286         return this.data.length || 0;
25287     },
25288
25289     /**
25290      * Gets the total number of records in the dataset as returned by the server.
25291      * <p>
25292      * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
25293      * the dataset size</em>
25294      */
25295     getTotalCount : function(){
25296         return this.totalLength || 0;
25297     },
25298
25299     /**
25300      * Returns the sort state of the Store as an object with two properties:
25301      * <pre><code>
25302  field {String} The name of the field by which the Records are sorted
25303  direction {String} The sort order, "ASC" or "DESC"
25304      * </code></pre>
25305      */
25306     getSortState : function(){
25307         return this.sortInfo;
25308     },
25309
25310     // private
25311     applySort : function(){
25312         if(this.sortInfo && !this.remoteSort){
25313             var s = this.sortInfo, f = s.field;
25314             var st = this.fields.get(f).sortType;
25315             var fn = function(r1, r2){
25316                 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
25317                 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
25318             };
25319             this.data.sort(s.direction, fn);
25320             if(this.snapshot && this.snapshot != this.data){
25321                 this.snapshot.sort(s.direction, fn);
25322             }
25323         }
25324     },
25325
25326     /**
25327      * Sets the default sort column and order to be used by the next load operation.
25328      * @param {String} fieldName The name of the field to sort by.
25329      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
25330      */
25331     setDefaultSort : function(field, dir){
25332         this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
25333     },
25334
25335     /**
25336      * Sort the Records.
25337      * If remote sorting is used, the sort is performed on the server, and the cache is
25338      * reloaded. If local sorting is used, the cache is sorted internally.
25339      * @param {String} fieldName The name of the field to sort by.
25340      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
25341      */
25342     sort : function(fieldName, dir){
25343         var f = this.fields.get(fieldName);
25344         if(!dir){
25345             this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
25346             
25347             if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
25348                 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
25349             }else{
25350                 dir = f.sortDir;
25351             }
25352         }
25353         this.sortToggle[f.name] = dir;
25354         this.sortInfo = {field: f.name, direction: dir};
25355         if(!this.remoteSort){
25356             this.applySort();
25357             this.fireEvent("datachanged", this);
25358         }else{
25359             this.load(this.lastOptions);
25360         }
25361     },
25362
25363     /**
25364      * Calls the specified function for each of the Records in the cache.
25365      * @param {Function} fn The function to call. The Record is passed as the first parameter.
25366      * Returning <em>false</em> aborts and exits the iteration.
25367      * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
25368      */
25369     each : function(fn, scope){
25370         this.data.each(fn, scope);
25371     },
25372
25373     /**
25374      * Gets all records modified since the last commit.  Modified records are persisted across load operations
25375      * (e.g., during paging).
25376      * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
25377      */
25378     getModifiedRecords : function(){
25379         return this.modified;
25380     },
25381
25382     // private
25383     createFilterFn : function(property, value, anyMatch){
25384         if(!value.exec){ // not a regex
25385             value = String(value);
25386             if(value.length == 0){
25387                 return false;
25388             }
25389             value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
25390         }
25391         return function(r){
25392             return value.test(r.data[property]);
25393         };
25394     },
25395
25396     /**
25397      * Sums the value of <i>property</i> for each record between start and end and returns the result.
25398      * @param {String} property A field on your records
25399      * @param {Number} start The record index to start at (defaults to 0)
25400      * @param {Number} end The last record index to include (defaults to length - 1)
25401      * @return {Number} The sum
25402      */
25403     sum : function(property, start, end){
25404         var rs = this.data.items, v = 0;
25405         start = start || 0;
25406         end = (end || end === 0) ? end : rs.length-1;
25407
25408         for(var i = start; i <= end; i++){
25409             v += (rs[i].data[property] || 0);
25410         }
25411         return v;
25412     },
25413
25414     /**
25415      * Filter the records by a specified property.
25416      * @param {String} field A field on your records
25417      * @param {String/RegExp} value Either a string that the field
25418      * should start with or a RegExp to test against the field
25419      * @param {Boolean} anyMatch True to match any part not just the beginning
25420      */
25421     filter : function(property, value, anyMatch){
25422         var fn = this.createFilterFn(property, value, anyMatch);
25423         return fn ? this.filterBy(fn) : this.clearFilter();
25424     },
25425
25426     /**
25427      * Filter by a function. The specified function will be called with each
25428      * record in this data source. If the function returns true the record is included,
25429      * otherwise it is filtered.
25430      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
25431      * @param {Object} scope (optional) The scope of the function (defaults to this)
25432      */
25433     filterBy : function(fn, scope){
25434         this.snapshot = this.snapshot || this.data;
25435         this.data = this.queryBy(fn, scope||this);
25436         this.fireEvent("datachanged", this);
25437     },
25438
25439     /**
25440      * Query the records by a specified property.
25441      * @param {String} field A field on your records
25442      * @param {String/RegExp} value Either a string that the field
25443      * should start with or a RegExp to test against the field
25444      * @param {Boolean} anyMatch True to match any part not just the beginning
25445      * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
25446      */
25447     query : function(property, value, anyMatch){
25448         var fn = this.createFilterFn(property, value, anyMatch);
25449         return fn ? this.queryBy(fn) : this.data.clone();
25450     },
25451
25452     /**
25453      * Query by a function. The specified function will be called with each
25454      * record in this data source. If the function returns true the record is included
25455      * in the results.
25456      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
25457      * @param {Object} scope (optional) The scope of the function (defaults to this)
25458       @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
25459      **/
25460     queryBy : function(fn, scope){
25461         var data = this.snapshot || this.data;
25462         return data.filterBy(fn, scope||this);
25463     },
25464
25465     /**
25466      * Collects unique values for a particular dataIndex from this store.
25467      * @param {String} dataIndex The property to collect
25468      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
25469      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
25470      * @return {Array} An array of the unique values
25471      **/
25472     collect : function(dataIndex, allowNull, bypassFilter){
25473         var d = (bypassFilter === true && this.snapshot) ?
25474                 this.snapshot.items : this.data.items;
25475         var v, sv, r = [], l = {};
25476         for(var i = 0, len = d.length; i < len; i++){
25477             v = d[i].data[dataIndex];
25478             sv = String(v);
25479             if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
25480                 l[sv] = true;
25481                 r[r.length] = v;
25482             }
25483         }
25484         return r;
25485     },
25486
25487     /**
25488      * Revert to a view of the Record cache with no filtering applied.
25489      * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
25490      */
25491     clearFilter : function(suppressEvent){
25492         if(this.snapshot && this.snapshot != this.data){
25493             this.data = this.snapshot;
25494             delete this.snapshot;
25495             if(suppressEvent !== true){
25496                 this.fireEvent("datachanged", this);
25497             }
25498         }
25499     },
25500
25501     // private
25502     afterEdit : function(record){
25503         if(this.modified.indexOf(record) == -1){
25504             this.modified.push(record);
25505         }
25506         this.fireEvent("update", this, record, Roo.data.Record.EDIT);
25507     },
25508     
25509     // private
25510     afterReject : function(record){
25511         this.modified.remove(record);
25512         this.fireEvent("update", this, record, Roo.data.Record.REJECT);
25513     },
25514
25515     // private
25516     afterCommit : function(record){
25517         this.modified.remove(record);
25518         this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
25519     },
25520
25521     /**
25522      * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
25523      * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
25524      */
25525     commitChanges : function(){
25526         var m = this.modified.slice(0);
25527         this.modified = [];
25528         for(var i = 0, len = m.length; i < len; i++){
25529             m[i].commit();
25530         }
25531     },
25532
25533     /**
25534      * Cancel outstanding changes on all changed records.
25535      */
25536     rejectChanges : function(){
25537         var m = this.modified.slice(0);
25538         this.modified = [];
25539         for(var i = 0, len = m.length; i < len; i++){
25540             m[i].reject();
25541         }
25542     },
25543
25544     onMetaChange : function(meta, rtype, o){
25545         this.recordType = rtype;
25546         this.fields = rtype.prototype.fields;
25547         delete this.snapshot;
25548         this.sortInfo = meta.sortInfo || this.sortInfo;
25549         this.modified = [];
25550         this.fireEvent('metachange', this, this.reader.meta);
25551     },
25552     
25553     moveIndex : function(data, type)
25554     {
25555         var index = this.indexOf(data);
25556         
25557         var newIndex = index + type;
25558         
25559         this.remove(data);
25560         
25561         this.insert(newIndex, data);
25562         
25563     }
25564 });/*
25565  * Based on:
25566  * Ext JS Library 1.1.1
25567  * Copyright(c) 2006-2007, Ext JS, LLC.
25568  *
25569  * Originally Released Under LGPL - original licence link has changed is not relivant.
25570  *
25571  * Fork - LGPL
25572  * <script type="text/javascript">
25573  */
25574
25575 /**
25576  * @class Roo.data.SimpleStore
25577  * @extends Roo.data.Store
25578  * Small helper class to make creating Stores from Array data easier.
25579  * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
25580  * @cfg {Array} fields An array of field definition objects, or field name strings.
25581  * @cfg {Object} an existing reader (eg. copied from another store)
25582  * @cfg {Array} data The multi-dimensional array of data
25583  * @cfg {Roo.data.DataProxy} proxy [not-required]  
25584  * @cfg {Roo.data.Reader} reader  [not-required] 
25585  * @constructor
25586  * @param {Object} config
25587  */
25588 Roo.data.SimpleStore = function(config)
25589 {
25590     Roo.data.SimpleStore.superclass.constructor.call(this, {
25591         isLocal : true,
25592         reader: typeof(config.reader) != 'undefined' ? config.reader : new Roo.data.ArrayReader({
25593                 id: config.id
25594             },
25595             Roo.data.Record.create(config.fields)
25596         ),
25597         proxy : new Roo.data.MemoryProxy(config.data)
25598     });
25599     this.load();
25600 };
25601 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
25602  * Based on:
25603  * Ext JS Library 1.1.1
25604  * Copyright(c) 2006-2007, Ext JS, LLC.
25605  *
25606  * Originally Released Under LGPL - original licence link has changed is not relivant.
25607  *
25608  * Fork - LGPL
25609  * <script type="text/javascript">
25610  */
25611
25612 /**
25613 /**
25614  * @extends Roo.data.Store
25615  * @class Roo.data.JsonStore
25616  * Small helper class to make creating Stores for JSON data easier. <br/>
25617 <pre><code>
25618 var store = new Roo.data.JsonStore({
25619     url: 'get-images.php',
25620     root: 'images',
25621     fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
25622 });
25623 </code></pre>
25624  * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
25625  * JsonReader and HttpProxy (unless inline data is provided).</b>
25626  * @cfg {Array} fields An array of field definition objects, or field name strings.
25627  * @constructor
25628  * @param {Object} config
25629  */
25630 Roo.data.JsonStore = function(c){
25631     Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
25632         proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
25633         reader: new Roo.data.JsonReader(c, c.fields)
25634     }));
25635 };
25636 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
25637  * Based on:
25638  * Ext JS Library 1.1.1
25639  * Copyright(c) 2006-2007, Ext JS, LLC.
25640  *
25641  * Originally Released Under LGPL - original licence link has changed is not relivant.
25642  *
25643  * Fork - LGPL
25644  * <script type="text/javascript">
25645  */
25646
25647  
25648 Roo.data.Field = function(config){
25649     if(typeof config == "string"){
25650         config = {name: config};
25651     }
25652     Roo.apply(this, config);
25653     
25654     if(!this.type){
25655         this.type = "auto";
25656     }
25657     
25658     var st = Roo.data.SortTypes;
25659     // named sortTypes are supported, here we look them up
25660     if(typeof this.sortType == "string"){
25661         this.sortType = st[this.sortType];
25662     }
25663     
25664     // set default sortType for strings and dates
25665     if(!this.sortType){
25666         switch(this.type){
25667             case "string":
25668                 this.sortType = st.asUCString;
25669                 break;
25670             case "date":
25671                 this.sortType = st.asDate;
25672                 break;
25673             default:
25674                 this.sortType = st.none;
25675         }
25676     }
25677
25678     // define once
25679     var stripRe = /[\$,%]/g;
25680
25681     // prebuilt conversion function for this field, instead of
25682     // switching every time we're reading a value
25683     if(!this.convert){
25684         var cv, dateFormat = this.dateFormat;
25685         switch(this.type){
25686             case "":
25687             case "auto":
25688             case undefined:
25689                 cv = function(v){ return v; };
25690                 break;
25691             case "string":
25692                 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
25693                 break;
25694             case "int":
25695                 cv = function(v){
25696                     return v !== undefined && v !== null && v !== '' ?
25697                            parseInt(String(v).replace(stripRe, ""), 10) : '';
25698                     };
25699                 break;
25700             case "float":
25701                 cv = function(v){
25702                     return v !== undefined && v !== null && v !== '' ?
25703                            parseFloat(String(v).replace(stripRe, ""), 10) : ''; 
25704                     };
25705                 break;
25706             case "bool":
25707             case "boolean":
25708                 cv = function(v){ return v === true || v === "true" || v == 1; };
25709                 break;
25710             case "date":
25711                 cv = function(v){
25712                     if(!v){
25713                         return '';
25714                     }
25715                     if(v instanceof Date){
25716                         return v;
25717                     }
25718                     if(dateFormat){
25719                         if(dateFormat == "timestamp"){
25720                             return new Date(v*1000);
25721                         }
25722                         return Date.parseDate(v, dateFormat);
25723                     }
25724                     var parsed = Date.parse(v);
25725                     return parsed ? new Date(parsed) : null;
25726                 };
25727              break;
25728             
25729         }
25730         this.convert = cv;
25731     }
25732 };
25733
25734 Roo.data.Field.prototype = {
25735     dateFormat: null,
25736     defaultValue: "",
25737     mapping: null,
25738     sortType : null,
25739     sortDir : "ASC"
25740 };/*
25741  * Based on:
25742  * Ext JS Library 1.1.1
25743  * Copyright(c) 2006-2007, Ext JS, LLC.
25744  *
25745  * Originally Released Under LGPL - original licence link has changed is not relivant.
25746  *
25747  * Fork - LGPL
25748  * <script type="text/javascript">
25749  */
25750  
25751 // Base class for reading structured data from a data source.  This class is intended to be
25752 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
25753
25754 /**
25755  * @class Roo.data.DataReader
25756  * @abstract
25757  * Base class for reading structured data from a data source.  This class is intended to be
25758  * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
25759  */
25760
25761 Roo.data.DataReader = function(meta, recordType){
25762     
25763     this.meta = meta;
25764     
25765     this.recordType = recordType instanceof Array ? 
25766         Roo.data.Record.create(recordType) : recordType;
25767 };
25768
25769 Roo.data.DataReader.prototype = {
25770     
25771     
25772     readerType : 'Data',
25773      /**
25774      * Create an empty record
25775      * @param {Object} data (optional) - overlay some values
25776      * @return {Roo.data.Record} record created.
25777      */
25778     newRow :  function(d) {
25779         var da =  {};
25780         this.recordType.prototype.fields.each(function(c) {
25781             switch( c.type) {
25782                 case 'int' : da[c.name] = 0; break;
25783                 case 'date' : da[c.name] = new Date(); break;
25784                 case 'float' : da[c.name] = 0.0; break;
25785                 case 'boolean' : da[c.name] = false; break;
25786                 default : da[c.name] = ""; break;
25787             }
25788             
25789         });
25790         return new this.recordType(Roo.apply(da, d));
25791     }
25792     
25793     
25794 };/*
25795  * Based on:
25796  * Ext JS Library 1.1.1
25797  * Copyright(c) 2006-2007, Ext JS, LLC.
25798  *
25799  * Originally Released Under LGPL - original licence link has changed is not relivant.
25800  *
25801  * Fork - LGPL
25802  * <script type="text/javascript">
25803  */
25804
25805 /**
25806  * @class Roo.data.DataProxy
25807  * @extends Roo.util.Observable
25808  * @abstract
25809  * This class is an abstract base class for implementations which provide retrieval of
25810  * unformatted data objects.<br>
25811  * <p>
25812  * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
25813  * (of the appropriate type which knows how to parse the data object) to provide a block of
25814  * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
25815  * <p>
25816  * Custom implementations must implement the load method as described in
25817  * {@link Roo.data.HttpProxy#load}.
25818  */
25819 Roo.data.DataProxy = function(){
25820     this.addEvents({
25821         /**
25822          * @event beforeload
25823          * Fires before a network request is made to retrieve a data object.
25824          * @param {Object} This DataProxy object.
25825          * @param {Object} params The params parameter to the load function.
25826          */
25827         beforeload : true,
25828         /**
25829          * @event load
25830          * Fires before the load method's callback is called.
25831          * @param {Object} This DataProxy object.
25832          * @param {Object} o The data object.
25833          * @param {Object} arg The callback argument object passed to the load function.
25834          */
25835         load : true,
25836         /**
25837          * @event loadexception
25838          * Fires if an Exception occurs during data retrieval.
25839          * @param {Object} This DataProxy object.
25840          * @param {Object} o The data object.
25841          * @param {Object} arg The callback argument object passed to the load function.
25842          * @param {Object} e The Exception.
25843          */
25844         loadexception : true
25845     });
25846     Roo.data.DataProxy.superclass.constructor.call(this);
25847 };
25848
25849 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
25850
25851     /**
25852      * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
25853      */
25854 /*
25855  * Based on:
25856  * Ext JS Library 1.1.1
25857  * Copyright(c) 2006-2007, Ext JS, LLC.
25858  *
25859  * Originally Released Under LGPL - original licence link has changed is not relivant.
25860  *
25861  * Fork - LGPL
25862  * <script type="text/javascript">
25863  */
25864 /**
25865  * @class Roo.data.MemoryProxy
25866  * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
25867  * to the Reader when its load method is called.
25868  * @constructor
25869  * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
25870  */
25871 Roo.data.MemoryProxy = function(data){
25872     if (data.data) {
25873         data = data.data;
25874     }
25875     Roo.data.MemoryProxy.superclass.constructor.call(this);
25876     this.data = data;
25877 };
25878
25879 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
25880     
25881     /**
25882      * Load data from the requested source (in this case an in-memory
25883      * data object passed to the constructor), read the data object into
25884      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
25885      * process that block using the passed callback.
25886      * @param {Object} params This parameter is not used by the MemoryProxy class.
25887      * @param {Roo.data.DataReader} reader The Reader object which converts the data
25888      * object into a block of Roo.data.Records.
25889      * @param {Function} callback The function into which to pass the block of Roo.data.records.
25890      * The function must be passed <ul>
25891      * <li>The Record block object</li>
25892      * <li>The "arg" argument from the load function</li>
25893      * <li>A boolean success indicator</li>
25894      * </ul>
25895      * @param {Object} scope The scope in which to call the callback
25896      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
25897      */
25898     load : function(params, reader, callback, scope, arg){
25899         params = params || {};
25900         var result;
25901         try {
25902             result = reader.readRecords(params.data ? params.data :this.data);
25903         }catch(e){
25904             this.fireEvent("loadexception", this, arg, null, e);
25905             callback.call(scope, null, arg, false);
25906             return;
25907         }
25908         callback.call(scope, result, arg, true);
25909     },
25910     
25911     // private
25912     update : function(params, records){
25913         
25914     }
25915 });/*
25916  * Based on:
25917  * Ext JS Library 1.1.1
25918  * Copyright(c) 2006-2007, Ext JS, LLC.
25919  *
25920  * Originally Released Under LGPL - original licence link has changed is not relivant.
25921  *
25922  * Fork - LGPL
25923  * <script type="text/javascript">
25924  */
25925 /**
25926  * @class Roo.data.HttpProxy
25927  * @extends Roo.data.DataProxy
25928  * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
25929  * configured to reference a certain URL.<br><br>
25930  * <p>
25931  * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
25932  * from which the running page was served.<br><br>
25933  * <p>
25934  * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
25935  * <p>
25936  * Be aware that to enable the browser to parse an XML document, the server must set
25937  * the Content-Type header in the HTTP response to "text/xml".
25938  * @constructor
25939  * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
25940  * an {@link Roo.data.Connection} object.  If a Connection config is passed, the singleton {@link Roo.Ajax} object
25941  * will be used to make the request.
25942  */
25943 Roo.data.HttpProxy = function(conn){
25944     Roo.data.HttpProxy.superclass.constructor.call(this);
25945     // is conn a conn config or a real conn?
25946     this.conn = conn;
25947     this.useAjax = !conn || !conn.events;
25948   
25949 };
25950
25951 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
25952     // thse are take from connection...
25953     
25954     /**
25955      * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
25956      */
25957     /**
25958      * @cfg {Object} extraParams (Optional) An object containing properties which are used as
25959      * extra parameters to each request made by this object. (defaults to undefined)
25960      */
25961     /**
25962      * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
25963      *  to each request made by this object. (defaults to undefined)
25964      */
25965     /**
25966      * @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)
25967      */
25968     /**
25969      * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
25970      */
25971      /**
25972      * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
25973      * @type Boolean
25974      */
25975   
25976
25977     /**
25978      * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
25979      * @type Boolean
25980      */
25981     /**
25982      * Return the {@link Roo.data.Connection} object being used by this Proxy.
25983      * @return {Connection} The Connection object. This object may be used to subscribe to events on
25984      * a finer-grained basis than the DataProxy events.
25985      */
25986     getConnection : function(){
25987         return this.useAjax ? Roo.Ajax : this.conn;
25988     },
25989
25990     /**
25991      * Load data from the configured {@link Roo.data.Connection}, read the data object into
25992      * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
25993      * process that block using the passed callback.
25994      * @param {Object} params An object containing properties which are to be used as HTTP parameters
25995      * for the request to the remote server.
25996      * @param {Roo.data.DataReader} reader The Reader object which converts the data
25997      * object into a block of Roo.data.Records.
25998      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
25999      * The function must be passed <ul>
26000      * <li>The Record block object</li>
26001      * <li>The "arg" argument from the load function</li>
26002      * <li>A boolean success indicator</li>
26003      * </ul>
26004      * @param {Object} scope The scope in which to call the callback
26005      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
26006      */
26007     load : function(params, reader, callback, scope, arg){
26008         if(this.fireEvent("beforeload", this, params) !== false){
26009             var  o = {
26010                 params : params || {},
26011                 request: {
26012                     callback : callback,
26013                     scope : scope,
26014                     arg : arg
26015                 },
26016                 reader: reader,
26017                 callback : this.loadResponse,
26018                 scope: this
26019             };
26020             if(this.useAjax){
26021                 Roo.applyIf(o, this.conn);
26022                 if(this.activeRequest){
26023                     Roo.Ajax.abort(this.activeRequest);
26024                 }
26025                 this.activeRequest = Roo.Ajax.request(o);
26026             }else{
26027                 this.conn.request(o);
26028             }
26029         }else{
26030             callback.call(scope||this, null, arg, false);
26031         }
26032     },
26033
26034     // private
26035     loadResponse : function(o, success, response){
26036         delete this.activeRequest;
26037         if(!success){
26038             this.fireEvent("loadexception", this, o, response);
26039             o.request.callback.call(o.request.scope, null, o.request.arg, false);
26040             return;
26041         }
26042         var result;
26043         try {
26044             result = o.reader.read(response);
26045         }catch(e){
26046             o.success = false;
26047             o.raw = { errorMsg : response.responseText };
26048             this.fireEvent("loadexception", this, o, response, e);
26049             o.request.callback.call(o.request.scope, o, o.request.arg, false);
26050             return;
26051         }
26052         
26053         this.fireEvent("load", this, o, o.request.arg);
26054         o.request.callback.call(o.request.scope, result, o.request.arg, true);
26055     },
26056
26057     // private
26058     update : function(dataSet){
26059
26060     },
26061
26062     // private
26063     updateResponse : function(dataSet){
26064
26065     }
26066 });/*
26067  * Based on:
26068  * Ext JS Library 1.1.1
26069  * Copyright(c) 2006-2007, Ext JS, LLC.
26070  *
26071  * Originally Released Under LGPL - original licence link has changed is not relivant.
26072  *
26073  * Fork - LGPL
26074  * <script type="text/javascript">
26075  */
26076
26077 /**
26078  * @class Roo.data.ScriptTagProxy
26079  * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
26080  * other than the originating domain of the running page.<br><br>
26081  * <p>
26082  * <em>Note that if you are retrieving data from a page that is in a domain that is NOT the same as the originating domain
26083  * of the running page, you must use this class, rather than DataProxy.</em><br><br>
26084  * <p>
26085  * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
26086  * source code that is used as the source inside a &lt;script> tag.<br><br>
26087  * <p>
26088  * In order for the browser to process the returned data, the server must wrap the data object
26089  * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
26090  * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
26091  * depending on whether the callback name was passed:
26092  * <p>
26093  * <pre><code>
26094 boolean scriptTag = false;
26095 String cb = request.getParameter("callback");
26096 if (cb != null) {
26097     scriptTag = true;
26098     response.setContentType("text/javascript");
26099 } else {
26100     response.setContentType("application/x-json");
26101 }
26102 Writer out = response.getWriter();
26103 if (scriptTag) {
26104     out.write(cb + "(");
26105 }
26106 out.print(dataBlock.toJsonString());
26107 if (scriptTag) {
26108     out.write(");");
26109 }
26110 </pre></code>
26111  *
26112  * @constructor
26113  * @param {Object} config A configuration object.
26114  */
26115 Roo.data.ScriptTagProxy = function(config){
26116     Roo.data.ScriptTagProxy.superclass.constructor.call(this);
26117     Roo.apply(this, config);
26118     this.head = document.getElementsByTagName("head")[0];
26119 };
26120
26121 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
26122
26123 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
26124     /**
26125      * @cfg {String} url The URL from which to request the data object.
26126      */
26127     /**
26128      * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
26129      */
26130     timeout : 30000,
26131     /**
26132      * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
26133      * the server the name of the callback function set up by the load call to process the returned data object.
26134      * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
26135      * javascript output which calls this named function passing the data object as its only parameter.
26136      */
26137     callbackParam : "callback",
26138     /**
26139      *  @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
26140      * name to the request.
26141      */
26142     nocache : true,
26143
26144     /**
26145      * Load data from the configured URL, read the data object into
26146      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
26147      * process that block using the passed callback.
26148      * @param {Object} params An object containing properties which are to be used as HTTP parameters
26149      * for the request to the remote server.
26150      * @param {Roo.data.DataReader} reader The Reader object which converts the data
26151      * object into a block of Roo.data.Records.
26152      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
26153      * The function must be passed <ul>
26154      * <li>The Record block object</li>
26155      * <li>The "arg" argument from the load function</li>
26156      * <li>A boolean success indicator</li>
26157      * </ul>
26158      * @param {Object} scope The scope in which to call the callback
26159      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
26160      */
26161     load : function(params, reader, callback, scope, arg){
26162         if(this.fireEvent("beforeload", this, params) !== false){
26163
26164             var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
26165
26166             var url = this.url;
26167             url += (url.indexOf("?") != -1 ? "&" : "?") + p;
26168             if(this.nocache){
26169                 url += "&_dc=" + (new Date().getTime());
26170             }
26171             var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
26172             var trans = {
26173                 id : transId,
26174                 cb : "stcCallback"+transId,
26175                 scriptId : "stcScript"+transId,
26176                 params : params,
26177                 arg : arg,
26178                 url : url,
26179                 callback : callback,
26180                 scope : scope,
26181                 reader : reader
26182             };
26183             var conn = this;
26184
26185             window[trans.cb] = function(o){
26186                 conn.handleResponse(o, trans);
26187             };
26188
26189             url += String.format("&{0}={1}", this.callbackParam, trans.cb);
26190
26191             if(this.autoAbort !== false){
26192                 this.abort();
26193             }
26194
26195             trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
26196
26197             var script = document.createElement("script");
26198             script.setAttribute("src", url);
26199             script.setAttribute("type", "text/javascript");
26200             script.setAttribute("id", trans.scriptId);
26201             this.head.appendChild(script);
26202
26203             this.trans = trans;
26204         }else{
26205             callback.call(scope||this, null, arg, false);
26206         }
26207     },
26208
26209     // private
26210     isLoading : function(){
26211         return this.trans ? true : false;
26212     },
26213
26214     /**
26215      * Abort the current server request.
26216      */
26217     abort : function(){
26218         if(this.isLoading()){
26219             this.destroyTrans(this.trans);
26220         }
26221     },
26222
26223     // private
26224     destroyTrans : function(trans, isLoaded){
26225         this.head.removeChild(document.getElementById(trans.scriptId));
26226         clearTimeout(trans.timeoutId);
26227         if(isLoaded){
26228             window[trans.cb] = undefined;
26229             try{
26230                 delete window[trans.cb];
26231             }catch(e){}
26232         }else{
26233             // if hasn't been loaded, wait for load to remove it to prevent script error
26234             window[trans.cb] = function(){
26235                 window[trans.cb] = undefined;
26236                 try{
26237                     delete window[trans.cb];
26238                 }catch(e){}
26239             };
26240         }
26241     },
26242
26243     // private
26244     handleResponse : function(o, trans){
26245         this.trans = false;
26246         this.destroyTrans(trans, true);
26247         var result;
26248         try {
26249             result = trans.reader.readRecords(o);
26250         }catch(e){
26251             this.fireEvent("loadexception", this, o, trans.arg, e);
26252             trans.callback.call(trans.scope||window, null, trans.arg, false);
26253             return;
26254         }
26255         this.fireEvent("load", this, o, trans.arg);
26256         trans.callback.call(trans.scope||window, result, trans.arg, true);
26257     },
26258
26259     // private
26260     handleFailure : function(trans){
26261         this.trans = false;
26262         this.destroyTrans(trans, false);
26263         this.fireEvent("loadexception", this, null, trans.arg);
26264         trans.callback.call(trans.scope||window, null, trans.arg, false);
26265     }
26266 });/*
26267  * Based on:
26268  * Ext JS Library 1.1.1
26269  * Copyright(c) 2006-2007, Ext JS, LLC.
26270  *
26271  * Originally Released Under LGPL - original licence link has changed is not relivant.
26272  *
26273  * Fork - LGPL
26274  * <script type="text/javascript">
26275  */
26276
26277 /**
26278  * @class Roo.data.JsonReader
26279  * @extends Roo.data.DataReader
26280  * Data reader class to create an Array of Roo.data.Record objects from a JSON response
26281  * based on mappings in a provided Roo.data.Record constructor.
26282  * 
26283  * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
26284  * in the reply previously. 
26285  * 
26286  * <p>
26287  * Example code:
26288  * <pre><code>
26289 var RecordDef = Roo.data.Record.create([
26290     {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
26291     {name: 'occupation'}                 // This field will use "occupation" as the mapping.
26292 ]);
26293 var myReader = new Roo.data.JsonReader({
26294     totalProperty: "results",    // The property which contains the total dataset size (optional)
26295     root: "rows",                // The property which contains an Array of row objects
26296     id: "id"                     // The property within each row object that provides an ID for the record (optional)
26297 }, RecordDef);
26298 </code></pre>
26299  * <p>
26300  * This would consume a JSON file like this:
26301  * <pre><code>
26302 { 'results': 2, 'rows': [
26303     { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
26304     { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
26305 }
26306 </code></pre>
26307  * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
26308  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
26309  * paged from the remote server.
26310  * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
26311  * @cfg {String} root name of the property which contains the Array of row objects.
26312  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
26313  * @cfg {Array} fields Array of field definition objects
26314  * @constructor
26315  * Create a new JsonReader
26316  * @param {Object} meta Metadata configuration options
26317  * @param {Object} recordType Either an Array of field definition objects,
26318  * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
26319  */
26320 Roo.data.JsonReader = function(meta, recordType){
26321     
26322     meta = meta || {};
26323     // set some defaults:
26324     Roo.applyIf(meta, {
26325         totalProperty: 'total',
26326         successProperty : 'success',
26327         root : 'data',
26328         id : 'id'
26329     });
26330     
26331     Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
26332 };
26333 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
26334     
26335     readerType : 'Json',
26336     
26337     /**
26338      * @prop {Boolean} metaFromRemote  - if the meta data was loaded from the remote source.
26339      * Used by Store query builder to append _requestMeta to params.
26340      * 
26341      */
26342     metaFromRemote : false,
26343     /**
26344      * This method is only used by a DataProxy which has retrieved data from a remote server.
26345      * @param {Object} response The XHR object which contains the JSON data in its responseText.
26346      * @return {Object} data A data block which is used by an Roo.data.Store object as
26347      * a cache of Roo.data.Records.
26348      */
26349     read : function(response){
26350         var json = response.responseText;
26351        
26352         var o = /* eval:var:o */ eval("("+json+")");
26353         if(!o) {
26354             throw {message: "JsonReader.read: Json object not found"};
26355         }
26356         
26357         if(o.metaData){
26358             
26359             delete this.ef;
26360             this.metaFromRemote = true;
26361             this.meta = o.metaData;
26362             this.recordType = Roo.data.Record.create(o.metaData.fields);
26363             this.onMetaChange(this.meta, this.recordType, o);
26364         }
26365         return this.readRecords(o);
26366     },
26367
26368     // private function a store will implement
26369     onMetaChange : function(meta, recordType, o){
26370
26371     },
26372
26373     /**
26374          * @ignore
26375          */
26376     simpleAccess: function(obj, subsc) {
26377         return obj[subsc];
26378     },
26379
26380         /**
26381          * @ignore
26382          */
26383     getJsonAccessor: function(){
26384         var re = /[\[\.]/;
26385         return function(expr) {
26386             try {
26387                 return(re.test(expr))
26388                     ? new Function("obj", "return obj." + expr)
26389                     : function(obj){
26390                         return obj[expr];
26391                     };
26392             } catch(e){}
26393             return Roo.emptyFn;
26394         };
26395     }(),
26396
26397     /**
26398      * Create a data block containing Roo.data.Records from an XML document.
26399      * @param {Object} o An object which contains an Array of row objects in the property specified
26400      * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
26401      * which contains the total size of the dataset.
26402      * @return {Object} data A data block which is used by an Roo.data.Store object as
26403      * a cache of Roo.data.Records.
26404      */
26405     readRecords : function(o){
26406         /**
26407          * After any data loads, the raw JSON data is available for further custom processing.
26408          * @type Object
26409          */
26410         this.o = o;
26411         var s = this.meta, Record = this.recordType,
26412             f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
26413
26414 //      Generate extraction functions for the totalProperty, the root, the id, and for each field
26415         if (!this.ef) {
26416             if(s.totalProperty) {
26417                     this.getTotal = this.getJsonAccessor(s.totalProperty);
26418                 }
26419                 if(s.successProperty) {
26420                     this.getSuccess = this.getJsonAccessor(s.successProperty);
26421                 }
26422                 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
26423                 if (s.id) {
26424                         var g = this.getJsonAccessor(s.id);
26425                         this.getId = function(rec) {
26426                                 var r = g(rec);  
26427                                 return (r === undefined || r === "") ? null : r;
26428                         };
26429                 } else {
26430                         this.getId = function(){return null;};
26431                 }
26432             this.ef = [];
26433             for(var jj = 0; jj < fl; jj++){
26434                 f = fi[jj];
26435                 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
26436                 this.ef[jj] = this.getJsonAccessor(map);
26437             }
26438         }
26439
26440         var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
26441         if(s.totalProperty){
26442             var vt = parseInt(this.getTotal(o), 10);
26443             if(!isNaN(vt)){
26444                 totalRecords = vt;
26445             }
26446         }
26447         if(s.successProperty){
26448             var vs = this.getSuccess(o);
26449             if(vs === false || vs === 'false'){
26450                 success = false;
26451             }
26452         }
26453         var records = [];
26454         for(var i = 0; i < c; i++){
26455             var n = root[i];
26456             var values = {};
26457             var id = this.getId(n);
26458             for(var j = 0; j < fl; j++){
26459                 f = fi[j];
26460                                 var v = this.ef[j](n);
26461                                 if (!f.convert) {
26462                                         Roo.log('missing convert for ' + f.name);
26463                                         Roo.log(f);
26464                                         continue;
26465                                 }
26466                                 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
26467             }
26468                         if (!Record) {
26469                                 return {
26470                                         raw : { errorMsg : "JSON Reader Error: fields or metadata not available to create Record" },
26471                                         success : false,
26472                                         records : [],
26473                                         totalRecords : 0
26474                                 };
26475                         }
26476             var record = new Record(values, id);
26477             record.json = n;
26478             records[i] = record;
26479         }
26480         return {
26481             raw : o,
26482             success : success,
26483             records : records,
26484             totalRecords : totalRecords
26485         };
26486     },
26487     // used when loading children.. @see loadDataFromChildren
26488     toLoadData: function(rec)
26489     {
26490         // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
26491         var data = typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
26492         return { data : data, total : data.length };
26493         
26494     }
26495 });/*
26496  * Based on:
26497  * Ext JS Library 1.1.1
26498  * Copyright(c) 2006-2007, Ext JS, LLC.
26499  *
26500  * Originally Released Under LGPL - original licence link has changed is not relivant.
26501  *
26502  * Fork - LGPL
26503  * <script type="text/javascript">
26504  */
26505
26506 /**
26507  * @class Roo.data.XmlReader
26508  * @extends Roo.data.DataReader
26509  * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
26510  * based on mappings in a provided Roo.data.Record constructor.<br><br>
26511  * <p>
26512  * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
26513  * header in the HTTP response must be set to "text/xml".</em>
26514  * <p>
26515  * Example code:
26516  * <pre><code>
26517 var RecordDef = Roo.data.Record.create([
26518    {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
26519    {name: 'occupation'}                 // This field will use "occupation" as the mapping.
26520 ]);
26521 var myReader = new Roo.data.XmlReader({
26522    totalRecords: "results", // The element which contains the total dataset size (optional)
26523    record: "row",           // The repeated element which contains row information
26524    id: "id"                 // The element within the row that provides an ID for the record (optional)
26525 }, RecordDef);
26526 </code></pre>
26527  * <p>
26528  * This would consume an XML file like this:
26529  * <pre><code>
26530 &lt;?xml?>
26531 &lt;dataset>
26532  &lt;results>2&lt;/results>
26533  &lt;row>
26534    &lt;id>1&lt;/id>
26535    &lt;name>Bill&lt;/name>
26536    &lt;occupation>Gardener&lt;/occupation>
26537  &lt;/row>
26538  &lt;row>
26539    &lt;id>2&lt;/id>
26540    &lt;name>Ben&lt;/name>
26541    &lt;occupation>Horticulturalist&lt;/occupation>
26542  &lt;/row>
26543 &lt;/dataset>
26544 </code></pre>
26545  * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
26546  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
26547  * paged from the remote server.
26548  * @cfg {String} record The DomQuery path to the repeated element which contains record information.
26549  * @cfg {String} success The DomQuery path to the success attribute used by forms.
26550  * @cfg {String} id The DomQuery path relative from the record element to the element that contains
26551  * a record identifier value.
26552  * @constructor
26553  * Create a new XmlReader
26554  * @param {Object} meta Metadata configuration options
26555  * @param {Mixed} recordType The definition of the data record type to produce.  This can be either a valid
26556  * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
26557  * Roo.data.Record.create.  See the {@link Roo.data.Record} class for more details.
26558  */
26559 Roo.data.XmlReader = function(meta, recordType){
26560     meta = meta || {};
26561     Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
26562 };
26563 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
26564     
26565     readerType : 'Xml',
26566     
26567     /**
26568      * This method is only used by a DataProxy which has retrieved data from a remote server.
26569          * @param {Object} response The XHR object which contains the parsed XML document.  The response is expected
26570          * to contain a method called 'responseXML' that returns an XML document object.
26571      * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
26572      * a cache of Roo.data.Records.
26573      */
26574     read : function(response){
26575         var doc = response.responseXML;
26576         if(!doc) {
26577             throw {message: "XmlReader.read: XML Document not available"};
26578         }
26579         return this.readRecords(doc);
26580     },
26581
26582     /**
26583      * Create a data block containing Roo.data.Records from an XML document.
26584          * @param {Object} doc A parsed XML document.
26585      * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
26586      * a cache of Roo.data.Records.
26587      */
26588     readRecords : function(doc){
26589         /**
26590          * After any data loads/reads, the raw XML Document is available for further custom processing.
26591          * @type XMLDocument
26592          */
26593         this.xmlData = doc;
26594         var root = doc.documentElement || doc;
26595         var q = Roo.DomQuery;
26596         var recordType = this.recordType, fields = recordType.prototype.fields;
26597         var sid = this.meta.id;
26598         var totalRecords = 0, success = true;
26599         if(this.meta.totalRecords){
26600             totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
26601         }
26602         
26603         if(this.meta.success){
26604             var sv = q.selectValue(this.meta.success, root, true);
26605             success = sv !== false && sv !== 'false';
26606         }
26607         var records = [];
26608         var ns = q.select(this.meta.record, root);
26609         for(var i = 0, len = ns.length; i < len; i++) {
26610                 var n = ns[i];
26611                 var values = {};
26612                 var id = sid ? q.selectValue(sid, n) : undefined;
26613                 for(var j = 0, jlen = fields.length; j < jlen; j++){
26614                     var f = fields.items[j];
26615                 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
26616                     v = f.convert(v);
26617                     values[f.name] = v;
26618                 }
26619                 var record = new recordType(values, id);
26620                 record.node = n;
26621                 records[records.length] = record;
26622             }
26623
26624             return {
26625                 success : success,
26626                 records : records,
26627                 totalRecords : totalRecords || records.length
26628             };
26629     }
26630 });/*
26631  * Based on:
26632  * Ext JS Library 1.1.1
26633  * Copyright(c) 2006-2007, Ext JS, LLC.
26634  *
26635  * Originally Released Under LGPL - original licence link has changed is not relivant.
26636  *
26637  * Fork - LGPL
26638  * <script type="text/javascript">
26639  */
26640
26641 /**
26642  * @class Roo.data.ArrayReader
26643  * @extends Roo.data.DataReader
26644  * Data reader class to create an Array of Roo.data.Record objects from an Array.
26645  * Each element of that Array represents a row of data fields. The
26646  * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
26647  * of the field definition if it exists, or the field's ordinal position in the definition.<br>
26648  * <p>
26649  * Example code:.
26650  * <pre><code>
26651 var RecordDef = Roo.data.Record.create([
26652     {name: 'name', mapping: 1},         // "mapping" only needed if an "id" field is present which
26653     {name: 'occupation', mapping: 2}    // precludes using the ordinal position as the index.
26654 ]);
26655 var myReader = new Roo.data.ArrayReader({
26656     id: 0                     // The subscript within row Array that provides an ID for the Record (optional)
26657 }, RecordDef);
26658 </code></pre>
26659  * <p>
26660  * This would consume an Array like this:
26661  * <pre><code>
26662 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
26663   </code></pre>
26664  
26665  * @constructor
26666  * Create a new JsonReader
26667  * @param {Object} meta Metadata configuration options.
26668  * @param {Object|Array} recordType Either an Array of field definition objects
26669  * 
26670  * @cfg {Array} fields Array of field definition objects
26671  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
26672  * as specified to {@link Roo.data.Record#create},
26673  * or an {@link Roo.data.Record} object
26674  *
26675  * 
26676  * created using {@link Roo.data.Record#create}.
26677  */
26678 Roo.data.ArrayReader = function(meta, recordType)
26679 {    
26680     Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType||meta.fields);
26681 };
26682
26683 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
26684     
26685       /**
26686      * Create a data block containing Roo.data.Records from an XML document.
26687      * @param {Object} o An Array of row objects which represents the dataset.
26688      * @return {Object} A data block which is used by an {@link Roo.data.Store} object as
26689      * a cache of Roo.data.Records.
26690      */
26691     readRecords : function(o)
26692     {
26693         var sid = this.meta ? this.meta.id : null;
26694         var recordType = this.recordType, fields = recordType.prototype.fields;
26695         var records = [];
26696         var root = o;
26697         for(var i = 0; i < root.length; i++){
26698             var n = root[i];
26699             var values = {};
26700             var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
26701             for(var j = 0, jlen = fields.length; j < jlen; j++){
26702                 var f = fields.items[j];
26703                 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
26704                 var v = n[k] !== undefined ? n[k] : f.defaultValue;
26705                 v = f.convert(v);
26706                 values[f.name] = v;
26707             }
26708             var record = new recordType(values, id);
26709             record.json = n;
26710             records[records.length] = record;
26711         }
26712         return {
26713             records : records,
26714             totalRecords : records.length
26715         };
26716     },
26717     // used when loading children.. @see loadDataFromChildren
26718     toLoadData: function(rec)
26719     {
26720         // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
26721         return typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
26722         
26723     }
26724     
26725     
26726 });/*
26727  * Based on:
26728  * Ext JS Library 1.1.1
26729  * Copyright(c) 2006-2007, Ext JS, LLC.
26730  *
26731  * Originally Released Under LGPL - original licence link has changed is not relivant.
26732  *
26733  * Fork - LGPL
26734  * <script type="text/javascript">
26735  */
26736
26737
26738 /**
26739  * @class Roo.data.Tree
26740  * @extends Roo.util.Observable
26741  * Represents a tree data structure and bubbles all the events for its nodes. The nodes
26742  * in the tree have most standard DOM functionality.
26743  * @constructor
26744  * @param {Node} root (optional) The root node
26745  */
26746 Roo.data.Tree = function(root){
26747    this.nodeHash = {};
26748    /**
26749     * The root node for this tree
26750     * @type Node
26751     */
26752    this.root = null;
26753    if(root){
26754        this.setRootNode(root);
26755    }
26756    this.addEvents({
26757        /**
26758         * @event append
26759         * Fires when a new child node is appended to a node in this tree.
26760         * @param {Tree} tree The owner tree
26761         * @param {Node} parent The parent node
26762         * @param {Node} node The newly appended node
26763         * @param {Number} index The index of the newly appended node
26764         */
26765        "append" : true,
26766        /**
26767         * @event remove
26768         * Fires when a child node is removed from a node in this tree.
26769         * @param {Tree} tree The owner tree
26770         * @param {Node} parent The parent node
26771         * @param {Node} node The child node removed
26772         */
26773        "remove" : true,
26774        /**
26775         * @event move
26776         * Fires when a node is moved to a new location in the tree
26777         * @param {Tree} tree The owner tree
26778         * @param {Node} node The node moved
26779         * @param {Node} oldParent The old parent of this node
26780         * @param {Node} newParent The new parent of this node
26781         * @param {Number} index The index it was moved to
26782         */
26783        "move" : true,
26784        /**
26785         * @event insert
26786         * Fires when a new child node is inserted in a node in this tree.
26787         * @param {Tree} tree The owner tree
26788         * @param {Node} parent The parent node
26789         * @param {Node} node The child node inserted
26790         * @param {Node} refNode The child node the node was inserted before
26791         */
26792        "insert" : true,
26793        /**
26794         * @event beforeappend
26795         * Fires before a new child is appended to a node in this tree, return false to cancel the append.
26796         * @param {Tree} tree The owner tree
26797         * @param {Node} parent The parent node
26798         * @param {Node} node The child node to be appended
26799         */
26800        "beforeappend" : true,
26801        /**
26802         * @event beforeremove
26803         * Fires before a child is removed from a node in this tree, return false to cancel the remove.
26804         * @param {Tree} tree The owner tree
26805         * @param {Node} parent The parent node
26806         * @param {Node} node The child node to be removed
26807         */
26808        "beforeremove" : true,
26809        /**
26810         * @event beforemove
26811         * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
26812         * @param {Tree} tree The owner tree
26813         * @param {Node} node The node being moved
26814         * @param {Node} oldParent The parent of the node
26815         * @param {Node} newParent The new parent the node is moving to
26816         * @param {Number} index The index it is being moved to
26817         */
26818        "beforemove" : true,
26819        /**
26820         * @event beforeinsert
26821         * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
26822         * @param {Tree} tree The owner tree
26823         * @param {Node} parent The parent node
26824         * @param {Node} node The child node to be inserted
26825         * @param {Node} refNode The child node the node is being inserted before
26826         */
26827        "beforeinsert" : true
26828    });
26829
26830     Roo.data.Tree.superclass.constructor.call(this);
26831 };
26832
26833 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
26834     pathSeparator: "/",
26835
26836     proxyNodeEvent : function(){
26837         return this.fireEvent.apply(this, arguments);
26838     },
26839
26840     /**
26841      * Returns the root node for this tree.
26842      * @return {Node}
26843      */
26844     getRootNode : function(){
26845         return this.root;
26846     },
26847
26848     /**
26849      * Sets the root node for this tree.
26850      * @param {Node} node
26851      * @return {Node}
26852      */
26853     setRootNode : function(node){
26854         this.root = node;
26855         node.ownerTree = this;
26856         node.isRoot = true;
26857         this.registerNode(node);
26858         return node;
26859     },
26860
26861     /**
26862      * Gets a node in this tree by its id.
26863      * @param {String} id
26864      * @return {Node}
26865      */
26866     getNodeById : function(id){
26867         return this.nodeHash[id];
26868     },
26869
26870     registerNode : function(node){
26871         this.nodeHash[node.id] = node;
26872     },
26873
26874     unregisterNode : function(node){
26875         delete this.nodeHash[node.id];
26876     },
26877
26878     toString : function(){
26879         return "[Tree"+(this.id?" "+this.id:"")+"]";
26880     }
26881 });
26882
26883 /**
26884  * @class Roo.data.Node
26885  * @extends Roo.util.Observable
26886  * @cfg {Boolean} leaf true if this node is a leaf and does not have children
26887  * @cfg {String} id The id for this node. If one is not specified, one is generated.
26888  * @constructor
26889  * @param {Object} attributes The attributes/config for the node
26890  */
26891 Roo.data.Node = function(attributes){
26892     /**
26893      * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
26894      * @type {Object}
26895      */
26896     this.attributes = attributes || {};
26897     this.leaf = this.attributes.leaf;
26898     /**
26899      * The node id. @type String
26900      */
26901     this.id = this.attributes.id;
26902     if(!this.id){
26903         this.id = Roo.id(null, "ynode-");
26904         this.attributes.id = this.id;
26905     }
26906      
26907     
26908     /**
26909      * All child nodes of this node. @type Array
26910      */
26911     this.childNodes = [];
26912     if(!this.childNodes.indexOf){ // indexOf is a must
26913         this.childNodes.indexOf = function(o){
26914             for(var i = 0, len = this.length; i < len; i++){
26915                 if(this[i] == o) {
26916                     return i;
26917                 }
26918             }
26919             return -1;
26920         };
26921     }
26922     /**
26923      * The parent node for this node. @type Node
26924      */
26925     this.parentNode = null;
26926     /**
26927      * The first direct child node of this node, or null if this node has no child nodes. @type Node
26928      */
26929     this.firstChild = null;
26930     /**
26931      * The last direct child node of this node, or null if this node has no child nodes. @type Node
26932      */
26933     this.lastChild = null;
26934     /**
26935      * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
26936      */
26937     this.previousSibling = null;
26938     /**
26939      * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
26940      */
26941     this.nextSibling = null;
26942
26943     this.addEvents({
26944        /**
26945         * @event append
26946         * Fires when a new child node is appended
26947         * @param {Tree} tree The owner tree
26948         * @param {Node} this This node
26949         * @param {Node} node The newly appended node
26950         * @param {Number} index The index of the newly appended node
26951         */
26952        "append" : true,
26953        /**
26954         * @event remove
26955         * Fires when a child node is removed
26956         * @param {Tree} tree The owner tree
26957         * @param {Node} this This node
26958         * @param {Node} node The removed node
26959         */
26960        "remove" : true,
26961        /**
26962         * @event move
26963         * Fires when this node is moved to a new location in the tree
26964         * @param {Tree} tree The owner tree
26965         * @param {Node} this This node
26966         * @param {Node} oldParent The old parent of this node
26967         * @param {Node} newParent The new parent of this node
26968         * @param {Number} index The index it was moved to
26969         */
26970        "move" : true,
26971        /**
26972         * @event insert
26973         * Fires when a new child node is inserted.
26974         * @param {Tree} tree The owner tree
26975         * @param {Node} this This node
26976         * @param {Node} node The child node inserted
26977         * @param {Node} refNode The child node the node was inserted before
26978         */
26979        "insert" : true,
26980        /**
26981         * @event beforeappend
26982         * Fires before a new child is appended, return false to cancel the append.
26983         * @param {Tree} tree The owner tree
26984         * @param {Node} this This node
26985         * @param {Node} node The child node to be appended
26986         */
26987        "beforeappend" : true,
26988        /**
26989         * @event beforeremove
26990         * Fires before a child is removed, return false to cancel the remove.
26991         * @param {Tree} tree The owner tree
26992         * @param {Node} this This node
26993         * @param {Node} node The child node to be removed
26994         */
26995        "beforeremove" : true,
26996        /**
26997         * @event beforemove
26998         * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
26999         * @param {Tree} tree The owner tree
27000         * @param {Node} this This node
27001         * @param {Node} oldParent The parent of this node
27002         * @param {Node} newParent The new parent this node is moving to
27003         * @param {Number} index The index it is being moved to
27004         */
27005        "beforemove" : true,
27006        /**
27007         * @event beforeinsert
27008         * Fires before a new child is inserted, return false to cancel the insert.
27009         * @param {Tree} tree The owner tree
27010         * @param {Node} this This node
27011         * @param {Node} node The child node to be inserted
27012         * @param {Node} refNode The child node the node is being inserted before
27013         */
27014        "beforeinsert" : true
27015    });
27016     this.listeners = this.attributes.listeners;
27017     Roo.data.Node.superclass.constructor.call(this);
27018 };
27019
27020 Roo.extend(Roo.data.Node, Roo.util.Observable, {
27021     fireEvent : function(evtName){
27022         // first do standard event for this node
27023         if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
27024             return false;
27025         }
27026         // then bubble it up to the tree if the event wasn't cancelled
27027         var ot = this.getOwnerTree();
27028         if(ot){
27029             if(ot.proxyNodeEvent.apply(ot, arguments) === false){
27030                 return false;
27031             }
27032         }
27033         return true;
27034     },
27035
27036     /**
27037      * Returns true if this node is a leaf
27038      * @return {Boolean}
27039      */
27040     isLeaf : function(){
27041         return this.leaf === true;
27042     },
27043
27044     // private
27045     setFirstChild : function(node){
27046         this.firstChild = node;
27047     },
27048
27049     //private
27050     setLastChild : function(node){
27051         this.lastChild = node;
27052     },
27053
27054
27055     /**
27056      * Returns true if this node is the last child of its parent
27057      * @return {Boolean}
27058      */
27059     isLast : function(){
27060        return (!this.parentNode ? true : this.parentNode.lastChild == this);
27061     },
27062
27063     /**
27064      * Returns true if this node is the first child of its parent
27065      * @return {Boolean}
27066      */
27067     isFirst : function(){
27068        return (!this.parentNode ? true : this.parentNode.firstChild == this);
27069     },
27070
27071     hasChildNodes : function(){
27072         return !this.isLeaf() && this.childNodes.length > 0;
27073     },
27074
27075     /**
27076      * Insert node(s) as the last child node of this node.
27077      * @param {Node/Array} node The node or Array of nodes to append
27078      * @return {Node} The appended node if single append, or null if an array was passed
27079      */
27080     appendChild : function(node){
27081         var multi = false;
27082         if(node instanceof Array){
27083             multi = node;
27084         }else if(arguments.length > 1){
27085             multi = arguments;
27086         }
27087         
27088         // if passed an array or multiple args do them one by one
27089         if(multi){
27090             for(var i = 0, len = multi.length; i < len; i++) {
27091                 this.appendChild(multi[i]);
27092             }
27093         }else{
27094             if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
27095                 return false;
27096             }
27097             var index = this.childNodes.length;
27098             var oldParent = node.parentNode;
27099             // it's a move, make sure we move it cleanly
27100             if(oldParent){
27101                 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
27102                     return false;
27103                 }
27104                 oldParent.removeChild(node);
27105             }
27106             
27107             index = this.childNodes.length;
27108             if(index == 0){
27109                 this.setFirstChild(node);
27110             }
27111             this.childNodes.push(node);
27112             node.parentNode = this;
27113             var ps = this.childNodes[index-1];
27114             if(ps){
27115                 node.previousSibling = ps;
27116                 ps.nextSibling = node;
27117             }else{
27118                 node.previousSibling = null;
27119             }
27120             node.nextSibling = null;
27121             this.setLastChild(node);
27122             node.setOwnerTree(this.getOwnerTree());
27123             this.fireEvent("append", this.ownerTree, this, node, index);
27124             if(this.ownerTree) {
27125                 this.ownerTree.fireEvent("appendnode", this, node, index);
27126             }
27127             if(oldParent){
27128                 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
27129             }
27130             return node;
27131         }
27132     },
27133
27134     /**
27135      * Removes a child node from this node.
27136      * @param {Node} node The node to remove
27137      * @return {Node} The removed node
27138      */
27139     removeChild : function(node){
27140         var index = this.childNodes.indexOf(node);
27141         if(index == -1){
27142             return false;
27143         }
27144         if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
27145             return false;
27146         }
27147
27148         // remove it from childNodes collection
27149         this.childNodes.splice(index, 1);
27150
27151         // update siblings
27152         if(node.previousSibling){
27153             node.previousSibling.nextSibling = node.nextSibling;
27154         }
27155         if(node.nextSibling){
27156             node.nextSibling.previousSibling = node.previousSibling;
27157         }
27158
27159         // update child refs
27160         if(this.firstChild == node){
27161             this.setFirstChild(node.nextSibling);
27162         }
27163         if(this.lastChild == node){
27164             this.setLastChild(node.previousSibling);
27165         }
27166
27167         node.setOwnerTree(null);
27168         // clear any references from the node
27169         node.parentNode = null;
27170         node.previousSibling = null;
27171         node.nextSibling = null;
27172         this.fireEvent("remove", this.ownerTree, this, node);
27173         return node;
27174     },
27175
27176     /**
27177      * Inserts the first node before the second node in this nodes childNodes collection.
27178      * @param {Node} node The node to insert
27179      * @param {Node} refNode The node to insert before (if null the node is appended)
27180      * @return {Node} The inserted node
27181      */
27182     insertBefore : function(node, refNode){
27183         if(!refNode){ // like standard Dom, refNode can be null for append
27184             return this.appendChild(node);
27185         }
27186         // nothing to do
27187         if(node == refNode){
27188             return false;
27189         }
27190
27191         if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
27192             return false;
27193         }
27194         var index = this.childNodes.indexOf(refNode);
27195         var oldParent = node.parentNode;
27196         var refIndex = index;
27197
27198         // when moving internally, indexes will change after remove
27199         if(oldParent == this && this.childNodes.indexOf(node) < index){
27200             refIndex--;
27201         }
27202
27203         // it's a move, make sure we move it cleanly
27204         if(oldParent){
27205             if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
27206                 return false;
27207             }
27208             oldParent.removeChild(node);
27209         }
27210         if(refIndex == 0){
27211             this.setFirstChild(node);
27212         }
27213         this.childNodes.splice(refIndex, 0, node);
27214         node.parentNode = this;
27215         var ps = this.childNodes[refIndex-1];
27216         if(ps){
27217             node.previousSibling = ps;
27218             ps.nextSibling = node;
27219         }else{
27220             node.previousSibling = null;
27221         }
27222         node.nextSibling = refNode;
27223         refNode.previousSibling = node;
27224         node.setOwnerTree(this.getOwnerTree());
27225         this.fireEvent("insert", this.ownerTree, this, node, refNode);
27226         if(oldParent){
27227             node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
27228         }
27229         return node;
27230     },
27231
27232     /**
27233      * Returns the child node at the specified index.
27234      * @param {Number} index
27235      * @return {Node}
27236      */
27237     item : function(index){
27238         return this.childNodes[index];
27239     },
27240
27241     /**
27242      * Replaces one child node in this node with another.
27243      * @param {Node} newChild The replacement node
27244      * @param {Node} oldChild The node to replace
27245      * @return {Node} The replaced node
27246      */
27247     replaceChild : function(newChild, oldChild){
27248         this.insertBefore(newChild, oldChild);
27249         this.removeChild(oldChild);
27250         return oldChild;
27251     },
27252
27253     /**
27254      * Returns the index of a child node
27255      * @param {Node} node
27256      * @return {Number} The index of the node or -1 if it was not found
27257      */
27258     indexOf : function(child){
27259         return this.childNodes.indexOf(child);
27260     },
27261
27262     /**
27263      * Returns the tree this node is in.
27264      * @return {Tree}
27265      */
27266     getOwnerTree : function(){
27267         // if it doesn't have one, look for one
27268         if(!this.ownerTree){
27269             var p = this;
27270             while(p){
27271                 if(p.ownerTree){
27272                     this.ownerTree = p.ownerTree;
27273                     break;
27274                 }
27275                 p = p.parentNode;
27276             }
27277         }
27278         return this.ownerTree;
27279     },
27280
27281     /**
27282      * Returns depth of this node (the root node has a depth of 0)
27283      * @return {Number}
27284      */
27285     getDepth : function(){
27286         var depth = 0;
27287         var p = this;
27288         while(p.parentNode){
27289             ++depth;
27290             p = p.parentNode;
27291         }
27292         return depth;
27293     },
27294
27295     // private
27296     setOwnerTree : function(tree){
27297         // if it's move, we need to update everyone
27298         if(tree != this.ownerTree){
27299             if(this.ownerTree){
27300                 this.ownerTree.unregisterNode(this);
27301             }
27302             this.ownerTree = tree;
27303             var cs = this.childNodes;
27304             for(var i = 0, len = cs.length; i < len; i++) {
27305                 cs[i].setOwnerTree(tree);
27306             }
27307             if(tree){
27308                 tree.registerNode(this);
27309             }
27310         }
27311     },
27312
27313     /**
27314      * Returns the path for this node. The path can be used to expand or select this node programmatically.
27315      * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
27316      * @return {String} The path
27317      */
27318     getPath : function(attr){
27319         attr = attr || "id";
27320         var p = this.parentNode;
27321         var b = [this.attributes[attr]];
27322         while(p){
27323             b.unshift(p.attributes[attr]);
27324             p = p.parentNode;
27325         }
27326         var sep = this.getOwnerTree().pathSeparator;
27327         return sep + b.join(sep);
27328     },
27329
27330     /**
27331      * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
27332      * function call will be the scope provided or the current node. The arguments to the function
27333      * will be the args provided or the current node. If the function returns false at any point,
27334      * the bubble is stopped.
27335      * @param {Function} fn The function to call
27336      * @param {Object} scope (optional) The scope of the function (defaults to current node)
27337      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
27338      */
27339     bubble : function(fn, scope, args){
27340         var p = this;
27341         while(p){
27342             if(fn.call(scope || p, args || p) === false){
27343                 break;
27344             }
27345             p = p.parentNode;
27346         }
27347     },
27348
27349     /**
27350      * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
27351      * function call will be the scope provided or the current node. The arguments to the function
27352      * will be the args provided or the current node. If the function returns false at any point,
27353      * the cascade is stopped on that branch.
27354      * @param {Function} fn The function to call
27355      * @param {Object} scope (optional) The scope of the function (defaults to current node)
27356      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
27357      */
27358     cascade : function(fn, scope, args){
27359         if(fn.call(scope || this, args || this) !== false){
27360             var cs = this.childNodes;
27361             for(var i = 0, len = cs.length; i < len; i++) {
27362                 cs[i].cascade(fn, scope, args);
27363             }
27364         }
27365     },
27366
27367     /**
27368      * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
27369      * function call will be the scope provided or the current node. The arguments to the function
27370      * will be the args provided or the current node. If the function returns false at any point,
27371      * the iteration stops.
27372      * @param {Function} fn The function to call
27373      * @param {Object} scope (optional) The scope of the function (defaults to current node)
27374      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
27375      */
27376     eachChild : function(fn, scope, args){
27377         var cs = this.childNodes;
27378         for(var i = 0, len = cs.length; i < len; i++) {
27379                 if(fn.call(scope || this, args || cs[i]) === false){
27380                     break;
27381                 }
27382         }
27383     },
27384
27385     /**
27386      * Finds the first child that has the attribute with the specified value.
27387      * @param {String} attribute The attribute name
27388      * @param {Mixed} value The value to search for
27389      * @return {Node} The found child or null if none was found
27390      */
27391     findChild : function(attribute, value){
27392         var cs = this.childNodes;
27393         for(var i = 0, len = cs.length; i < len; i++) {
27394                 if(cs[i].attributes[attribute] == value){
27395                     return cs[i];
27396                 }
27397         }
27398         return null;
27399     },
27400
27401     /**
27402      * Finds the first child by a custom function. The child matches if the function passed
27403      * returns true.
27404      * @param {Function} fn
27405      * @param {Object} scope (optional)
27406      * @return {Node} The found child or null if none was found
27407      */
27408     findChildBy : function(fn, scope){
27409         var cs = this.childNodes;
27410         for(var i = 0, len = cs.length; i < len; i++) {
27411                 if(fn.call(scope||cs[i], cs[i]) === true){
27412                     return cs[i];
27413                 }
27414         }
27415         return null;
27416     },
27417
27418     /**
27419      * Sorts this nodes children using the supplied sort function
27420      * @param {Function} fn
27421      * @param {Object} scope (optional)
27422      */
27423     sort : function(fn, scope){
27424         var cs = this.childNodes;
27425         var len = cs.length;
27426         if(len > 0){
27427             var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
27428             cs.sort(sortFn);
27429             for(var i = 0; i < len; i++){
27430                 var n = cs[i];
27431                 n.previousSibling = cs[i-1];
27432                 n.nextSibling = cs[i+1];
27433                 if(i == 0){
27434                     this.setFirstChild(n);
27435                 }
27436                 if(i == len-1){
27437                     this.setLastChild(n);
27438                 }
27439             }
27440         }
27441     },
27442
27443     /**
27444      * Returns true if this node is an ancestor (at any point) of the passed node.
27445      * @param {Node} node
27446      * @return {Boolean}
27447      */
27448     contains : function(node){
27449         return node.isAncestor(this);
27450     },
27451
27452     /**
27453      * Returns true if the passed node is an ancestor (at any point) of this node.
27454      * @param {Node} node
27455      * @return {Boolean}
27456      */
27457     isAncestor : function(node){
27458         var p = this.parentNode;
27459         while(p){
27460             if(p == node){
27461                 return true;
27462             }
27463             p = p.parentNode;
27464         }
27465         return false;
27466     },
27467
27468     toString : function(){
27469         return "[Node"+(this.id?" "+this.id:"")+"]";
27470     }
27471 });/*
27472  * Based on:
27473  * Ext JS Library 1.1.1
27474  * Copyright(c) 2006-2007, Ext JS, LLC.
27475  *
27476  * Originally Released Under LGPL - original licence link has changed is not relivant.
27477  *
27478  * Fork - LGPL
27479  * <script type="text/javascript">
27480  */
27481
27482
27483 /**
27484  * @class Roo.Shadow
27485  * Simple class that can provide a shadow effect for any element.  Note that the element MUST be absolutely positioned,
27486  * and the shadow does not provide any shimming.  This should be used only in simple cases -- for more advanced
27487  * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
27488  * @constructor
27489  * Create a new Shadow
27490  * @param {Object} config The config object
27491  */
27492 Roo.Shadow = function(config){
27493     Roo.apply(this, config);
27494     if(typeof this.mode != "string"){
27495         this.mode = this.defaultMode;
27496     }
27497     var o = this.offset, a = {h: 0};
27498     var rad = Math.floor(this.offset/2);
27499     switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
27500         case "drop":
27501             a.w = 0;
27502             a.l = a.t = o;
27503             a.t -= 1;
27504             if(Roo.isIE){
27505                 a.l -= this.offset + rad;
27506                 a.t -= this.offset + rad;
27507                 a.w -= rad;
27508                 a.h -= rad;
27509                 a.t += 1;
27510             }
27511         break;
27512         case "sides":
27513             a.w = (o*2);
27514             a.l = -o;
27515             a.t = o-1;
27516             if(Roo.isIE){
27517                 a.l -= (this.offset - rad);
27518                 a.t -= this.offset + rad;
27519                 a.l += 1;
27520                 a.w -= (this.offset - rad)*2;
27521                 a.w -= rad + 1;
27522                 a.h -= 1;
27523             }
27524         break;
27525         case "frame":
27526             a.w = a.h = (o*2);
27527             a.l = a.t = -o;
27528             a.t += 1;
27529             a.h -= 2;
27530             if(Roo.isIE){
27531                 a.l -= (this.offset - rad);
27532                 a.t -= (this.offset - rad);
27533                 a.l += 1;
27534                 a.w -= (this.offset + rad + 1);
27535                 a.h -= (this.offset + rad);
27536                 a.h += 1;
27537             }
27538         break;
27539     };
27540
27541     this.adjusts = a;
27542 };
27543
27544 Roo.Shadow.prototype = {
27545     /**
27546      * @cfg {String} mode
27547      * The shadow display mode.  Supports the following options:<br />
27548      * sides: Shadow displays on both sides and bottom only<br />
27549      * frame: Shadow displays equally on all four sides<br />
27550      * drop: Traditional bottom-right drop shadow (default)
27551      */
27552     mode: false,
27553     /**
27554      * @cfg {String} offset
27555      * The number of pixels to offset the shadow from the element (defaults to 4)
27556      */
27557     offset: 4,
27558
27559     // private
27560     defaultMode: "drop",
27561
27562     /**
27563      * Displays the shadow under the target element
27564      * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
27565      */
27566     show : function(target){
27567         target = Roo.get(target);
27568         if(!this.el){
27569             this.el = Roo.Shadow.Pool.pull();
27570             if(this.el.dom.nextSibling != target.dom){
27571                 this.el.insertBefore(target);
27572             }
27573         }
27574         this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
27575         if(Roo.isIE){
27576             this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
27577         }
27578         this.realign(
27579             target.getLeft(true),
27580             target.getTop(true),
27581             target.getWidth(),
27582             target.getHeight()
27583         );
27584         this.el.dom.style.display = "block";
27585     },
27586
27587     /**
27588      * Returns true if the shadow is visible, else false
27589      */
27590     isVisible : function(){
27591         return this.el ? true : false;  
27592     },
27593
27594     /**
27595      * Direct alignment when values are already available. Show must be called at least once before
27596      * calling this method to ensure it is initialized.
27597      * @param {Number} left The target element left position
27598      * @param {Number} top The target element top position
27599      * @param {Number} width The target element width
27600      * @param {Number} height The target element height
27601      */
27602     realign : function(l, t, w, h){
27603         if(!this.el){
27604             return;
27605         }
27606         var a = this.adjusts, d = this.el.dom, s = d.style;
27607         var iea = 0;
27608         s.left = (l+a.l)+"px";
27609         s.top = (t+a.t)+"px";
27610         var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
27611  
27612         if(s.width != sws || s.height != shs){
27613             s.width = sws;
27614             s.height = shs;
27615             if(!Roo.isIE){
27616                 var cn = d.childNodes;
27617                 var sww = Math.max(0, (sw-12))+"px";
27618                 cn[0].childNodes[1].style.width = sww;
27619                 cn[1].childNodes[1].style.width = sww;
27620                 cn[2].childNodes[1].style.width = sww;
27621                 cn[1].style.height = Math.max(0, (sh-12))+"px";
27622             }
27623         }
27624     },
27625
27626     /**
27627      * Hides this shadow
27628      */
27629     hide : function(){
27630         if(this.el){
27631             this.el.dom.style.display = "none";
27632             Roo.Shadow.Pool.push(this.el);
27633             delete this.el;
27634         }
27635     },
27636
27637     /**
27638      * Adjust the z-index of this shadow
27639      * @param {Number} zindex The new z-index
27640      */
27641     setZIndex : function(z){
27642         this.zIndex = z;
27643         if(this.el){
27644             this.el.setStyle("z-index", z);
27645         }
27646     }
27647 };
27648
27649 // Private utility class that manages the internal Shadow cache
27650 Roo.Shadow.Pool = function(){
27651     var p = [];
27652     var markup = Roo.isIE ?
27653                  '<div class="x-ie-shadow"></div>' :
27654                  '<div class="x-shadow"><div class="xst"><div class="xstl"></div><div class="xstc"></div><div class="xstr"></div></div><div class="xsc"><div class="xsml"></div><div class="xsmc"></div><div class="xsmr"></div></div><div class="xsb"><div class="xsbl"></div><div class="xsbc"></div><div class="xsbr"></div></div></div>';
27655     return {
27656         pull : function(){
27657             var sh = p.shift();
27658             if(!sh){
27659                 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
27660                 sh.autoBoxAdjust = false;
27661             }
27662             return sh;
27663         },
27664
27665         push : function(sh){
27666             p.push(sh);
27667         }
27668     };
27669 }();/*
27670  * Based on:
27671  * Ext JS Library 1.1.1
27672  * Copyright(c) 2006-2007, Ext JS, LLC.
27673  *
27674  * Originally Released Under LGPL - original licence link has changed is not relivant.
27675  *
27676  * Fork - LGPL
27677  * <script type="text/javascript">
27678  */
27679
27680
27681 /**
27682  * @class Roo.SplitBar
27683  * @extends Roo.util.Observable
27684  * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
27685  * <br><br>
27686  * Usage:
27687  * <pre><code>
27688 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
27689                    Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
27690 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
27691 split.minSize = 100;
27692 split.maxSize = 600;
27693 split.animate = true;
27694 split.on('moved', splitterMoved);
27695 </code></pre>
27696  * @constructor
27697  * Create a new SplitBar
27698  * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar. 
27699  * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged 
27700  * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
27701  * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or  
27702                         Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
27703                         position of the SplitBar).
27704  */
27705 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
27706     
27707     /** @private */
27708     this.el = Roo.get(dragElement, true);
27709     this.el.dom.unselectable = "on";
27710     /** @private */
27711     this.resizingEl = Roo.get(resizingElement, true);
27712
27713     /**
27714      * @private
27715      * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
27716      * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
27717      * @type Number
27718      */
27719     this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
27720     
27721     /**
27722      * The minimum size of the resizing element. (Defaults to 0)
27723      * @type Number
27724      */
27725     this.minSize = 0;
27726     
27727     /**
27728      * The maximum size of the resizing element. (Defaults to 2000)
27729      * @type Number
27730      */
27731     this.maxSize = 2000;
27732     
27733     /**
27734      * Whether to animate the transition to the new size
27735      * @type Boolean
27736      */
27737     this.animate = false;
27738     
27739     /**
27740      * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
27741      * @type Boolean
27742      */
27743     this.useShim = false;
27744     
27745     /** @private */
27746     this.shim = null;
27747     
27748     if(!existingProxy){
27749         /** @private */
27750         this.proxy = Roo.SplitBar.createProxy(this.orientation);
27751     }else{
27752         this.proxy = Roo.get(existingProxy).dom;
27753     }
27754     /** @private */
27755     this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
27756     
27757     /** @private */
27758     this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
27759     
27760     /** @private */
27761     this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
27762     
27763     /** @private */
27764     this.dragSpecs = {};
27765     
27766     /**
27767      * @private The adapter to use to positon and resize elements
27768      */
27769     this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
27770     this.adapter.init(this);
27771     
27772     if(this.orientation == Roo.SplitBar.HORIZONTAL){
27773         /** @private */
27774         this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
27775         this.el.addClass("x-splitbar-h");
27776     }else{
27777         /** @private */
27778         this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
27779         this.el.addClass("x-splitbar-v");
27780     }
27781     
27782     this.addEvents({
27783         /**
27784          * @event resize
27785          * Fires when the splitter is moved (alias for {@link #event-moved})
27786          * @param {Roo.SplitBar} this
27787          * @param {Number} newSize the new width or height
27788          */
27789         "resize" : true,
27790         /**
27791          * @event moved
27792          * Fires when the splitter is moved
27793          * @param {Roo.SplitBar} this
27794          * @param {Number} newSize the new width or height
27795          */
27796         "moved" : true,
27797         /**
27798          * @event beforeresize
27799          * Fires before the splitter is dragged
27800          * @param {Roo.SplitBar} this
27801          */
27802         "beforeresize" : true,
27803
27804         "beforeapply" : true
27805     });
27806
27807     Roo.util.Observable.call(this);
27808 };
27809
27810 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
27811     onStartProxyDrag : function(x, y){
27812         this.fireEvent("beforeresize", this);
27813         if(!this.overlay){
27814             var o = Roo.DomHelper.insertFirst(document.body,  {cls: "x-drag-overlay", html: "&#160;"}, true);
27815             o.unselectable();
27816             o.enableDisplayMode("block");
27817             // all splitbars share the same overlay
27818             Roo.SplitBar.prototype.overlay = o;
27819         }
27820         this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
27821         this.overlay.show();
27822         Roo.get(this.proxy).setDisplayed("block");
27823         var size = this.adapter.getElementSize(this);
27824         this.activeMinSize = this.getMinimumSize();;
27825         this.activeMaxSize = this.getMaximumSize();;
27826         var c1 = size - this.activeMinSize;
27827         var c2 = Math.max(this.activeMaxSize - size, 0);
27828         if(this.orientation == Roo.SplitBar.HORIZONTAL){
27829             this.dd.resetConstraints();
27830             this.dd.setXConstraint(
27831                 this.placement == Roo.SplitBar.LEFT ? c1 : c2, 
27832                 this.placement == Roo.SplitBar.LEFT ? c2 : c1
27833             );
27834             this.dd.setYConstraint(0, 0);
27835         }else{
27836             this.dd.resetConstraints();
27837             this.dd.setXConstraint(0, 0);
27838             this.dd.setYConstraint(
27839                 this.placement == Roo.SplitBar.TOP ? c1 : c2, 
27840                 this.placement == Roo.SplitBar.TOP ? c2 : c1
27841             );
27842          }
27843         this.dragSpecs.startSize = size;
27844         this.dragSpecs.startPoint = [x, y];
27845         Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
27846     },
27847     
27848     /** 
27849      * @private Called after the drag operation by the DDProxy
27850      */
27851     onEndProxyDrag : function(e){
27852         Roo.get(this.proxy).setDisplayed(false);
27853         var endPoint = Roo.lib.Event.getXY(e);
27854         if(this.overlay){
27855             this.overlay.hide();
27856         }
27857         var newSize;
27858         if(this.orientation == Roo.SplitBar.HORIZONTAL){
27859             newSize = this.dragSpecs.startSize + 
27860                 (this.placement == Roo.SplitBar.LEFT ?
27861                     endPoint[0] - this.dragSpecs.startPoint[0] :
27862                     this.dragSpecs.startPoint[0] - endPoint[0]
27863                 );
27864         }else{
27865             newSize = this.dragSpecs.startSize + 
27866                 (this.placement == Roo.SplitBar.TOP ?
27867                     endPoint[1] - this.dragSpecs.startPoint[1] :
27868                     this.dragSpecs.startPoint[1] - endPoint[1]
27869                 );
27870         }
27871         newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
27872         if(newSize != this.dragSpecs.startSize){
27873             if(this.fireEvent('beforeapply', this, newSize) !== false){
27874                 this.adapter.setElementSize(this, newSize);
27875                 this.fireEvent("moved", this, newSize);
27876                 this.fireEvent("resize", this, newSize);
27877             }
27878         }
27879     },
27880     
27881     /**
27882      * Get the adapter this SplitBar uses
27883      * @return The adapter object
27884      */
27885     getAdapter : function(){
27886         return this.adapter;
27887     },
27888     
27889     /**
27890      * Set the adapter this SplitBar uses
27891      * @param {Object} adapter A SplitBar adapter object
27892      */
27893     setAdapter : function(adapter){
27894         this.adapter = adapter;
27895         this.adapter.init(this);
27896     },
27897     
27898     /**
27899      * Gets the minimum size for the resizing element
27900      * @return {Number} The minimum size
27901      */
27902     getMinimumSize : function(){
27903         return this.minSize;
27904     },
27905     
27906     /**
27907      * Sets the minimum size for the resizing element
27908      * @param {Number} minSize The minimum size
27909      */
27910     setMinimumSize : function(minSize){
27911         this.minSize = minSize;
27912     },
27913     
27914     /**
27915      * Gets the maximum size for the resizing element
27916      * @return {Number} The maximum size
27917      */
27918     getMaximumSize : function(){
27919         return this.maxSize;
27920     },
27921     
27922     /**
27923      * Sets the maximum size for the resizing element
27924      * @param {Number} maxSize The maximum size
27925      */
27926     setMaximumSize : function(maxSize){
27927         this.maxSize = maxSize;
27928     },
27929     
27930     /**
27931      * Sets the initialize size for the resizing element
27932      * @param {Number} size The initial size
27933      */
27934     setCurrentSize : function(size){
27935         var oldAnimate = this.animate;
27936         this.animate = false;
27937         this.adapter.setElementSize(this, size);
27938         this.animate = oldAnimate;
27939     },
27940     
27941     /**
27942      * Destroy this splitbar. 
27943      * @param {Boolean} removeEl True to remove the element
27944      */
27945     destroy : function(removeEl){
27946         if(this.shim){
27947             this.shim.remove();
27948         }
27949         this.dd.unreg();
27950         this.proxy.parentNode.removeChild(this.proxy);
27951         if(removeEl){
27952             this.el.remove();
27953         }
27954     }
27955 });
27956
27957 /**
27958  * @private static Create our own proxy element element. So it will be the same same size on all browsers, we won't use borders. Instead we use a background color.
27959  */
27960 Roo.SplitBar.createProxy = function(dir){
27961     var proxy = new Roo.Element(document.createElement("div"));
27962     proxy.unselectable();
27963     var cls = 'x-splitbar-proxy';
27964     proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
27965     document.body.appendChild(proxy.dom);
27966     return proxy.dom;
27967 };
27968
27969 /** 
27970  * @class Roo.SplitBar.BasicLayoutAdapter
27971  * Default Adapter. It assumes the splitter and resizing element are not positioned
27972  * elements and only gets/sets the width of the element. Generally used for table based layouts.
27973  */
27974 Roo.SplitBar.BasicLayoutAdapter = function(){
27975 };
27976
27977 Roo.SplitBar.BasicLayoutAdapter.prototype = {
27978     // do nothing for now
27979     init : function(s){
27980     
27981     },
27982     /**
27983      * Called before drag operations to get the current size of the resizing element. 
27984      * @param {Roo.SplitBar} s The SplitBar using this adapter
27985      */
27986      getElementSize : function(s){
27987         if(s.orientation == Roo.SplitBar.HORIZONTAL){
27988             return s.resizingEl.getWidth();
27989         }else{
27990             return s.resizingEl.getHeight();
27991         }
27992     },
27993     
27994     /**
27995      * Called after drag operations to set the size of the resizing element.
27996      * @param {Roo.SplitBar} s The SplitBar using this adapter
27997      * @param {Number} newSize The new size to set
27998      * @param {Function} onComplete A function to be invoked when resizing is complete
27999      */
28000     setElementSize : function(s, newSize, onComplete){
28001         if(s.orientation == Roo.SplitBar.HORIZONTAL){
28002             if(!s.animate){
28003                 s.resizingEl.setWidth(newSize);
28004                 if(onComplete){
28005                     onComplete(s, newSize);
28006                 }
28007             }else{
28008                 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
28009             }
28010         }else{
28011             
28012             if(!s.animate){
28013                 s.resizingEl.setHeight(newSize);
28014                 if(onComplete){
28015                     onComplete(s, newSize);
28016                 }
28017             }else{
28018                 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
28019             }
28020         }
28021     }
28022 };
28023
28024 /** 
28025  *@class Roo.SplitBar.AbsoluteLayoutAdapter
28026  * @extends Roo.SplitBar.BasicLayoutAdapter
28027  * Adapter that  moves the splitter element to align with the resized sizing element. 
28028  * Used with an absolute positioned SplitBar.
28029  * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
28030  * document.body, make sure you assign an id to the body element.
28031  */
28032 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
28033     this.basic = new Roo.SplitBar.BasicLayoutAdapter();
28034     this.container = Roo.get(container);
28035 };
28036
28037 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
28038     init : function(s){
28039         this.basic.init(s);
28040     },
28041     
28042     getElementSize : function(s){
28043         return this.basic.getElementSize(s);
28044     },
28045     
28046     setElementSize : function(s, newSize, onComplete){
28047         this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
28048     },
28049     
28050     moveSplitter : function(s){
28051         var yes = Roo.SplitBar;
28052         switch(s.placement){
28053             case yes.LEFT:
28054                 s.el.setX(s.resizingEl.getRight());
28055                 break;
28056             case yes.RIGHT:
28057                 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
28058                 break;
28059             case yes.TOP:
28060                 s.el.setY(s.resizingEl.getBottom());
28061                 break;
28062             case yes.BOTTOM:
28063                 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
28064                 break;
28065         }
28066     }
28067 };
28068
28069 /**
28070  * Orientation constant - Create a vertical SplitBar
28071  * @static
28072  * @type Number
28073  */
28074 Roo.SplitBar.VERTICAL = 1;
28075
28076 /**
28077  * Orientation constant - Create a horizontal SplitBar
28078  * @static
28079  * @type Number
28080  */
28081 Roo.SplitBar.HORIZONTAL = 2;
28082
28083 /**
28084  * Placement constant - The resizing element is to the left of the splitter element
28085  * @static
28086  * @type Number
28087  */
28088 Roo.SplitBar.LEFT = 1;
28089
28090 /**
28091  * Placement constant - The resizing element is to the right of the splitter element
28092  * @static
28093  * @type Number
28094  */
28095 Roo.SplitBar.RIGHT = 2;
28096
28097 /**
28098  * Placement constant - The resizing element is positioned above the splitter element
28099  * @static
28100  * @type Number
28101  */
28102 Roo.SplitBar.TOP = 3;
28103
28104 /**
28105  * Placement constant - The resizing element is positioned under splitter element
28106  * @static
28107  * @type Number
28108  */
28109 Roo.SplitBar.BOTTOM = 4;
28110 /*
28111  * Based on:
28112  * Ext JS Library 1.1.1
28113  * Copyright(c) 2006-2007, Ext JS, LLC.
28114  *
28115  * Originally Released Under LGPL - original licence link has changed is not relivant.
28116  *
28117  * Fork - LGPL
28118  * <script type="text/javascript">
28119  */
28120
28121 /**
28122  * @class Roo.View
28123  * @extends Roo.util.Observable
28124  * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template. 
28125  * This class also supports single and multi selection modes. <br>
28126  * Create a data model bound view:
28127  <pre><code>
28128  var store = new Roo.data.Store(...);
28129
28130  var view = new Roo.View({
28131     el : "my-element",
28132     tpl : '&lt;div id="{0}"&gt;{2} - {1}&lt;/div&gt;', // auto create template
28133  
28134     singleSelect: true,
28135     selectedClass: "ydataview-selected",
28136     store: store
28137  });
28138
28139  // listen for node click?
28140  view.on("click", function(vw, index, node, e){
28141  alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
28142  });
28143
28144  // load XML data
28145  dataModel.load("foobar.xml");
28146  </code></pre>
28147  For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
28148  * <br><br>
28149  * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
28150  * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
28151  * 
28152  * Note: old style constructor is still suported (container, template, config)
28153  * 
28154  * @constructor
28155  * Create a new View
28156  * @param {Object} config The config object
28157  * 
28158  */
28159 Roo.View = function(config, depreciated_tpl, depreciated_config){
28160     
28161     this.parent = false;
28162     
28163     if (typeof(depreciated_tpl) == 'undefined') {
28164         // new way.. - universal constructor.
28165         Roo.apply(this, config);
28166         this.el  = Roo.get(this.el);
28167     } else {
28168         // old format..
28169         this.el  = Roo.get(config);
28170         this.tpl = depreciated_tpl;
28171         Roo.apply(this, depreciated_config);
28172     }
28173     this.wrapEl  = this.el.wrap().wrap();
28174     ///this.el = this.wrapEla.appendChild(document.createElement("div"));
28175     
28176     
28177     if(typeof(this.tpl) == "string"){
28178         this.tpl = new Roo.Template(this.tpl);
28179     } else {
28180         // support xtype ctors..
28181         this.tpl = new Roo.factory(this.tpl, Roo);
28182     }
28183     
28184     
28185     this.tpl.compile();
28186     
28187     /** @private */
28188     this.addEvents({
28189         /**
28190          * @event beforeclick
28191          * Fires before a click is processed. Returns false to cancel the default action.
28192          * @param {Roo.View} this
28193          * @param {Number} index The index of the target node
28194          * @param {HTMLElement} node The target node
28195          * @param {Roo.EventObject} e The raw event object
28196          */
28197             "beforeclick" : true,
28198         /**
28199          * @event click
28200          * Fires when a template node is clicked.
28201          * @param {Roo.View} this
28202          * @param {Number} index The index of the target node
28203          * @param {HTMLElement} node The target node
28204          * @param {Roo.EventObject} e The raw event object
28205          */
28206             "click" : true,
28207         /**
28208          * @event dblclick
28209          * Fires when a template node is double clicked.
28210          * @param {Roo.View} this
28211          * @param {Number} index The index of the target node
28212          * @param {HTMLElement} node The target node
28213          * @param {Roo.EventObject} e The raw event object
28214          */
28215             "dblclick" : true,
28216         /**
28217          * @event contextmenu
28218          * Fires when a template node is right clicked.
28219          * @param {Roo.View} this
28220          * @param {Number} index The index of the target node
28221          * @param {HTMLElement} node The target node
28222          * @param {Roo.EventObject} e The raw event object
28223          */
28224             "contextmenu" : true,
28225         /**
28226          * @event selectionchange
28227          * Fires when the selected nodes change.
28228          * @param {Roo.View} this
28229          * @param {Array} selections Array of the selected nodes
28230          */
28231             "selectionchange" : true,
28232     
28233         /**
28234          * @event beforeselect
28235          * Fires before a selection is made. If any handlers return false, the selection is cancelled.
28236          * @param {Roo.View} this
28237          * @param {HTMLElement} node The node to be selected
28238          * @param {Array} selections Array of currently selected nodes
28239          */
28240             "beforeselect" : true,
28241         /**
28242          * @event preparedata
28243          * Fires on every row to render, to allow you to change the data.
28244          * @param {Roo.View} this
28245          * @param {Object} data to be rendered (change this)
28246          */
28247           "preparedata" : true
28248           
28249           
28250         });
28251
28252
28253
28254     this.el.on({
28255         "click": this.onClick,
28256         "dblclick": this.onDblClick,
28257         "contextmenu": this.onContextMenu,
28258         scope:this
28259     });
28260
28261     this.selections = [];
28262     this.nodes = [];
28263     this.cmp = new Roo.CompositeElementLite([]);
28264     if(this.store){
28265         this.store = Roo.factory(this.store, Roo.data);
28266         this.setStore(this.store, true);
28267     }
28268     
28269     if ( this.footer && this.footer.xtype) {
28270            
28271          var fctr = this.wrapEl.appendChild(document.createElement("div"));
28272         
28273         this.footer.dataSource = this.store;
28274         this.footer.container = fctr;
28275         this.footer = Roo.factory(this.footer, Roo);
28276         fctr.insertFirst(this.el);
28277         
28278         // this is a bit insane - as the paging toolbar seems to detach the el..
28279 //        dom.parentNode.parentNode.parentNode
28280          // they get detached?
28281     }
28282     
28283     
28284     Roo.View.superclass.constructor.call(this);
28285     
28286     
28287 };
28288
28289 Roo.extend(Roo.View, Roo.util.Observable, {
28290     
28291      /**
28292      * @cfg {Roo.data.Store} store Data store to load data from.
28293      */
28294     store : false,
28295     
28296     /**
28297      * @cfg {String|Roo.Element} el The container element.
28298      */
28299     el : '',
28300     
28301     /**
28302      * @cfg {String|Roo.Template} tpl The template used by this View 
28303      */
28304     tpl : false,
28305     /**
28306      * @cfg {String} dataName the named area of the template to use as the data area
28307      *                          Works with domtemplates roo-name="name"
28308      */
28309     dataName: false,
28310     /**
28311      * @cfg {String} selectedClass The css class to add to selected nodes
28312      */
28313     selectedClass : "x-view-selected",
28314      /**
28315      * @cfg {String} emptyText The empty text to show when nothing is loaded.
28316      */
28317     emptyText : "",
28318     
28319     /**
28320      * @cfg {String} text to display on mask (default Loading)
28321      */
28322     mask : false,
28323     /**
28324      * @cfg {Boolean} multiSelect Allow multiple selection
28325      */
28326     multiSelect : false,
28327     /**
28328      * @cfg {Boolean} singleSelect Allow single selection
28329      */
28330     singleSelect:  false,
28331     
28332     /**
28333      * @cfg {Boolean} toggleSelect - selecting 
28334      */
28335     toggleSelect : false,
28336     
28337     /**
28338      * @cfg {Boolean} tickable - selecting 
28339      */
28340     tickable : false,
28341     
28342     /**
28343      * Returns the element this view is bound to.
28344      * @return {Roo.Element}
28345      */
28346     getEl : function(){
28347         return this.wrapEl;
28348     },
28349     
28350     
28351
28352     /**
28353      * Refreshes the view. - called by datachanged on the store. - do not call directly.
28354      */
28355     refresh : function(){
28356         //Roo.log('refresh');
28357         var t = this.tpl;
28358         
28359         // if we are using something like 'domtemplate', then
28360         // the what gets used is:
28361         // t.applySubtemplate(NAME, data, wrapping data..)
28362         // the outer template then get' applied with
28363         //     the store 'extra data'
28364         // and the body get's added to the
28365         //      roo-name="data" node?
28366         //      <span class='roo-tpl-{name}'></span> ?????
28367         
28368         
28369         
28370         this.clearSelections();
28371         this.el.update("");
28372         var html = [];
28373         var records = this.store.getRange();
28374         if(records.length < 1) {
28375             
28376             // is this valid??  = should it render a template??
28377             
28378             this.el.update(this.emptyText);
28379             return;
28380         }
28381         var el = this.el;
28382         if (this.dataName) {
28383             this.el.update(t.apply(this.store.meta)); //????
28384             el = this.el.child('.roo-tpl-' + this.dataName);
28385         }
28386         
28387         for(var i = 0, len = records.length; i < len; i++){
28388             var data = this.prepareData(records[i].data, i, records[i]);
28389             this.fireEvent("preparedata", this, data, i, records[i]);
28390             
28391             var d = Roo.apply({}, data);
28392             
28393             if(this.tickable){
28394                 Roo.apply(d, {'roo-id' : Roo.id()});
28395                 
28396                 var _this = this;
28397             
28398                 Roo.each(this.parent.item, function(item){
28399                     if(item[_this.parent.valueField] != data[_this.parent.valueField]){
28400                         return;
28401                     }
28402                     Roo.apply(d, {'roo-data-checked' : 'checked'});
28403                 });
28404             }
28405             
28406             html[html.length] = Roo.util.Format.trim(
28407                 this.dataName ?
28408                     t.applySubtemplate(this.dataName, d, this.store.meta) :
28409                     t.apply(d)
28410             );
28411         }
28412         
28413         
28414         
28415         el.update(html.join(""));
28416         this.nodes = el.dom.childNodes;
28417         this.updateIndexes(0);
28418     },
28419     
28420
28421     /**
28422      * Function to override to reformat the data that is sent to
28423      * the template for each node.
28424      * DEPRICATED - use the preparedata event handler.
28425      * @param {Array/Object} data The raw data (array of colData for a data model bound view or
28426      * a JSON object for an UpdateManager bound view).
28427      */
28428     prepareData : function(data, index, record)
28429     {
28430         this.fireEvent("preparedata", this, data, index, record);
28431         return data;
28432     },
28433
28434     onUpdate : function(ds, record){
28435         // Roo.log('on update');   
28436         this.clearSelections();
28437         var index = this.store.indexOf(record);
28438         var n = this.nodes[index];
28439         this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
28440         n.parentNode.removeChild(n);
28441         this.updateIndexes(index, index);
28442     },
28443
28444     
28445     
28446 // --------- FIXME     
28447     onAdd : function(ds, records, index)
28448     {
28449         //Roo.log(['on Add', ds, records, index] );        
28450         this.clearSelections();
28451         if(this.nodes.length == 0){
28452             this.refresh();
28453             return;
28454         }
28455         var n = this.nodes[index];
28456         for(var i = 0, len = records.length; i < len; i++){
28457             var d = this.prepareData(records[i].data, i, records[i]);
28458             if(n){
28459                 this.tpl.insertBefore(n, d);
28460             }else{
28461                 
28462                 this.tpl.append(this.el, d);
28463             }
28464         }
28465         this.updateIndexes(index);
28466     },
28467
28468     onRemove : function(ds, record, index){
28469        // Roo.log('onRemove');
28470         this.clearSelections();
28471         var el = this.dataName  ?
28472             this.el.child('.roo-tpl-' + this.dataName) :
28473             this.el; 
28474         
28475         el.dom.removeChild(this.nodes[index]);
28476         this.updateIndexes(index);
28477     },
28478
28479     /**
28480      * Refresh an individual node.
28481      * @param {Number} index
28482      */
28483     refreshNode : function(index){
28484         this.onUpdate(this.store, this.store.getAt(index));
28485     },
28486
28487     updateIndexes : function(startIndex, endIndex){
28488         var ns = this.nodes;
28489         startIndex = startIndex || 0;
28490         endIndex = endIndex || ns.length - 1;
28491         for(var i = startIndex; i <= endIndex; i++){
28492             ns[i].nodeIndex = i;
28493         }
28494     },
28495
28496     /**
28497      * Changes the data store this view uses and refresh the view.
28498      * @param {Store} store
28499      */
28500     setStore : function(store, initial){
28501         if(!initial && this.store){
28502             this.store.un("datachanged", this.refresh);
28503             this.store.un("add", this.onAdd);
28504             this.store.un("remove", this.onRemove);
28505             this.store.un("update", this.onUpdate);
28506             this.store.un("clear", this.refresh);
28507             this.store.un("beforeload", this.onBeforeLoad);
28508             this.store.un("load", this.onLoad);
28509             this.store.un("loadexception", this.onLoad);
28510         }
28511         if(store){
28512           
28513             store.on("datachanged", this.refresh, this);
28514             store.on("add", this.onAdd, this);
28515             store.on("remove", this.onRemove, this);
28516             store.on("update", this.onUpdate, this);
28517             store.on("clear", this.refresh, this);
28518             store.on("beforeload", this.onBeforeLoad, this);
28519             store.on("load", this.onLoad, this);
28520             store.on("loadexception", this.onLoad, this);
28521         }
28522         
28523         if(store){
28524             this.refresh();
28525         }
28526     },
28527     /**
28528      * onbeforeLoad - masks the loading area.
28529      *
28530      */
28531     onBeforeLoad : function(store,opts)
28532     {
28533          //Roo.log('onBeforeLoad');   
28534         if (!opts.add) {
28535             this.el.update("");
28536         }
28537         this.el.mask(this.mask ? this.mask : "Loading" ); 
28538     },
28539     onLoad : function ()
28540     {
28541         this.el.unmask();
28542     },
28543     
28544
28545     /**
28546      * Returns the template node the passed child belongs to or null if it doesn't belong to one.
28547      * @param {HTMLElement} node
28548      * @return {HTMLElement} The template node
28549      */
28550     findItemFromChild : function(node){
28551         var el = this.dataName  ?
28552             this.el.child('.roo-tpl-' + this.dataName,true) :
28553             this.el.dom; 
28554         
28555         if(!node || node.parentNode == el){
28556                     return node;
28557             }
28558             var p = node.parentNode;
28559             while(p && p != el){
28560             if(p.parentNode == el){
28561                 return p;
28562             }
28563             p = p.parentNode;
28564         }
28565             return null;
28566     },
28567
28568     /** @ignore */
28569     onClick : function(e){
28570         var item = this.findItemFromChild(e.getTarget());
28571         if(item){
28572             var index = this.indexOf(item);
28573             if(this.onItemClick(item, index, e) !== false){
28574                 this.fireEvent("click", this, index, item, e);
28575             }
28576         }else{
28577             this.clearSelections();
28578         }
28579     },
28580
28581     /** @ignore */
28582     onContextMenu : function(e){
28583         var item = this.findItemFromChild(e.getTarget());
28584         if(item){
28585             this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
28586         }
28587     },
28588
28589     /** @ignore */
28590     onDblClick : function(e){
28591         var item = this.findItemFromChild(e.getTarget());
28592         if(item){
28593             this.fireEvent("dblclick", this, this.indexOf(item), item, e);
28594         }
28595     },
28596
28597     onItemClick : function(item, index, e)
28598     {
28599         if(this.fireEvent("beforeclick", this, index, item, e) === false){
28600             return false;
28601         }
28602         if (this.toggleSelect) {
28603             var m = this.isSelected(item) ? 'unselect' : 'select';
28604             //Roo.log(m);
28605             var _t = this;
28606             _t[m](item, true, false);
28607             return true;
28608         }
28609         if(this.multiSelect || this.singleSelect){
28610             if(this.multiSelect && e.shiftKey && this.lastSelection){
28611                 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
28612             }else{
28613                 this.select(item, this.multiSelect && e.ctrlKey);
28614                 this.lastSelection = item;
28615             }
28616             
28617             if(!this.tickable){
28618                 e.preventDefault();
28619             }
28620             
28621         }
28622         return true;
28623     },
28624
28625     /**
28626      * Get the number of selected nodes.
28627      * @return {Number}
28628      */
28629     getSelectionCount : function(){
28630         return this.selections.length;
28631     },
28632
28633     /**
28634      * Get the currently selected nodes.
28635      * @return {Array} An array of HTMLElements
28636      */
28637     getSelectedNodes : function(){
28638         return this.selections;
28639     },
28640
28641     /**
28642      * Get the indexes of the selected nodes.
28643      * @return {Array}
28644      */
28645     getSelectedIndexes : function(){
28646         var indexes = [], s = this.selections;
28647         for(var i = 0, len = s.length; i < len; i++){
28648             indexes.push(s[i].nodeIndex);
28649         }
28650         return indexes;
28651     },
28652
28653     /**
28654      * Clear all selections
28655      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
28656      */
28657     clearSelections : function(suppressEvent){
28658         if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
28659             this.cmp.elements = this.selections;
28660             this.cmp.removeClass(this.selectedClass);
28661             this.selections = [];
28662             if(!suppressEvent){
28663                 this.fireEvent("selectionchange", this, this.selections);
28664             }
28665         }
28666     },
28667
28668     /**
28669      * Returns true if the passed node is selected
28670      * @param {HTMLElement/Number} node The node or node index
28671      * @return {Boolean}
28672      */
28673     isSelected : function(node){
28674         var s = this.selections;
28675         if(s.length < 1){
28676             return false;
28677         }
28678         node = this.getNode(node);
28679         return s.indexOf(node) !== -1;
28680     },
28681
28682     /**
28683      * Selects nodes.
28684      * @param {Array/HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node, id of a template node or an array of any of those to select
28685      * @param {Boolean} keepExisting (optional) true to keep existing selections
28686      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
28687      */
28688     select : function(nodeInfo, keepExisting, suppressEvent){
28689         if(nodeInfo instanceof Array){
28690             if(!keepExisting){
28691                 this.clearSelections(true);
28692             }
28693             for(var i = 0, len = nodeInfo.length; i < len; i++){
28694                 this.select(nodeInfo[i], true, true);
28695             }
28696             return;
28697         } 
28698         var node = this.getNode(nodeInfo);
28699         if(!node || this.isSelected(node)){
28700             return; // already selected.
28701         }
28702         if(!keepExisting){
28703             this.clearSelections(true);
28704         }
28705         
28706         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
28707             Roo.fly(node).addClass(this.selectedClass);
28708             this.selections.push(node);
28709             if(!suppressEvent){
28710                 this.fireEvent("selectionchange", this, this.selections);
28711             }
28712         }
28713         
28714         
28715     },
28716       /**
28717      * Unselects nodes.
28718      * @param {Array/HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node, id of a template node or an array of any of those to select
28719      * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
28720      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
28721      */
28722     unselect : function(nodeInfo, keepExisting, suppressEvent)
28723     {
28724         if(nodeInfo instanceof Array){
28725             Roo.each(this.selections, function(s) {
28726                 this.unselect(s, nodeInfo);
28727             }, this);
28728             return;
28729         }
28730         var node = this.getNode(nodeInfo);
28731         if(!node || !this.isSelected(node)){
28732             //Roo.log("not selected");
28733             return; // not selected.
28734         }
28735         // fireevent???
28736         var ns = [];
28737         Roo.each(this.selections, function(s) {
28738             if (s == node ) {
28739                 Roo.fly(node).removeClass(this.selectedClass);
28740
28741                 return;
28742             }
28743             ns.push(s);
28744         },this);
28745         
28746         this.selections= ns;
28747         this.fireEvent("selectionchange", this, this.selections);
28748     },
28749
28750     /**
28751      * Gets a template node.
28752      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
28753      * @return {HTMLElement} The node or null if it wasn't found
28754      */
28755     getNode : function(nodeInfo){
28756         if(typeof nodeInfo == "string"){
28757             return document.getElementById(nodeInfo);
28758         }else if(typeof nodeInfo == "number"){
28759             return this.nodes[nodeInfo];
28760         }
28761         return nodeInfo;
28762     },
28763
28764     /**
28765      * Gets a range template nodes.
28766      * @param {Number} startIndex
28767      * @param {Number} endIndex
28768      * @return {Array} An array of nodes
28769      */
28770     getNodes : function(start, end){
28771         var ns = this.nodes;
28772         start = start || 0;
28773         end = typeof end == "undefined" ? ns.length - 1 : end;
28774         var nodes = [];
28775         if(start <= end){
28776             for(var i = start; i <= end; i++){
28777                 nodes.push(ns[i]);
28778             }
28779         } else{
28780             for(var i = start; i >= end; i--){
28781                 nodes.push(ns[i]);
28782             }
28783         }
28784         return nodes;
28785     },
28786
28787     /**
28788      * Finds the index of the passed node
28789      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
28790      * @return {Number} The index of the node or -1
28791      */
28792     indexOf : function(node){
28793         node = this.getNode(node);
28794         if(typeof node.nodeIndex == "number"){
28795             return node.nodeIndex;
28796         }
28797         var ns = this.nodes;
28798         for(var i = 0, len = ns.length; i < len; i++){
28799             if(ns[i] == node){
28800                 return i;
28801             }
28802         }
28803         return -1;
28804     }
28805 });
28806 /*
28807  * Based on:
28808  * Ext JS Library 1.1.1
28809  * Copyright(c) 2006-2007, Ext JS, LLC.
28810  *
28811  * Originally Released Under LGPL - original licence link has changed is not relivant.
28812  *
28813  * Fork - LGPL
28814  * <script type="text/javascript">
28815  */
28816
28817 /**
28818  * @class Roo.JsonView
28819  * @extends Roo.View
28820  * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
28821 <pre><code>
28822 var view = new Roo.JsonView({
28823     container: "my-element",
28824     tpl: '&lt;div id="{id}"&gt;{foo} - {bar}&lt;/div&gt;', // auto create template
28825     multiSelect: true, 
28826     jsonRoot: "data" 
28827 });
28828
28829 // listen for node click?
28830 view.on("click", function(vw, index, node, e){
28831     alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
28832 });
28833
28834 // direct load of JSON data
28835 view.load("foobar.php");
28836
28837 // Example from my blog list
28838 var tpl = new Roo.Template(
28839     '&lt;div class="entry"&gt;' +
28840     '&lt;a class="entry-title" href="{link}"&gt;{title}&lt;/a&gt;' +
28841     "&lt;h4&gt;{date} by {author} | {comments} Comments&lt;/h4&gt;{description}" +
28842     "&lt;/div&gt;&lt;hr /&gt;"
28843 );
28844
28845 var moreView = new Roo.JsonView({
28846     container :  "entry-list", 
28847     template : tpl,
28848     jsonRoot: "posts"
28849 });
28850 moreView.on("beforerender", this.sortEntries, this);
28851 moreView.load({
28852     url: "/blog/get-posts.php",
28853     params: "allposts=true",
28854     text: "Loading Blog Entries..."
28855 });
28856 </code></pre>
28857
28858 * Note: old code is supported with arguments : (container, template, config)
28859
28860
28861  * @constructor
28862  * Create a new JsonView
28863  * 
28864  * @param {Object} config The config object
28865  * 
28866  */
28867 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
28868     
28869     
28870     Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
28871
28872     var um = this.el.getUpdateManager();
28873     um.setRenderer(this);
28874     um.on("update", this.onLoad, this);
28875     um.on("failure", this.onLoadException, this);
28876
28877     /**
28878      * @event beforerender
28879      * Fires before rendering of the downloaded JSON data.
28880      * @param {Roo.JsonView} this
28881      * @param {Object} data The JSON data loaded
28882      */
28883     /**
28884      * @event load
28885      * Fires when data is loaded.
28886      * @param {Roo.JsonView} this
28887      * @param {Object} data The JSON data loaded
28888      * @param {Object} response The raw Connect response object
28889      */
28890     /**
28891      * @event loadexception
28892      * Fires when loading fails.
28893      * @param {Roo.JsonView} this
28894      * @param {Object} response The raw Connect response object
28895      */
28896     this.addEvents({
28897         'beforerender' : true,
28898         'load' : true,
28899         'loadexception' : true
28900     });
28901 };
28902 Roo.extend(Roo.JsonView, Roo.View, {
28903     /**
28904      * @type {String} The root property in the loaded JSON object that contains the data
28905      */
28906     jsonRoot : "",
28907
28908     /**
28909      * Refreshes the view.
28910      */
28911     refresh : function(){
28912         this.clearSelections();
28913         this.el.update("");
28914         var html = [];
28915         var o = this.jsonData;
28916         if(o && o.length > 0){
28917             for(var i = 0, len = o.length; i < len; i++){
28918                 var data = this.prepareData(o[i], i, o);
28919                 html[html.length] = this.tpl.apply(data);
28920             }
28921         }else{
28922             html.push(this.emptyText);
28923         }
28924         this.el.update(html.join(""));
28925         this.nodes = this.el.dom.childNodes;
28926         this.updateIndexes(0);
28927     },
28928
28929     /**
28930      * Performs an async HTTP request, and loads the JSON from the response. If <i>params</i> are specified it uses POST, otherwise it uses GET.
28931      * @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:
28932      <pre><code>
28933      view.load({
28934          url: "your-url.php",
28935          params: {param1: "foo", param2: "bar"}, // or a URL encoded string
28936          callback: yourFunction,
28937          scope: yourObject, //(optional scope)
28938          discardUrl: false,
28939          nocache: false,
28940          text: "Loading...",
28941          timeout: 30,
28942          scripts: false
28943      });
28944      </code></pre>
28945      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
28946      * are respectively shorthand for <i>disableCaching</i>, <i>indicatorText</i>, and <i>loadScripts</i> and are used to set their associated property on this UpdateManager instance.
28947      * @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}
28948      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
28949      * @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.
28950      */
28951     load : function(){
28952         var um = this.el.getUpdateManager();
28953         um.update.apply(um, arguments);
28954     },
28955
28956     // note - render is a standard framework call...
28957     // using it for the response is really flaky... - it's called by UpdateManager normally, except when called by the XComponent/addXtype.
28958     render : function(el, response){
28959         
28960         this.clearSelections();
28961         this.el.update("");
28962         var o;
28963         try{
28964             if (response != '') {
28965                 o = Roo.util.JSON.decode(response.responseText);
28966                 if(this.jsonRoot){
28967                     
28968                     o = o[this.jsonRoot];
28969                 }
28970             }
28971         } catch(e){
28972         }
28973         /**
28974          * The current JSON data or null
28975          */
28976         this.jsonData = o;
28977         this.beforeRender();
28978         this.refresh();
28979     },
28980
28981 /**
28982  * Get the number of records in the current JSON dataset
28983  * @return {Number}
28984  */
28985     getCount : function(){
28986         return this.jsonData ? this.jsonData.length : 0;
28987     },
28988
28989 /**
28990  * Returns the JSON object for the specified node(s)
28991  * @param {HTMLElement/Array} node The node or an array of nodes
28992  * @return {Object/Array} If you pass in an array, you get an array back, otherwise
28993  * you get the JSON object for the node
28994  */
28995     getNodeData : function(node){
28996         if(node instanceof Array){
28997             var data = [];
28998             for(var i = 0, len = node.length; i < len; i++){
28999                 data.push(this.getNodeData(node[i]));
29000             }
29001             return data;
29002         }
29003         return this.jsonData[this.indexOf(node)] || null;
29004     },
29005
29006     beforeRender : function(){
29007         this.snapshot = this.jsonData;
29008         if(this.sortInfo){
29009             this.sort.apply(this, this.sortInfo);
29010         }
29011         this.fireEvent("beforerender", this, this.jsonData);
29012     },
29013
29014     onLoad : function(el, o){
29015         this.fireEvent("load", this, this.jsonData, o);
29016     },
29017
29018     onLoadException : function(el, o){
29019         this.fireEvent("loadexception", this, o);
29020     },
29021
29022 /**
29023  * Filter the data by a specific property.
29024  * @param {String} property A property on your JSON objects
29025  * @param {String/RegExp} value Either string that the property values
29026  * should start with, or a RegExp to test against the property
29027  */
29028     filter : function(property, value){
29029         if(this.jsonData){
29030             var data = [];
29031             var ss = this.snapshot;
29032             if(typeof value == "string"){
29033                 var vlen = value.length;
29034                 if(vlen == 0){
29035                     this.clearFilter();
29036                     return;
29037                 }
29038                 value = value.toLowerCase();
29039                 for(var i = 0, len = ss.length; i < len; i++){
29040                     var o = ss[i];
29041                     if(o[property].substr(0, vlen).toLowerCase() == value){
29042                         data.push(o);
29043                     }
29044                 }
29045             } else if(value.exec){ // regex?
29046                 for(var i = 0, len = ss.length; i < len; i++){
29047                     var o = ss[i];
29048                     if(value.test(o[property])){
29049                         data.push(o);
29050                     }
29051                 }
29052             } else{
29053                 return;
29054             }
29055             this.jsonData = data;
29056             this.refresh();
29057         }
29058     },
29059
29060 /**
29061  * Filter by a function. The passed function will be called with each
29062  * object in the current dataset. If the function returns true the value is kept,
29063  * otherwise it is filtered.
29064  * @param {Function} fn
29065  * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
29066  */
29067     filterBy : function(fn, scope){
29068         if(this.jsonData){
29069             var data = [];
29070             var ss = this.snapshot;
29071             for(var i = 0, len = ss.length; i < len; i++){
29072                 var o = ss[i];
29073                 if(fn.call(scope || this, o)){
29074                     data.push(o);
29075                 }
29076             }
29077             this.jsonData = data;
29078             this.refresh();
29079         }
29080     },
29081
29082 /**
29083  * Clears the current filter.
29084  */
29085     clearFilter : function(){
29086         if(this.snapshot && this.jsonData != this.snapshot){
29087             this.jsonData = this.snapshot;
29088             this.refresh();
29089         }
29090     },
29091
29092
29093 /**
29094  * Sorts the data for this view and refreshes it.
29095  * @param {String} property A property on your JSON objects to sort on
29096  * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
29097  * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
29098  */
29099     sort : function(property, dir, sortType){
29100         this.sortInfo = Array.prototype.slice.call(arguments, 0);
29101         if(this.jsonData){
29102             var p = property;
29103             var dsc = dir && dir.toLowerCase() == "desc";
29104             var f = function(o1, o2){
29105                 var v1 = sortType ? sortType(o1[p]) : o1[p];
29106                 var v2 = sortType ? sortType(o2[p]) : o2[p];
29107                 ;
29108                 if(v1 < v2){
29109                     return dsc ? +1 : -1;
29110                 } else if(v1 > v2){
29111                     return dsc ? -1 : +1;
29112                 } else{
29113                     return 0;
29114                 }
29115             };
29116             this.jsonData.sort(f);
29117             this.refresh();
29118             if(this.jsonData != this.snapshot){
29119                 this.snapshot.sort(f);
29120             }
29121         }
29122     }
29123 });/*
29124  * Based on:
29125  * Ext JS Library 1.1.1
29126  * Copyright(c) 2006-2007, Ext JS, LLC.
29127  *
29128  * Originally Released Under LGPL - original licence link has changed is not relivant.
29129  *
29130  * Fork - LGPL
29131  * <script type="text/javascript">
29132  */
29133  
29134
29135 /**
29136  * @class Roo.ColorPalette
29137  * @extends Roo.Component
29138  * Simple color palette class for choosing colors.  The palette can be rendered to any container.<br />
29139  * Here's an example of typical usage:
29140  * <pre><code>
29141 var cp = new Roo.ColorPalette({value:'993300'});  // initial selected color
29142 cp.render('my-div');
29143
29144 cp.on('select', function(palette, selColor){
29145     // do something with selColor
29146 });
29147 </code></pre>
29148  * @constructor
29149  * Create a new ColorPalette
29150  * @param {Object} config The config object
29151  */
29152 Roo.ColorPalette = function(config){
29153     Roo.ColorPalette.superclass.constructor.call(this, config);
29154     this.addEvents({
29155         /**
29156              * @event select
29157              * Fires when a color is selected
29158              * @param {ColorPalette} this
29159              * @param {String} color The 6-digit color hex code (without the # symbol)
29160              */
29161         select: true
29162     });
29163
29164     if(this.handler){
29165         this.on("select", this.handler, this.scope, true);
29166     }
29167 };
29168 Roo.extend(Roo.ColorPalette, Roo.Component, {
29169     /**
29170      * @cfg {String} itemCls
29171      * The CSS class to apply to the containing element (defaults to "x-color-palette")
29172      */
29173     itemCls : "x-color-palette",
29174     /**
29175      * @cfg {String} value
29176      * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol).  Note that
29177      * the hex codes are case-sensitive.
29178      */
29179     value : null,
29180     clickEvent:'click',
29181     // private
29182     ctype: "Roo.ColorPalette",
29183
29184     /**
29185      * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
29186      */
29187     allowReselect : false,
29188
29189     /**
29190      * <p>An array of 6-digit color hex code strings (without the # symbol).  This array can contain any number
29191      * of colors, and each hex code should be unique.  The width of the palette is controlled via CSS by adjusting
29192      * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
29193      * of colors with the width setting until the box is symmetrical.</p>
29194      * <p>You can override individual colors if needed:</p>
29195      * <pre><code>
29196 var cp = new Roo.ColorPalette();
29197 cp.colors[0] = "FF0000";  // change the first box to red
29198 </code></pre>
29199
29200 Or you can provide a custom array of your own for complete control:
29201 <pre><code>
29202 var cp = new Roo.ColorPalette();
29203 cp.colors = ["000000", "993300", "333300"];
29204 </code></pre>
29205      * @type Array
29206      */
29207     colors : [
29208         "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
29209         "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
29210         "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
29211         "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
29212         "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
29213     ],
29214
29215     // private
29216     onRender : function(container, position){
29217         var t = new Roo.MasterTemplate(
29218             '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on">&#160;</span></em></a></tpl>'
29219         );
29220         var c = this.colors;
29221         for(var i = 0, len = c.length; i < len; i++){
29222             t.add([c[i]]);
29223         }
29224         var el = document.createElement("div");
29225         el.className = this.itemCls;
29226         t.overwrite(el);
29227         container.dom.insertBefore(el, position);
29228         this.el = Roo.get(el);
29229         this.el.on(this.clickEvent, this.handleClick,  this, {delegate: "a"});
29230         if(this.clickEvent != 'click'){
29231             this.el.on('click', Roo.emptyFn,  this, {delegate: "a", preventDefault:true});
29232         }
29233     },
29234
29235     // private
29236     afterRender : function(){
29237         Roo.ColorPalette.superclass.afterRender.call(this);
29238         if(this.value){
29239             var s = this.value;
29240             this.value = null;
29241             this.select(s);
29242         }
29243     },
29244
29245     // private
29246     handleClick : function(e, t){
29247         e.preventDefault();
29248         if(!this.disabled){
29249             var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
29250             this.select(c.toUpperCase());
29251         }
29252     },
29253
29254     /**
29255      * Selects the specified color in the palette (fires the select event)
29256      * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
29257      */
29258     select : function(color){
29259         color = color.replace("#", "");
29260         if(color != this.value || this.allowReselect){
29261             var el = this.el;
29262             if(this.value){
29263                 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
29264             }
29265             el.child("a.color-"+color).addClass("x-color-palette-sel");
29266             this.value = color;
29267             this.fireEvent("select", this, color);
29268         }
29269     }
29270 });/*
29271  * Based on:
29272  * Ext JS Library 1.1.1
29273  * Copyright(c) 2006-2007, Ext JS, LLC.
29274  *
29275  * Originally Released Under LGPL - original licence link has changed is not relivant.
29276  *
29277  * Fork - LGPL
29278  * <script type="text/javascript">
29279  */
29280  
29281 /**
29282  * @class Roo.DatePicker
29283  * @extends Roo.Component
29284  * Simple date picker class.
29285  * @constructor
29286  * Create a new DatePicker
29287  * @param {Object} config The config object
29288  */
29289 Roo.DatePicker = function(config){
29290     Roo.DatePicker.superclass.constructor.call(this, config);
29291
29292     this.value = config && config.value ?
29293                  config.value.clearTime() : new Date().clearTime();
29294
29295     this.addEvents({
29296         /**
29297              * @event select
29298              * Fires when a date is selected
29299              * @param {DatePicker} this
29300              * @param {Date} date The selected date
29301              */
29302         'select': true,
29303         /**
29304              * @event monthchange
29305              * Fires when the displayed month changes 
29306              * @param {DatePicker} this
29307              * @param {Date} date The selected month
29308              */
29309         'monthchange': true
29310     });
29311
29312     if(this.handler){
29313         this.on("select", this.handler,  this.scope || this);
29314     }
29315     // build the disabledDatesRE
29316     if(!this.disabledDatesRE && this.disabledDates){
29317         var dd = this.disabledDates;
29318         var re = "(?:";
29319         for(var i = 0; i < dd.length; i++){
29320             re += dd[i];
29321             if(i != dd.length-1) {
29322                 re += "|";
29323             }
29324         }
29325         this.disabledDatesRE = new RegExp(re + ")");
29326     }
29327 };
29328
29329 Roo.extend(Roo.DatePicker, Roo.Component, {
29330     /**
29331      * @cfg {String} todayText
29332      * The text to display on the button that selects the current date (defaults to "Today")
29333      */
29334     todayText : "Today",
29335     /**
29336      * @cfg {String} okText
29337      * The text to display on the ok button
29338      */
29339     okText : "&#160;OK&#160;", // &#160; to give the user extra clicking room
29340     /**
29341      * @cfg {String} cancelText
29342      * The text to display on the cancel button
29343      */
29344     cancelText : "Cancel",
29345     /**
29346      * @cfg {String} todayTip
29347      * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
29348      */
29349     todayTip : "{0} (Spacebar)",
29350     /**
29351      * @cfg {Date} minDate
29352      * Minimum allowable date (JavaScript date object, defaults to null)
29353      */
29354     minDate : null,
29355     /**
29356      * @cfg {Date} maxDate
29357      * Maximum allowable date (JavaScript date object, defaults to null)
29358      */
29359     maxDate : null,
29360     /**
29361      * @cfg {String} minText
29362      * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
29363      */
29364     minText : "This date is before the minimum date",
29365     /**
29366      * @cfg {String} maxText
29367      * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
29368      */
29369     maxText : "This date is after the maximum date",
29370     /**
29371      * @cfg {String} format
29372      * The default date format string which can be overriden for localization support.  The format must be
29373      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
29374      */
29375     format : "m/d/y",
29376     /**
29377      * @cfg {Array} disabledDays
29378      * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
29379      */
29380     disabledDays : null,
29381     /**
29382      * @cfg {String} disabledDaysText
29383      * The tooltip to display when the date falls on a disabled day (defaults to "")
29384      */
29385     disabledDaysText : "",
29386     /**
29387      * @cfg {RegExp} disabledDatesRE
29388      * JavaScript regular expression used to disable a pattern of dates (defaults to null)
29389      */
29390     disabledDatesRE : null,
29391     /**
29392      * @cfg {String} disabledDatesText
29393      * The tooltip text to display when the date falls on a disabled date (defaults to "")
29394      */
29395     disabledDatesText : "",
29396     /**
29397      * @cfg {Boolean} constrainToViewport
29398      * True to constrain the date picker to the viewport (defaults to true)
29399      */
29400     constrainToViewport : true,
29401     /**
29402      * @cfg {Array} monthNames
29403      * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
29404      */
29405     monthNames : Date.monthNames,
29406     /**
29407      * @cfg {Array} dayNames
29408      * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
29409      */
29410     dayNames : Date.dayNames,
29411     /**
29412      * @cfg {String} nextText
29413      * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
29414      */
29415     nextText: 'Next Month (Control+Right)',
29416     /**
29417      * @cfg {String} prevText
29418      * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
29419      */
29420     prevText: 'Previous Month (Control+Left)',
29421     /**
29422      * @cfg {String} monthYearText
29423      * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
29424      */
29425     monthYearText: 'Choose a month (Control+Up/Down to move years)',
29426     /**
29427      * @cfg {Number} startDay
29428      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
29429      */
29430     startDay : 0,
29431     /**
29432      * @cfg {Bool} showClear
29433      * Show a clear button (usefull for date form elements that can be blank.)
29434      */
29435     
29436     showClear: false,
29437     
29438     /**
29439      * Sets the value of the date field
29440      * @param {Date} value The date to set
29441      */
29442     setValue : function(value){
29443         var old = this.value;
29444         
29445         if (typeof(value) == 'string') {
29446          
29447             value = Date.parseDate(value, this.format);
29448         }
29449         if (!value) {
29450             value = new Date();
29451         }
29452         
29453         this.value = value.clearTime(true);
29454         if(this.el){
29455             this.update(this.value);
29456         }
29457     },
29458
29459     /**
29460      * Gets the current selected value of the date field
29461      * @return {Date} The selected date
29462      */
29463     getValue : function(){
29464         return this.value;
29465     },
29466
29467     // private
29468     focus : function(){
29469         if(this.el){
29470             this.update(this.activeDate);
29471         }
29472     },
29473
29474     // privateval
29475     onRender : function(container, position){
29476         
29477         var m = [
29478              '<table cellspacing="0">',
29479                 '<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'">&#160;</a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'">&#160;</a></td></tr>',
29480                 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
29481         var dn = this.dayNames;
29482         for(var i = 0; i < 7; i++){
29483             var d = this.startDay+i;
29484             if(d > 6){
29485                 d = d-7;
29486             }
29487             m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
29488         }
29489         m[m.length] = "</tr></thead><tbody><tr>";
29490         for(var i = 0; i < 42; i++) {
29491             if(i % 7 == 0 && i != 0){
29492                 m[m.length] = "</tr><tr>";
29493             }
29494             m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
29495         }
29496         m[m.length] = '</tr></tbody></table></td></tr><tr>'+
29497             '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
29498
29499         var el = document.createElement("div");
29500         el.className = "x-date-picker";
29501         el.innerHTML = m.join("");
29502
29503         container.dom.insertBefore(el, position);
29504
29505         this.el = Roo.get(el);
29506         this.eventEl = Roo.get(el.firstChild);
29507
29508         new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
29509             handler: this.showPrevMonth,
29510             scope: this,
29511             preventDefault:true,
29512             stopDefault:true
29513         });
29514
29515         new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
29516             handler: this.showNextMonth,
29517             scope: this,
29518             preventDefault:true,
29519             stopDefault:true
29520         });
29521
29522         this.eventEl.on("mousewheel", this.handleMouseWheel,  this);
29523
29524         this.monthPicker = this.el.down('div.x-date-mp');
29525         this.monthPicker.enableDisplayMode('block');
29526         
29527         var kn = new Roo.KeyNav(this.eventEl, {
29528             "left" : function(e){
29529                 e.ctrlKey ?
29530                     this.showPrevMonth() :
29531                     this.update(this.activeDate.add("d", -1));
29532             },
29533
29534             "right" : function(e){
29535                 e.ctrlKey ?
29536                     this.showNextMonth() :
29537                     this.update(this.activeDate.add("d", 1));
29538             },
29539
29540             "up" : function(e){
29541                 e.ctrlKey ?
29542                     this.showNextYear() :
29543                     this.update(this.activeDate.add("d", -7));
29544             },
29545
29546             "down" : function(e){
29547                 e.ctrlKey ?
29548                     this.showPrevYear() :
29549                     this.update(this.activeDate.add("d", 7));
29550             },
29551
29552             "pageUp" : function(e){
29553                 this.showNextMonth();
29554             },
29555
29556             "pageDown" : function(e){
29557                 this.showPrevMonth();
29558             },
29559
29560             "enter" : function(e){
29561                 e.stopPropagation();
29562                 return true;
29563             },
29564
29565             scope : this
29566         });
29567
29568         this.eventEl.on("click", this.handleDateClick,  this, {delegate: "a.x-date-date"});
29569
29570         this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday,  this);
29571
29572         this.el.unselectable();
29573         
29574         this.cells = this.el.select("table.x-date-inner tbody td");
29575         this.textNodes = this.el.query("table.x-date-inner tbody span");
29576
29577         this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
29578             text: "&#160;",
29579             tooltip: this.monthYearText
29580         });
29581
29582         this.mbtn.on('click', this.showMonthPicker, this);
29583         this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
29584
29585
29586         var today = (new Date()).dateFormat(this.format);
29587         
29588         var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
29589         if (this.showClear) {
29590             baseTb.add( new Roo.Toolbar.Fill());
29591         }
29592         baseTb.add({
29593             text: String.format(this.todayText, today),
29594             tooltip: String.format(this.todayTip, today),
29595             handler: this.selectToday,
29596             scope: this
29597         });
29598         
29599         //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
29600             
29601         //});
29602         if (this.showClear) {
29603             
29604             baseTb.add( new Roo.Toolbar.Fill());
29605             baseTb.add({
29606                 text: '&#160;',
29607                 cls: 'x-btn-icon x-btn-clear',
29608                 handler: function() {
29609                     //this.value = '';
29610                     this.fireEvent("select", this, '');
29611                 },
29612                 scope: this
29613             });
29614         }
29615         
29616         
29617         if(Roo.isIE){
29618             this.el.repaint();
29619         }
29620         this.update(this.value);
29621     },
29622
29623     createMonthPicker : function(){
29624         if(!this.monthPicker.dom.firstChild){
29625             var buf = ['<table border="0" cellspacing="0">'];
29626             for(var i = 0; i < 6; i++){
29627                 buf.push(
29628                     '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
29629                     '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
29630                     i == 0 ?
29631                     '<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' :
29632                     '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
29633                 );
29634             }
29635             buf.push(
29636                 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
29637                     this.okText,
29638                     '</button><button type="button" class="x-date-mp-cancel">',
29639                     this.cancelText,
29640                     '</button></td></tr>',
29641                 '</table>'
29642             );
29643             this.monthPicker.update(buf.join(''));
29644             this.monthPicker.on('click', this.onMonthClick, this);
29645             this.monthPicker.on('dblclick', this.onMonthDblClick, this);
29646
29647             this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
29648             this.mpYears = this.monthPicker.select('td.x-date-mp-year');
29649
29650             this.mpMonths.each(function(m, a, i){
29651                 i += 1;
29652                 if((i%2) == 0){
29653                     m.dom.xmonth = 5 + Math.round(i * .5);
29654                 }else{
29655                     m.dom.xmonth = Math.round((i-1) * .5);
29656                 }
29657             });
29658         }
29659     },
29660
29661     showMonthPicker : function(){
29662         this.createMonthPicker();
29663         var size = this.el.getSize();
29664         this.monthPicker.setSize(size);
29665         this.monthPicker.child('table').setSize(size);
29666
29667         this.mpSelMonth = (this.activeDate || this.value).getMonth();
29668         this.updateMPMonth(this.mpSelMonth);
29669         this.mpSelYear = (this.activeDate || this.value).getFullYear();
29670         this.updateMPYear(this.mpSelYear);
29671
29672         this.monthPicker.slideIn('t', {duration:.2});
29673     },
29674
29675     updateMPYear : function(y){
29676         this.mpyear = y;
29677         var ys = this.mpYears.elements;
29678         for(var i = 1; i <= 10; i++){
29679             var td = ys[i-1], y2;
29680             if((i%2) == 0){
29681                 y2 = y + Math.round(i * .5);
29682                 td.firstChild.innerHTML = y2;
29683                 td.xyear = y2;
29684             }else{
29685                 y2 = y - (5-Math.round(i * .5));
29686                 td.firstChild.innerHTML = y2;
29687                 td.xyear = y2;
29688             }
29689             this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
29690         }
29691     },
29692
29693     updateMPMonth : function(sm){
29694         this.mpMonths.each(function(m, a, i){
29695             m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
29696         });
29697     },
29698
29699     selectMPMonth: function(m){
29700         
29701     },
29702
29703     onMonthClick : function(e, t){
29704         e.stopEvent();
29705         var el = new Roo.Element(t), pn;
29706         if(el.is('button.x-date-mp-cancel')){
29707             this.hideMonthPicker();
29708         }
29709         else if(el.is('button.x-date-mp-ok')){
29710             this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
29711             this.hideMonthPicker();
29712         }
29713         else if(pn = el.up('td.x-date-mp-month', 2)){
29714             this.mpMonths.removeClass('x-date-mp-sel');
29715             pn.addClass('x-date-mp-sel');
29716             this.mpSelMonth = pn.dom.xmonth;
29717         }
29718         else if(pn = el.up('td.x-date-mp-year', 2)){
29719             this.mpYears.removeClass('x-date-mp-sel');
29720             pn.addClass('x-date-mp-sel');
29721             this.mpSelYear = pn.dom.xyear;
29722         }
29723         else if(el.is('a.x-date-mp-prev')){
29724             this.updateMPYear(this.mpyear-10);
29725         }
29726         else if(el.is('a.x-date-mp-next')){
29727             this.updateMPYear(this.mpyear+10);
29728         }
29729     },
29730
29731     onMonthDblClick : function(e, t){
29732         e.stopEvent();
29733         var el = new Roo.Element(t), pn;
29734         if(pn = el.up('td.x-date-mp-month', 2)){
29735             this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
29736             this.hideMonthPicker();
29737         }
29738         else if(pn = el.up('td.x-date-mp-year', 2)){
29739             this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
29740             this.hideMonthPicker();
29741         }
29742     },
29743
29744     hideMonthPicker : function(disableAnim){
29745         if(this.monthPicker){
29746             if(disableAnim === true){
29747                 this.monthPicker.hide();
29748             }else{
29749                 this.monthPicker.slideOut('t', {duration:.2});
29750             }
29751         }
29752     },
29753
29754     // private
29755     showPrevMonth : function(e){
29756         this.update(this.activeDate.add("mo", -1));
29757     },
29758
29759     // private
29760     showNextMonth : function(e){
29761         this.update(this.activeDate.add("mo", 1));
29762     },
29763
29764     // private
29765     showPrevYear : function(){
29766         this.update(this.activeDate.add("y", -1));
29767     },
29768
29769     // private
29770     showNextYear : function(){
29771         this.update(this.activeDate.add("y", 1));
29772     },
29773
29774     // private
29775     handleMouseWheel : function(e){
29776         var delta = e.getWheelDelta();
29777         if(delta > 0){
29778             this.showPrevMonth();
29779             e.stopEvent();
29780         } else if(delta < 0){
29781             this.showNextMonth();
29782             e.stopEvent();
29783         }
29784     },
29785
29786     // private
29787     handleDateClick : function(e, t){
29788         e.stopEvent();
29789         if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
29790             this.setValue(new Date(t.dateValue));
29791             this.fireEvent("select", this, this.value);
29792         }
29793     },
29794
29795     // private
29796     selectToday : function(){
29797         this.setValue(new Date().clearTime());
29798         this.fireEvent("select", this, this.value);
29799     },
29800
29801     // private
29802     update : function(date)
29803     {
29804         var vd = this.activeDate;
29805         this.activeDate = date;
29806         if(vd && this.el){
29807             var t = date.getTime();
29808             if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
29809                 this.cells.removeClass("x-date-selected");
29810                 this.cells.each(function(c){
29811                    if(c.dom.firstChild.dateValue == t){
29812                        c.addClass("x-date-selected");
29813                        setTimeout(function(){
29814                             try{c.dom.firstChild.focus();}catch(e){}
29815                        }, 50);
29816                        return false;
29817                    }
29818                 });
29819                 return;
29820             }
29821         }
29822         
29823         var days = date.getDaysInMonth();
29824         var firstOfMonth = date.getFirstDateOfMonth();
29825         var startingPos = firstOfMonth.getDay()-this.startDay;
29826
29827         if(startingPos <= this.startDay){
29828             startingPos += 7;
29829         }
29830
29831         var pm = date.add("mo", -1);
29832         var prevStart = pm.getDaysInMonth()-startingPos;
29833
29834         var cells = this.cells.elements;
29835         var textEls = this.textNodes;
29836         days += startingPos;
29837
29838         // convert everything to numbers so it's fast
29839         var day = 86400000;
29840         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
29841         var today = new Date().clearTime().getTime();
29842         var sel = date.clearTime().getTime();
29843         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
29844         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
29845         var ddMatch = this.disabledDatesRE;
29846         var ddText = this.disabledDatesText;
29847         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
29848         var ddaysText = this.disabledDaysText;
29849         var format = this.format;
29850
29851         var setCellClass = function(cal, cell){
29852             cell.title = "";
29853             var t = d.getTime();
29854             cell.firstChild.dateValue = t;
29855             if(t == today){
29856                 cell.className += " x-date-today";
29857                 cell.title = cal.todayText;
29858             }
29859             if(t == sel){
29860                 cell.className += " x-date-selected";
29861                 setTimeout(function(){
29862                     try{cell.firstChild.focus();}catch(e){}
29863                 }, 50);
29864             }
29865             // disabling
29866             if(t < min) {
29867                 cell.className = " x-date-disabled";
29868                 cell.title = cal.minText;
29869                 return;
29870             }
29871             if(t > max) {
29872                 cell.className = " x-date-disabled";
29873                 cell.title = cal.maxText;
29874                 return;
29875             }
29876             if(ddays){
29877                 if(ddays.indexOf(d.getDay()) != -1){
29878                     cell.title = ddaysText;
29879                     cell.className = " x-date-disabled";
29880                 }
29881             }
29882             if(ddMatch && format){
29883                 var fvalue = d.dateFormat(format);
29884                 if(ddMatch.test(fvalue)){
29885                     cell.title = ddText.replace("%0", fvalue);
29886                     cell.className = " x-date-disabled";
29887                 }
29888             }
29889         };
29890
29891         var i = 0;
29892         for(; i < startingPos; i++) {
29893             textEls[i].innerHTML = (++prevStart);
29894             d.setDate(d.getDate()+1);
29895             cells[i].className = "x-date-prevday";
29896             setCellClass(this, cells[i]);
29897         }
29898         for(; i < days; i++){
29899             intDay = i - startingPos + 1;
29900             textEls[i].innerHTML = (intDay);
29901             d.setDate(d.getDate()+1);
29902             cells[i].className = "x-date-active";
29903             setCellClass(this, cells[i]);
29904         }
29905         var extraDays = 0;
29906         for(; i < 42; i++) {
29907              textEls[i].innerHTML = (++extraDays);
29908              d.setDate(d.getDate()+1);
29909              cells[i].className = "x-date-nextday";
29910              setCellClass(this, cells[i]);
29911         }
29912
29913         this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
29914         this.fireEvent('monthchange', this, date);
29915         
29916         if(!this.internalRender){
29917             var main = this.el.dom.firstChild;
29918             var w = main.offsetWidth;
29919             this.el.setWidth(w + this.el.getBorderWidth("lr"));
29920             Roo.fly(main).setWidth(w);
29921             this.internalRender = true;
29922             // opera does not respect the auto grow header center column
29923             // then, after it gets a width opera refuses to recalculate
29924             // without a second pass
29925             if(Roo.isOpera && !this.secondPass){
29926                 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
29927                 this.secondPass = true;
29928                 this.update.defer(10, this, [date]);
29929             }
29930         }
29931         
29932         
29933     }
29934 });        /*
29935  * Based on:
29936  * Ext JS Library 1.1.1
29937  * Copyright(c) 2006-2007, Ext JS, LLC.
29938  *
29939  * Originally Released Under LGPL - original licence link has changed is not relivant.
29940  *
29941  * Fork - LGPL
29942  * <script type="text/javascript">
29943  */
29944 /**
29945  * @class Roo.TabPanel
29946  * @extends Roo.util.Observable
29947  * A lightweight tab container.
29948  * <br><br>
29949  * Usage:
29950  * <pre><code>
29951 // basic tabs 1, built from existing content
29952 var tabs = new Roo.TabPanel("tabs1");
29953 tabs.addTab("script", "View Script");
29954 tabs.addTab("markup", "View Markup");
29955 tabs.activate("script");
29956
29957 // more advanced tabs, built from javascript
29958 var jtabs = new Roo.TabPanel("jtabs");
29959 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
29960
29961 // set up the UpdateManager
29962 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
29963 var updater = tab2.getUpdateManager();
29964 updater.setDefaultUrl("ajax1.htm");
29965 tab2.on('activate', updater.refresh, updater, true);
29966
29967 // Use setUrl for Ajax loading
29968 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
29969 tab3.setUrl("ajax2.htm", null, true);
29970
29971 // Disabled tab
29972 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
29973 tab4.disable();
29974
29975 jtabs.activate("jtabs-1");
29976  * </code></pre>
29977  * @constructor
29978  * Create a new TabPanel.
29979  * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
29980  * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
29981  */
29982 Roo.TabPanel = function(container, config){
29983     /**
29984     * The container element for this TabPanel.
29985     * @type Roo.Element
29986     */
29987     this.el = Roo.get(container, true);
29988     if(config){
29989         if(typeof config == "boolean"){
29990             this.tabPosition = config ? "bottom" : "top";
29991         }else{
29992             Roo.apply(this, config);
29993         }
29994     }
29995     if(this.tabPosition == "bottom"){
29996         this.bodyEl = Roo.get(this.createBody(this.el.dom));
29997         this.el.addClass("x-tabs-bottom");
29998     }
29999     this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
30000     this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
30001     this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
30002     if(Roo.isIE){
30003         Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
30004     }
30005     if(this.tabPosition != "bottom"){
30006         /** The body element that contains {@link Roo.TabPanelItem} bodies. +
30007          * @type Roo.Element
30008          */
30009         this.bodyEl = Roo.get(this.createBody(this.el.dom));
30010         this.el.addClass("x-tabs-top");
30011     }
30012     this.items = [];
30013
30014     this.bodyEl.setStyle("position", "relative");
30015
30016     this.active = null;
30017     this.activateDelegate = this.activate.createDelegate(this);
30018
30019     this.addEvents({
30020         /**
30021          * @event tabchange
30022          * Fires when the active tab changes
30023          * @param {Roo.TabPanel} this
30024          * @param {Roo.TabPanelItem} activePanel The new active tab
30025          */
30026         "tabchange": true,
30027         /**
30028          * @event beforetabchange
30029          * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
30030          * @param {Roo.TabPanel} this
30031          * @param {Object} e Set cancel to true on this object to cancel the tab change
30032          * @param {Roo.TabPanelItem} tab The tab being changed to
30033          */
30034         "beforetabchange" : true
30035     });
30036
30037     Roo.EventManager.onWindowResize(this.onResize, this);
30038     this.cpad = this.el.getPadding("lr");
30039     this.hiddenCount = 0;
30040
30041
30042     // toolbar on the tabbar support...
30043     if (this.toolbar) {
30044         var tcfg = this.toolbar;
30045         tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');  
30046         this.toolbar = new Roo.Toolbar(tcfg);
30047         if (Roo.isSafari) {
30048             var tbl = tcfg.container.child('table', true);
30049             tbl.setAttribute('width', '100%');
30050         }
30051         
30052     }
30053    
30054
30055
30056     Roo.TabPanel.superclass.constructor.call(this);
30057 };
30058
30059 Roo.extend(Roo.TabPanel, Roo.util.Observable, {
30060     /*
30061      *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
30062      */
30063     tabPosition : "top",
30064     /*
30065      *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
30066      */
30067     currentTabWidth : 0,
30068     /*
30069      *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
30070      */
30071     minTabWidth : 40,
30072     /*
30073      *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
30074      */
30075     maxTabWidth : 250,
30076     /*
30077      *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
30078      */
30079     preferredTabWidth : 175,
30080     /*
30081      *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
30082      */
30083     resizeTabs : false,
30084     /*
30085      *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
30086      */
30087     monitorResize : true,
30088     /*
30089      *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar. 
30090      */
30091     toolbar : false,
30092
30093     /**
30094      * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
30095      * @param {String} id The id of the div to use <b>or create</b>
30096      * @param {String} text The text for the tab
30097      * @param {String} content (optional) Content to put in the TabPanelItem body
30098      * @param {Boolean} closable (optional) True to create a close icon on the tab
30099      * @return {Roo.TabPanelItem} The created TabPanelItem
30100      */
30101     addTab : function(id, text, content, closable){
30102         var item = new Roo.TabPanelItem(this, id, text, closable);
30103         this.addTabItem(item);
30104         if(content){
30105             item.setContent(content);
30106         }
30107         return item;
30108     },
30109
30110     /**
30111      * Returns the {@link Roo.TabPanelItem} with the specified id/index
30112      * @param {String/Number} id The id or index of the TabPanelItem to fetch.
30113      * @return {Roo.TabPanelItem}
30114      */
30115     getTab : function(id){
30116         return this.items[id];
30117     },
30118
30119     /**
30120      * Hides the {@link Roo.TabPanelItem} with the specified id/index
30121      * @param {String/Number} id The id or index of the TabPanelItem to hide.
30122      */
30123     hideTab : function(id){
30124         var t = this.items[id];
30125         if(!t.isHidden()){
30126            t.setHidden(true);
30127            this.hiddenCount++;
30128            this.autoSizeTabs();
30129         }
30130     },
30131
30132     /**
30133      * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
30134      * @param {String/Number} id The id or index of the TabPanelItem to unhide.
30135      */
30136     unhideTab : function(id){
30137         var t = this.items[id];
30138         if(t.isHidden()){
30139            t.setHidden(false);
30140            this.hiddenCount--;
30141            this.autoSizeTabs();
30142         }
30143     },
30144
30145     /**
30146      * Adds an existing {@link Roo.TabPanelItem}.
30147      * @param {Roo.TabPanelItem} item The TabPanelItem to add
30148      */
30149     addTabItem : function(item){
30150         this.items[item.id] = item;
30151         this.items.push(item);
30152         if(this.resizeTabs){
30153            item.setWidth(this.currentTabWidth || this.preferredTabWidth);
30154            this.autoSizeTabs();
30155         }else{
30156             item.autoSize();
30157         }
30158     },
30159
30160     /**
30161      * Removes a {@link Roo.TabPanelItem}.
30162      * @param {String/Number} id The id or index of the TabPanelItem to remove.
30163      */
30164     removeTab : function(id){
30165         var items = this.items;
30166         var tab = items[id];
30167         if(!tab) { return; }
30168         var index = items.indexOf(tab);
30169         if(this.active == tab && items.length > 1){
30170             var newTab = this.getNextAvailable(index);
30171             if(newTab) {
30172                 newTab.activate();
30173             }
30174         }
30175         this.stripEl.dom.removeChild(tab.pnode.dom);
30176         if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
30177             this.bodyEl.dom.removeChild(tab.bodyEl.dom);
30178         }
30179         items.splice(index, 1);
30180         delete this.items[tab.id];
30181         tab.fireEvent("close", tab);
30182         tab.purgeListeners();
30183         this.autoSizeTabs();
30184     },
30185
30186     getNextAvailable : function(start){
30187         var items = this.items;
30188         var index = start;
30189         // look for a next tab that will slide over to
30190         // replace the one being removed
30191         while(index < items.length){
30192             var item = items[++index];
30193             if(item && !item.isHidden()){
30194                 return item;
30195             }
30196         }
30197         // if one isn't found select the previous tab (on the left)
30198         index = start;
30199         while(index >= 0){
30200             var item = items[--index];
30201             if(item && !item.isHidden()){
30202                 return item;
30203             }
30204         }
30205         return null;
30206     },
30207
30208     /**
30209      * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
30210      * @param {String/Number} id The id or index of the TabPanelItem to disable.
30211      */
30212     disableTab : function(id){
30213         var tab = this.items[id];
30214         if(tab && this.active != tab){
30215             tab.disable();
30216         }
30217     },
30218
30219     /**
30220      * Enables a {@link Roo.TabPanelItem} that is disabled.
30221      * @param {String/Number} id The id or index of the TabPanelItem to enable.
30222      */
30223     enableTab : function(id){
30224         var tab = this.items[id];
30225         tab.enable();
30226     },
30227
30228     /**
30229      * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
30230      * @param {String/Number} id The id or index of the TabPanelItem to activate.
30231      * @return {Roo.TabPanelItem} The TabPanelItem.
30232      */
30233     activate : function(id){
30234         var tab = this.items[id];
30235         if(!tab){
30236             return null;
30237         }
30238         if(tab == this.active || tab.disabled){
30239             return tab;
30240         }
30241         var e = {};
30242         this.fireEvent("beforetabchange", this, e, tab);
30243         if(e.cancel !== true && !tab.disabled){
30244             if(this.active){
30245                 this.active.hide();
30246             }
30247             this.active = this.items[id];
30248             this.active.show();
30249             this.fireEvent("tabchange", this, this.active);
30250         }
30251         return tab;
30252     },
30253
30254     /**
30255      * Gets the active {@link Roo.TabPanelItem}.
30256      * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
30257      */
30258     getActiveTab : function(){
30259         return this.active;
30260     },
30261
30262     /**
30263      * Updates the tab body element to fit the height of the container element
30264      * for overflow scrolling
30265      * @param {Number} targetHeight (optional) Override the starting height from the elements height
30266      */
30267     syncHeight : function(targetHeight){
30268         var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
30269         var bm = this.bodyEl.getMargins();
30270         var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
30271         this.bodyEl.setHeight(newHeight);
30272         return newHeight;
30273     },
30274
30275     onResize : function(){
30276         if(this.monitorResize){
30277             this.autoSizeTabs();
30278         }
30279     },
30280
30281     /**
30282      * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
30283      */
30284     beginUpdate : function(){
30285         this.updating = true;
30286     },
30287
30288     /**
30289      * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
30290      */
30291     endUpdate : function(){
30292         this.updating = false;
30293         this.autoSizeTabs();
30294     },
30295
30296     /**
30297      * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
30298      */
30299     autoSizeTabs : function(){
30300         var count = this.items.length;
30301         var vcount = count - this.hiddenCount;
30302         if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
30303             return;
30304         }
30305         var w = Math.max(this.el.getWidth() - this.cpad, 10);
30306         var availWidth = Math.floor(w / vcount);
30307         var b = this.stripBody;
30308         if(b.getWidth() > w){
30309             var tabs = this.items;
30310             this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
30311             if(availWidth < this.minTabWidth){
30312                 /*if(!this.sleft){    // incomplete scrolling code
30313                     this.createScrollButtons();
30314                 }
30315                 this.showScroll();
30316                 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
30317             }
30318         }else{
30319             if(this.currentTabWidth < this.preferredTabWidth){
30320                 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
30321             }
30322         }
30323     },
30324
30325     /**
30326      * Returns the number of tabs in this TabPanel.
30327      * @return {Number}
30328      */
30329      getCount : function(){
30330          return this.items.length;
30331      },
30332
30333     /**
30334      * Resizes all the tabs to the passed width
30335      * @param {Number} The new width
30336      */
30337     setTabWidth : function(width){
30338         this.currentTabWidth = width;
30339         for(var i = 0, len = this.items.length; i < len; i++) {
30340                 if(!this.items[i].isHidden()) {
30341                 this.items[i].setWidth(width);
30342             }
30343         }
30344     },
30345
30346     /**
30347      * Destroys this TabPanel
30348      * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
30349      */
30350     destroy : function(removeEl){
30351         Roo.EventManager.removeResizeListener(this.onResize, this);
30352         for(var i = 0, len = this.items.length; i < len; i++){
30353             this.items[i].purgeListeners();
30354         }
30355         if(removeEl === true){
30356             this.el.update("");
30357             this.el.remove();
30358         }
30359     }
30360 });
30361
30362 /**
30363  * @class Roo.TabPanelItem
30364  * @extends Roo.util.Observable
30365  * Represents an individual item (tab plus body) in a TabPanel.
30366  * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
30367  * @param {String} id The id of this TabPanelItem
30368  * @param {String} text The text for the tab of this TabPanelItem
30369  * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
30370  */
30371 Roo.TabPanelItem = function(tabPanel, id, text, closable){
30372     /**
30373      * The {@link Roo.TabPanel} this TabPanelItem belongs to
30374      * @type Roo.TabPanel
30375      */
30376     this.tabPanel = tabPanel;
30377     /**
30378      * The id for this TabPanelItem
30379      * @type String
30380      */
30381     this.id = id;
30382     /** @private */
30383     this.disabled = false;
30384     /** @private */
30385     this.text = text;
30386     /** @private */
30387     this.loaded = false;
30388     this.closable = closable;
30389
30390     /**
30391      * The body element for this TabPanelItem.
30392      * @type Roo.Element
30393      */
30394     this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
30395     this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
30396     this.bodyEl.setStyle("display", "block");
30397     this.bodyEl.setStyle("zoom", "1");
30398     this.hideAction();
30399
30400     var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
30401     /** @private */
30402     this.el = Roo.get(els.el, true);
30403     this.inner = Roo.get(els.inner, true);
30404     this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
30405     this.pnode = Roo.get(els.el.parentNode, true);
30406     this.el.on("mousedown", this.onTabMouseDown, this);
30407     this.el.on("click", this.onTabClick, this);
30408     /** @private */
30409     if(closable){
30410         var c = Roo.get(els.close, true);
30411         c.dom.title = this.closeText;
30412         c.addClassOnOver("close-over");
30413         c.on("click", this.closeClick, this);
30414      }
30415
30416     this.addEvents({
30417          /**
30418          * @event activate
30419          * Fires when this tab becomes the active tab.
30420          * @param {Roo.TabPanel} tabPanel The parent TabPanel
30421          * @param {Roo.TabPanelItem} this
30422          */
30423         "activate": true,
30424         /**
30425          * @event beforeclose
30426          * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
30427          * @param {Roo.TabPanelItem} this
30428          * @param {Object} e Set cancel to true on this object to cancel the close.
30429          */
30430         "beforeclose": true,
30431         /**
30432          * @event close
30433          * Fires when this tab is closed.
30434          * @param {Roo.TabPanelItem} this
30435          */
30436          "close": true,
30437         /**
30438          * @event deactivate
30439          * Fires when this tab is no longer the active tab.
30440          * @param {Roo.TabPanel} tabPanel The parent TabPanel
30441          * @param {Roo.TabPanelItem} this
30442          */
30443          "deactivate" : true
30444     });
30445     this.hidden = false;
30446
30447     Roo.TabPanelItem.superclass.constructor.call(this);
30448 };
30449
30450 Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
30451     purgeListeners : function(){
30452        Roo.util.Observable.prototype.purgeListeners.call(this);
30453        this.el.removeAllListeners();
30454     },
30455     /**
30456      * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
30457      */
30458     show : function(){
30459         this.pnode.addClass("on");
30460         this.showAction();
30461         if(Roo.isOpera){
30462             this.tabPanel.stripWrap.repaint();
30463         }
30464         this.fireEvent("activate", this.tabPanel, this);
30465     },
30466
30467     /**
30468      * Returns true if this tab is the active tab.
30469      * @return {Boolean}
30470      */
30471     isActive : function(){
30472         return this.tabPanel.getActiveTab() == this;
30473     },
30474
30475     /**
30476      * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
30477      */
30478     hide : function(){
30479         this.pnode.removeClass("on");
30480         this.hideAction();
30481         this.fireEvent("deactivate", this.tabPanel, this);
30482     },
30483
30484     hideAction : function(){
30485         this.bodyEl.hide();
30486         this.bodyEl.setStyle("position", "absolute");
30487         this.bodyEl.setLeft("-20000px");
30488         this.bodyEl.setTop("-20000px");
30489     },
30490
30491     showAction : function(){
30492         this.bodyEl.setStyle("position", "relative");
30493         this.bodyEl.setTop("");
30494         this.bodyEl.setLeft("");
30495         this.bodyEl.show();
30496     },
30497
30498     /**
30499      * Set the tooltip for the tab.
30500      * @param {String} tooltip The tab's tooltip
30501      */
30502     setTooltip : function(text){
30503         if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
30504             this.textEl.dom.qtip = text;
30505             this.textEl.dom.removeAttribute('title');
30506         }else{
30507             this.textEl.dom.title = text;
30508         }
30509     },
30510
30511     onTabClick : function(e){
30512         e.preventDefault();
30513         this.tabPanel.activate(this.id);
30514     },
30515
30516     onTabMouseDown : function(e){
30517         e.preventDefault();
30518         this.tabPanel.activate(this.id);
30519     },
30520
30521     getWidth : function(){
30522         return this.inner.getWidth();
30523     },
30524
30525     setWidth : function(width){
30526         var iwidth = width - this.pnode.getPadding("lr");
30527         this.inner.setWidth(iwidth);
30528         this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
30529         this.pnode.setWidth(width);
30530     },
30531
30532     /**
30533      * Show or hide the tab
30534      * @param {Boolean} hidden True to hide or false to show.
30535      */
30536     setHidden : function(hidden){
30537         this.hidden = hidden;
30538         this.pnode.setStyle("display", hidden ? "none" : "");
30539     },
30540
30541     /**
30542      * Returns true if this tab is "hidden"
30543      * @return {Boolean}
30544      */
30545     isHidden : function(){
30546         return this.hidden;
30547     },
30548
30549     /**
30550      * Returns the text for this tab
30551      * @return {String}
30552      */
30553     getText : function(){
30554         return this.text;
30555     },
30556
30557     autoSize : function(){
30558         //this.el.beginMeasure();
30559         this.textEl.setWidth(1);
30560         /*
30561          *  #2804 [new] Tabs in Roojs
30562          *  increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
30563          */
30564         this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
30565         //this.el.endMeasure();
30566     },
30567
30568     /**
30569      * Sets the text for the tab (Note: this also sets the tooltip text)
30570      * @param {String} text The tab's text and tooltip
30571      */
30572     setText : function(text){
30573         this.text = text;
30574         this.textEl.update(text);
30575         this.setTooltip(text);
30576         if(!this.tabPanel.resizeTabs){
30577             this.autoSize();
30578         }
30579     },
30580     /**
30581      * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
30582      */
30583     activate : function(){
30584         this.tabPanel.activate(this.id);
30585     },
30586
30587     /**
30588      * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
30589      */
30590     disable : function(){
30591         if(this.tabPanel.active != this){
30592             this.disabled = true;
30593             this.pnode.addClass("disabled");
30594         }
30595     },
30596
30597     /**
30598      * Enables this TabPanelItem if it was previously disabled.
30599      */
30600     enable : function(){
30601         this.disabled = false;
30602         this.pnode.removeClass("disabled");
30603     },
30604
30605     /**
30606      * Sets the content for this TabPanelItem.
30607      * @param {String} content The content
30608      * @param {Boolean} loadScripts true to look for and load scripts
30609      */
30610     setContent : function(content, loadScripts){
30611         this.bodyEl.update(content, loadScripts);
30612     },
30613
30614     /**
30615      * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
30616      * @return {Roo.UpdateManager} The UpdateManager
30617      */
30618     getUpdateManager : function(){
30619         return this.bodyEl.getUpdateManager();
30620     },
30621
30622     /**
30623      * Set a URL to be used to load the content for this TabPanelItem.
30624      * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
30625      * @param {String/Object} params (optional) The string params for the update call or an object of the params. See {@link Roo.UpdateManager#update} for more details. (Defaults to null)
30626      * @param {Boolean} loadOnce (optional) Whether to only load the content once. If this is false it makes the Ajax call every time this TabPanelItem is activated. (Defaults to false)
30627      * @return {Roo.UpdateManager} The UpdateManager
30628      */
30629     setUrl : function(url, params, loadOnce){
30630         if(this.refreshDelegate){
30631             this.un('activate', this.refreshDelegate);
30632         }
30633         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
30634         this.on("activate", this.refreshDelegate);
30635         return this.bodyEl.getUpdateManager();
30636     },
30637
30638     /** @private */
30639     _handleRefresh : function(url, params, loadOnce){
30640         if(!loadOnce || !this.loaded){
30641             var updater = this.bodyEl.getUpdateManager();
30642             updater.update(url, params, this._setLoaded.createDelegate(this));
30643         }
30644     },
30645
30646     /**
30647      *   Forces a content refresh from the URL specified in the {@link #setUrl} method.
30648      *   Will fail silently if the setUrl method has not been called.
30649      *   This does not activate the panel, just updates its content.
30650      */
30651     refresh : function(){
30652         if(this.refreshDelegate){
30653            this.loaded = false;
30654            this.refreshDelegate();
30655         }
30656     },
30657
30658     /** @private */
30659     _setLoaded : function(){
30660         this.loaded = true;
30661     },
30662
30663     /** @private */
30664     closeClick : function(e){
30665         var o = {};
30666         e.stopEvent();
30667         this.fireEvent("beforeclose", this, o);
30668         if(o.cancel !== true){
30669             this.tabPanel.removeTab(this.id);
30670         }
30671     },
30672     /**
30673      * The text displayed in the tooltip for the close icon.
30674      * @type String
30675      */
30676     closeText : "Close this tab"
30677 });
30678
30679 /** @private */
30680 Roo.TabPanel.prototype.createStrip = function(container){
30681     var strip = document.createElement("div");
30682     strip.className = "x-tabs-wrap";
30683     container.appendChild(strip);
30684     return strip;
30685 };
30686 /** @private */
30687 Roo.TabPanel.prototype.createStripList = function(strip){
30688     // div wrapper for retard IE
30689     // returns the "tr" element.
30690     strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
30691         '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
30692         '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
30693     return strip.firstChild.firstChild.firstChild.firstChild;
30694 };
30695 /** @private */
30696 Roo.TabPanel.prototype.createBody = function(container){
30697     var body = document.createElement("div");
30698     Roo.id(body, "tab-body");
30699     Roo.fly(body).addClass("x-tabs-body");
30700     container.appendChild(body);
30701     return body;
30702 };
30703 /** @private */
30704 Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
30705     var body = Roo.getDom(id);
30706     if(!body){
30707         body = document.createElement("div");
30708         body.id = id;
30709     }
30710     Roo.fly(body).addClass("x-tabs-item-body");
30711     bodyEl.insertBefore(body, bodyEl.firstChild);
30712     return body;
30713 };
30714 /** @private */
30715 Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
30716     var td = document.createElement("td");
30717     stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
30718     //stripEl.appendChild(td);
30719     if(closable){
30720         td.className = "x-tabs-closable";
30721         if(!this.closeTpl){
30722             this.closeTpl = new Roo.Template(
30723                '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
30724                '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
30725                '<div unselectable="on" class="close-icon">&#160;</div></em></span></a>'
30726             );
30727         }
30728         var el = this.closeTpl.overwrite(td, {"text": text});
30729         var close = el.getElementsByTagName("div")[0];
30730         var inner = el.getElementsByTagName("em")[0];
30731         return {"el": el, "close": close, "inner": inner};
30732     } else {
30733         if(!this.tabTpl){
30734             this.tabTpl = new Roo.Template(
30735                '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
30736                '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
30737             );
30738         }
30739         var el = this.tabTpl.overwrite(td, {"text": text});
30740         var inner = el.getElementsByTagName("em")[0];
30741         return {"el": el, "inner": inner};
30742     }
30743 };/*
30744  * Based on:
30745  * Ext JS Library 1.1.1
30746  * Copyright(c) 2006-2007, Ext JS, LLC.
30747  *
30748  * Originally Released Under LGPL - original licence link has changed is not relivant.
30749  *
30750  * Fork - LGPL
30751  * <script type="text/javascript">
30752  */
30753
30754 /**
30755  * @class Roo.Button
30756  * @extends Roo.util.Observable
30757  * Simple Button class
30758  * @cfg {String} text The button text
30759  * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
30760  * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
30761  * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
30762  * @cfg {Object} scope The scope of the handler
30763  * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
30764  * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
30765  * @cfg {Boolean} hidden True to start hidden (defaults to false)
30766  * @cfg {Boolean} disabled True to start disabled (defaults to false)
30767  * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
30768  * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
30769    applies if enableToggle = true)
30770  * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
30771  * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
30772   an {@link Roo.util.ClickRepeater} config object (defaults to false).
30773  * @constructor
30774  * Create a new button
30775  * @param {Object} config The config object
30776  */
30777 Roo.Button = function(renderTo, config)
30778 {
30779     if (!config) {
30780         config = renderTo;
30781         renderTo = config.renderTo || false;
30782     }
30783     
30784     Roo.apply(this, config);
30785     this.addEvents({
30786         /**
30787              * @event click
30788              * Fires when this button is clicked
30789              * @param {Button} this
30790              * @param {EventObject} e The click event
30791              */
30792             "click" : true,
30793         /**
30794              * @event toggle
30795              * Fires when the "pressed" state of this button changes (only if enableToggle = true)
30796              * @param {Button} this
30797              * @param {Boolean} pressed
30798              */
30799             "toggle" : true,
30800         /**
30801              * @event mouseover
30802              * Fires when the mouse hovers over the button
30803              * @param {Button} this
30804              * @param {Event} e The event object
30805              */
30806         'mouseover' : true,
30807         /**
30808              * @event mouseout
30809              * Fires when the mouse exits the button
30810              * @param {Button} this
30811              * @param {Event} e The event object
30812              */
30813         'mouseout': true,
30814          /**
30815              * @event render
30816              * Fires when the button is rendered
30817              * @param {Button} this
30818              */
30819         'render': true
30820     });
30821     if(this.menu){
30822         this.menu = Roo.menu.MenuMgr.get(this.menu);
30823     }
30824     // register listeners first!!  - so render can be captured..
30825     Roo.util.Observable.call(this);
30826     if(renderTo){
30827         this.render(renderTo);
30828     }
30829     
30830   
30831 };
30832
30833 Roo.extend(Roo.Button, Roo.util.Observable, {
30834     /**
30835      * 
30836      */
30837     
30838     /**
30839      * Read-only. True if this button is hidden
30840      * @type Boolean
30841      */
30842     hidden : false,
30843     /**
30844      * Read-only. True if this button is disabled
30845      * @type Boolean
30846      */
30847     disabled : false,
30848     /**
30849      * Read-only. True if this button is pressed (only if enableToggle = true)
30850      * @type Boolean
30851      */
30852     pressed : false,
30853
30854     /**
30855      * @cfg {Number} tabIndex 
30856      * The DOM tabIndex for this button (defaults to undefined)
30857      */
30858     tabIndex : undefined,
30859
30860     /**
30861      * @cfg {Boolean} enableToggle
30862      * True to enable pressed/not pressed toggling (defaults to false)
30863      */
30864     enableToggle: false,
30865     /**
30866      * @cfg {Roo.menu.Menu} menu
30867      * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
30868      */
30869     menu : undefined,
30870     /**
30871      * @cfg {String} menuAlign
30872      * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
30873      */
30874     menuAlign : "tl-bl?",
30875
30876     /**
30877      * @cfg {String} iconCls
30878      * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
30879      */
30880     iconCls : undefined,
30881     /**
30882      * @cfg {String} type
30883      * The button's type, corresponding to the DOM input element type attribute.  Either "submit," "reset" or "button" (default).
30884      */
30885     type : 'button',
30886
30887     // private
30888     menuClassTarget: 'tr',
30889
30890     /**
30891      * @cfg {String} clickEvent
30892      * The type of event to map to the button's event handler (defaults to 'click')
30893      */
30894     clickEvent : 'click',
30895
30896     /**
30897      * @cfg {Boolean} handleMouseEvents
30898      * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
30899      */
30900     handleMouseEvents : true,
30901
30902     /**
30903      * @cfg {String} tooltipType
30904      * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
30905      */
30906     tooltipType : 'qtip',
30907
30908     /**
30909      * @cfg {String} cls
30910      * A CSS class to apply to the button's main element.
30911      */
30912     
30913     /**
30914      * @cfg {Roo.Template} template (Optional)
30915      * An {@link Roo.Template} with which to create the Button's main element. This Template must
30916      * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
30917      * require code modifications if required elements (e.g. a button) aren't present.
30918      */
30919
30920     // private
30921     render : function(renderTo){
30922         var btn;
30923         if(this.hideParent){
30924             this.parentEl = Roo.get(renderTo);
30925         }
30926         if(!this.dhconfig){
30927             if(!this.template){
30928                 if(!Roo.Button.buttonTemplate){
30929                     // hideous table template
30930                     Roo.Button.buttonTemplate = new Roo.Template(
30931                         '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
30932                         '<td class="x-btn-left"><i>&#160;</i></td><td class="x-btn-center"><em unselectable="on"><button class="x-btn-text" type="{1}">{0}</button></em></td><td class="x-btn-right"><i>&#160;</i></td>',
30933                         "</tr></tbody></table>");
30934                 }
30935                 this.template = Roo.Button.buttonTemplate;
30936             }
30937             btn = this.template.append(renderTo, [this.text || '&#160;', this.type], true);
30938             var btnEl = btn.child("button:first");
30939             btnEl.on('focus', this.onFocus, this);
30940             btnEl.on('blur', this.onBlur, this);
30941             if(this.cls){
30942                 btn.addClass(this.cls);
30943             }
30944             if(this.icon){
30945                 btnEl.setStyle('background-image', 'url(' +this.icon +')');
30946             }
30947             if(this.iconCls){
30948                 btnEl.addClass(this.iconCls);
30949                 if(!this.cls){
30950                     btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
30951                 }
30952             }
30953             if(this.tabIndex !== undefined){
30954                 btnEl.dom.tabIndex = this.tabIndex;
30955             }
30956             if(this.tooltip){
30957                 if(typeof this.tooltip == 'object'){
30958                     Roo.QuickTips.tips(Roo.apply({
30959                           target: btnEl.id
30960                     }, this.tooltip));
30961                 } else {
30962                     btnEl.dom[this.tooltipType] = this.tooltip;
30963                 }
30964             }
30965         }else{
30966             btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
30967         }
30968         this.el = btn;
30969         if(this.id){
30970             this.el.dom.id = this.el.id = this.id;
30971         }
30972         if(this.menu){
30973             this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
30974             this.menu.on("show", this.onMenuShow, this);
30975             this.menu.on("hide", this.onMenuHide, this);
30976         }
30977         btn.addClass("x-btn");
30978         if(Roo.isIE && !Roo.isIE7){
30979             this.autoWidth.defer(1, this);
30980         }else{
30981             this.autoWidth();
30982         }
30983         if(this.handleMouseEvents){
30984             btn.on("mouseover", this.onMouseOver, this);
30985             btn.on("mouseout", this.onMouseOut, this);
30986             btn.on("mousedown", this.onMouseDown, this);
30987         }
30988         btn.on(this.clickEvent, this.onClick, this);
30989         //btn.on("mouseup", this.onMouseUp, this);
30990         if(this.hidden){
30991             this.hide();
30992         }
30993         if(this.disabled){
30994             this.disable();
30995         }
30996         Roo.ButtonToggleMgr.register(this);
30997         if(this.pressed){
30998             this.el.addClass("x-btn-pressed");
30999         }
31000         if(this.repeat){
31001             var repeater = new Roo.util.ClickRepeater(btn,
31002                 typeof this.repeat == "object" ? this.repeat : {}
31003             );
31004             repeater.on("click", this.onClick,  this);
31005         }
31006         
31007         this.fireEvent('render', this);
31008         
31009     },
31010     /**
31011      * Returns the button's underlying element
31012      * @return {Roo.Element} The element
31013      */
31014     getEl : function(){
31015         return this.el;  
31016     },
31017     
31018     /**
31019      * Destroys this Button and removes any listeners.
31020      */
31021     destroy : function(){
31022         Roo.ButtonToggleMgr.unregister(this);
31023         this.el.removeAllListeners();
31024         this.purgeListeners();
31025         this.el.remove();
31026     },
31027
31028     // private
31029     autoWidth : function(){
31030         if(this.el){
31031             this.el.setWidth("auto");
31032             if(Roo.isIE7 && Roo.isStrict){
31033                 var ib = this.el.child('button');
31034                 if(ib && ib.getWidth() > 20){
31035                     ib.clip();
31036                     ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
31037                 }
31038             }
31039             if(this.minWidth){
31040                 if(this.hidden){
31041                     this.el.beginMeasure();
31042                 }
31043                 if(this.el.getWidth() < this.minWidth){
31044                     this.el.setWidth(this.minWidth);
31045                 }
31046                 if(this.hidden){
31047                     this.el.endMeasure();
31048                 }
31049             }
31050         }
31051     },
31052
31053     /**
31054      * Assigns this button's click handler
31055      * @param {Function} handler The function to call when the button is clicked
31056      * @param {Object} scope (optional) Scope for the function passed in
31057      */
31058     setHandler : function(handler, scope){
31059         this.handler = handler;
31060         this.scope = scope;  
31061     },
31062     
31063     /**
31064      * Sets this button's text
31065      * @param {String} text The button text
31066      */
31067     setText : function(text){
31068         this.text = text;
31069         if(this.el){
31070             this.el.child("td.x-btn-center button.x-btn-text").update(text);
31071         }
31072         this.autoWidth();
31073     },
31074     
31075     /**
31076      * Gets the text for this button
31077      * @return {String} The button text
31078      */
31079     getText : function(){
31080         return this.text;  
31081     },
31082     
31083     /**
31084      * Show this button
31085      */
31086     show: function(){
31087         this.hidden = false;
31088         if(this.el){
31089             this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
31090         }
31091     },
31092     
31093     /**
31094      * Hide this button
31095      */
31096     hide: function(){
31097         this.hidden = true;
31098         if(this.el){
31099             this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
31100         }
31101     },
31102     
31103     /**
31104      * Convenience function for boolean show/hide
31105      * @param {Boolean} visible True to show, false to hide
31106      */
31107     setVisible: function(visible){
31108         if(visible) {
31109             this.show();
31110         }else{
31111             this.hide();
31112         }
31113     },
31114     
31115     /**
31116      * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
31117      * @param {Boolean} state (optional) Force a particular state
31118      */
31119     toggle : function(state){
31120         state = state === undefined ? !this.pressed : state;
31121         if(state != this.pressed){
31122             if(state){
31123                 this.el.addClass("x-btn-pressed");
31124                 this.pressed = true;
31125                 this.fireEvent("toggle", this, true);
31126             }else{
31127                 this.el.removeClass("x-btn-pressed");
31128                 this.pressed = false;
31129                 this.fireEvent("toggle", this, false);
31130             }
31131             if(this.toggleHandler){
31132                 this.toggleHandler.call(this.scope || this, this, state);
31133             }
31134         }
31135     },
31136     
31137     /**
31138      * Focus the button
31139      */
31140     focus : function(){
31141         this.el.child('button:first').focus();
31142     },
31143     
31144     /**
31145      * Disable this button
31146      */
31147     disable : function(){
31148         if(this.el){
31149             this.el.addClass("x-btn-disabled");
31150         }
31151         this.disabled = true;
31152     },
31153     
31154     /**
31155      * Enable this button
31156      */
31157     enable : function(){
31158         if(this.el){
31159             this.el.removeClass("x-btn-disabled");
31160         }
31161         this.disabled = false;
31162     },
31163
31164     /**
31165      * Convenience function for boolean enable/disable
31166      * @param {Boolean} enabled True to enable, false to disable
31167      */
31168     setDisabled : function(v){
31169         this[v !== true ? "enable" : "disable"]();
31170     },
31171
31172     // private
31173     onClick : function(e)
31174     {
31175         if(e){
31176             e.preventDefault();
31177         }
31178         if(e.button != 0){
31179             return;
31180         }
31181         if(!this.disabled){
31182             if(this.enableToggle){
31183                 this.toggle();
31184             }
31185             if(this.menu && !this.menu.isVisible()){
31186                 this.menu.show(this.el, this.menuAlign);
31187             }
31188             this.fireEvent("click", this, e);
31189             if(this.handler){
31190                 this.el.removeClass("x-btn-over");
31191                 this.handler.call(this.scope || this, this, e);
31192             }
31193         }
31194     },
31195     // private
31196     onMouseOver : function(e){
31197         if(!this.disabled){
31198             this.el.addClass("x-btn-over");
31199             this.fireEvent('mouseover', this, e);
31200         }
31201     },
31202     // private
31203     onMouseOut : function(e){
31204         if(!e.within(this.el,  true)){
31205             this.el.removeClass("x-btn-over");
31206             this.fireEvent('mouseout', this, e);
31207         }
31208     },
31209     // private
31210     onFocus : function(e){
31211         if(!this.disabled){
31212             this.el.addClass("x-btn-focus");
31213         }
31214     },
31215     // private
31216     onBlur : function(e){
31217         this.el.removeClass("x-btn-focus");
31218     },
31219     // private
31220     onMouseDown : function(e){
31221         if(!this.disabled && e.button == 0){
31222             this.el.addClass("x-btn-click");
31223             Roo.get(document).on('mouseup', this.onMouseUp, this);
31224         }
31225     },
31226     // private
31227     onMouseUp : function(e){
31228         if(e.button == 0){
31229             this.el.removeClass("x-btn-click");
31230             Roo.get(document).un('mouseup', this.onMouseUp, this);
31231         }
31232     },
31233     // private
31234     onMenuShow : function(e){
31235         this.el.addClass("x-btn-menu-active");
31236     },
31237     // private
31238     onMenuHide : function(e){
31239         this.el.removeClass("x-btn-menu-active");
31240     }   
31241 });
31242
31243 // Private utility class used by Button
31244 Roo.ButtonToggleMgr = function(){
31245    var groups = {};
31246    
31247    function toggleGroup(btn, state){
31248        if(state){
31249            var g = groups[btn.toggleGroup];
31250            for(var i = 0, l = g.length; i < l; i++){
31251                if(g[i] != btn){
31252                    g[i].toggle(false);
31253                }
31254            }
31255        }
31256    }
31257    
31258    return {
31259        register : function(btn){
31260            if(!btn.toggleGroup){
31261                return;
31262            }
31263            var g = groups[btn.toggleGroup];
31264            if(!g){
31265                g = groups[btn.toggleGroup] = [];
31266            }
31267            g.push(btn);
31268            btn.on("toggle", toggleGroup);
31269        },
31270        
31271        unregister : function(btn){
31272            if(!btn.toggleGroup){
31273                return;
31274            }
31275            var g = groups[btn.toggleGroup];
31276            if(g){
31277                g.remove(btn);
31278                btn.un("toggle", toggleGroup);
31279            }
31280        }
31281    };
31282 }();/*
31283  * Based on:
31284  * Ext JS Library 1.1.1
31285  * Copyright(c) 2006-2007, Ext JS, LLC.
31286  *
31287  * Originally Released Under LGPL - original licence link has changed is not relivant.
31288  *
31289  * Fork - LGPL
31290  * <script type="text/javascript">
31291  */
31292  
31293 /**
31294  * @class Roo.SplitButton
31295  * @extends Roo.Button
31296  * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
31297  * click event of the button.  Typically this would be used to display a dropdown menu that provides additional
31298  * options to the primary button action, but any custom handler can provide the arrowclick implementation.
31299  * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
31300  * @cfg {String} arrowTooltip The title attribute of the arrow
31301  * @constructor
31302  * Create a new menu button
31303  * @param {String/HTMLElement/Element} renderTo The element to append the button to
31304  * @param {Object} config The config object
31305  */
31306 Roo.SplitButton = function(renderTo, config){
31307     Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
31308     /**
31309      * @event arrowclick
31310      * Fires when this button's arrow is clicked
31311      * @param {SplitButton} this
31312      * @param {EventObject} e The click event
31313      */
31314     this.addEvents({"arrowclick":true});
31315 };
31316
31317 Roo.extend(Roo.SplitButton, Roo.Button, {
31318     render : function(renderTo){
31319         // this is one sweet looking template!
31320         var tpl = new Roo.Template(
31321             '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
31322             '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
31323             '<tr><td class="x-btn-left"><i>&#160;</i></td><td class="x-btn-center"><button class="x-btn-text" type="{1}">{0}</button></td></tr>',
31324             "</tbody></table></td><td>",
31325             '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
31326             '<tr><td class="x-btn-center"><button class="x-btn-menu-arrow-el" type="button">&#160;</button></td><td class="x-btn-right"><i>&#160;</i></td></tr>',
31327             "</tbody></table></td></tr></table>"
31328         );
31329         var btn = tpl.append(renderTo, [this.text, this.type], true);
31330         var btnEl = btn.child("button");
31331         if(this.cls){
31332             btn.addClass(this.cls);
31333         }
31334         if(this.icon){
31335             btnEl.setStyle('background-image', 'url(' +this.icon +')');
31336         }
31337         if(this.iconCls){
31338             btnEl.addClass(this.iconCls);
31339             if(!this.cls){
31340                 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
31341             }
31342         }
31343         this.el = btn;
31344         if(this.handleMouseEvents){
31345             btn.on("mouseover", this.onMouseOver, this);
31346             btn.on("mouseout", this.onMouseOut, this);
31347             btn.on("mousedown", this.onMouseDown, this);
31348             btn.on("mouseup", this.onMouseUp, this);
31349         }
31350         btn.on(this.clickEvent, this.onClick, this);
31351         if(this.tooltip){
31352             if(typeof this.tooltip == 'object'){
31353                 Roo.QuickTips.tips(Roo.apply({
31354                       target: btnEl.id
31355                 }, this.tooltip));
31356             } else {
31357                 btnEl.dom[this.tooltipType] = this.tooltip;
31358             }
31359         }
31360         if(this.arrowTooltip){
31361             btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
31362         }
31363         if(this.hidden){
31364             this.hide();
31365         }
31366         if(this.disabled){
31367             this.disable();
31368         }
31369         if(this.pressed){
31370             this.el.addClass("x-btn-pressed");
31371         }
31372         if(Roo.isIE && !Roo.isIE7){
31373             this.autoWidth.defer(1, this);
31374         }else{
31375             this.autoWidth();
31376         }
31377         if(this.menu){
31378             this.menu.on("show", this.onMenuShow, this);
31379             this.menu.on("hide", this.onMenuHide, this);
31380         }
31381         this.fireEvent('render', this);
31382     },
31383
31384     // private
31385     autoWidth : function(){
31386         if(this.el){
31387             var tbl = this.el.child("table:first");
31388             var tbl2 = this.el.child("table:last");
31389             this.el.setWidth("auto");
31390             tbl.setWidth("auto");
31391             if(Roo.isIE7 && Roo.isStrict){
31392                 var ib = this.el.child('button:first');
31393                 if(ib && ib.getWidth() > 20){
31394                     ib.clip();
31395                     ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
31396                 }
31397             }
31398             if(this.minWidth){
31399                 if(this.hidden){
31400                     this.el.beginMeasure();
31401                 }
31402                 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
31403                     tbl.setWidth(this.minWidth-tbl2.getWidth());
31404                 }
31405                 if(this.hidden){
31406                     this.el.endMeasure();
31407                 }
31408             }
31409             this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
31410         } 
31411     },
31412     /**
31413      * Sets this button's click handler
31414      * @param {Function} handler The function to call when the button is clicked
31415      * @param {Object} scope (optional) Scope for the function passed above
31416      */
31417     setHandler : function(handler, scope){
31418         this.handler = handler;
31419         this.scope = scope;  
31420     },
31421     
31422     /**
31423      * Sets this button's arrow click handler
31424      * @param {Function} handler The function to call when the arrow is clicked
31425      * @param {Object} scope (optional) Scope for the function passed above
31426      */
31427     setArrowHandler : function(handler, scope){
31428         this.arrowHandler = handler;
31429         this.scope = scope;  
31430     },
31431     
31432     /**
31433      * Focus the button
31434      */
31435     focus : function(){
31436         if(this.el){
31437             this.el.child("button:first").focus();
31438         }
31439     },
31440
31441     // private
31442     onClick : function(e){
31443         e.preventDefault();
31444         if(!this.disabled){
31445             if(e.getTarget(".x-btn-menu-arrow-wrap")){
31446                 if(this.menu && !this.menu.isVisible()){
31447                     this.menu.show(this.el, this.menuAlign);
31448                 }
31449                 this.fireEvent("arrowclick", this, e);
31450                 if(this.arrowHandler){
31451                     this.arrowHandler.call(this.scope || this, this, e);
31452                 }
31453             }else{
31454                 this.fireEvent("click", this, e);
31455                 if(this.handler){
31456                     this.handler.call(this.scope || this, this, e);
31457                 }
31458             }
31459         }
31460     },
31461     // private
31462     onMouseDown : function(e){
31463         if(!this.disabled){
31464             Roo.fly(e.getTarget("table")).addClass("x-btn-click");
31465         }
31466     },
31467     // private
31468     onMouseUp : function(e){
31469         Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
31470     }   
31471 });
31472
31473
31474 // backwards compat
31475 Roo.MenuButton = Roo.SplitButton;/*
31476  * Based on:
31477  * Ext JS Library 1.1.1
31478  * Copyright(c) 2006-2007, Ext JS, LLC.
31479  *
31480  * Originally Released Under LGPL - original licence link has changed is not relivant.
31481  *
31482  * Fork - LGPL
31483  * <script type="text/javascript">
31484  */
31485
31486 /**
31487  * @class Roo.Toolbar
31488  * @children   Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field 
31489  * Basic Toolbar class.
31490  * @constructor
31491  * Creates a new Toolbar
31492  * @param {Object} container The config object
31493  */ 
31494 Roo.Toolbar = function(container, buttons, config)
31495 {
31496     /// old consturctor format still supported..
31497     if(container instanceof Array){ // omit the container for later rendering
31498         buttons = container;
31499         config = buttons;
31500         container = null;
31501     }
31502     if (typeof(container) == 'object' && container.xtype) {
31503         config = container;
31504         container = config.container;
31505         buttons = config.buttons || []; // not really - use items!!
31506     }
31507     var xitems = [];
31508     if (config && config.items) {
31509         xitems = config.items;
31510         delete config.items;
31511     }
31512     Roo.apply(this, config);
31513     this.buttons = buttons;
31514     
31515     if(container){
31516         this.render(container);
31517     }
31518     this.xitems = xitems;
31519     Roo.each(xitems, function(b) {
31520         this.add(b);
31521     }, this);
31522     
31523 };
31524
31525 Roo.Toolbar.prototype = {
31526     /**
31527      * @cfg {Array} items
31528      * array of button configs or elements to add (will be converted to a MixedCollection)
31529      */
31530     items: false,
31531     /**
31532      * @cfg {String/HTMLElement/Element} container
31533      * The id or element that will contain the toolbar
31534      */
31535     // private
31536     render : function(ct){
31537         this.el = Roo.get(ct);
31538         if(this.cls){
31539             this.el.addClass(this.cls);
31540         }
31541         // using a table allows for vertical alignment
31542         // 100% width is needed by Safari...
31543         this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
31544         this.tr = this.el.child("tr", true);
31545         var autoId = 0;
31546         this.items = new Roo.util.MixedCollection(false, function(o){
31547             return o.id || ("item" + (++autoId));
31548         });
31549         if(this.buttons){
31550             this.add.apply(this, this.buttons);
31551             delete this.buttons;
31552         }
31553     },
31554
31555     /**
31556      * Adds element(s) to the toolbar -- this function takes a variable number of 
31557      * arguments of mixed type and adds them to the toolbar.
31558      * @param {Mixed} arg1 The following types of arguments are all valid:<br />
31559      * <ul>
31560      * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
31561      * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
31562      * <li>Field: Any form field (equivalent to {@link #addField})</li>
31563      * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
31564      * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
31565      * Note that there are a few special strings that are treated differently as explained nRoo.</li>
31566      * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
31567      * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
31568      * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
31569      * </ul>
31570      * @param {Mixed} arg2
31571      * @param {Mixed} etc.
31572      */
31573     add : function(){
31574         var a = arguments, l = a.length;
31575         for(var i = 0; i < l; i++){
31576             this._add(a[i]);
31577         }
31578     },
31579     // private..
31580     _add : function(el) {
31581         
31582         if (el.xtype) {
31583             el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
31584         }
31585         
31586         if (el.applyTo){ // some kind of form field
31587             return this.addField(el);
31588         } 
31589         if (el.render){ // some kind of Toolbar.Item
31590             return this.addItem(el);
31591         }
31592         if (typeof el == "string"){ // string
31593             if(el == "separator" || el == "-"){
31594                 return this.addSeparator();
31595             }
31596             if (el == " "){
31597                 return this.addSpacer();
31598             }
31599             if(el == "->"){
31600                 return this.addFill();
31601             }
31602             return this.addText(el);
31603             
31604         }
31605         if(el.tagName){ // element
31606             return this.addElement(el);
31607         }
31608         if(typeof el == "object"){ // must be button config?
31609             return this.addButton(el);
31610         }
31611         // and now what?!?!
31612         return false;
31613         
31614     },
31615     
31616     /**
31617      * Add an Xtype element
31618      * @param {Object} xtype Xtype Object
31619      * @return {Object} created Object
31620      */
31621     addxtype : function(e){
31622         return this.add(e);  
31623     },
31624     
31625     /**
31626      * Returns the Element for this toolbar.
31627      * @return {Roo.Element}
31628      */
31629     getEl : function(){
31630         return this.el;  
31631     },
31632     
31633     /**
31634      * Adds a separator
31635      * @return {Roo.Toolbar.Item} The separator item
31636      */
31637     addSeparator : function(){
31638         return this.addItem(new Roo.Toolbar.Separator());
31639     },
31640
31641     /**
31642      * Adds a spacer element
31643      * @return {Roo.Toolbar.Spacer} The spacer item
31644      */
31645     addSpacer : function(){
31646         return this.addItem(new Roo.Toolbar.Spacer());
31647     },
31648
31649     /**
31650      * Adds a fill element that forces subsequent additions to the right side of the toolbar
31651      * @return {Roo.Toolbar.Fill} The fill item
31652      */
31653     addFill : function(){
31654         return this.addItem(new Roo.Toolbar.Fill());
31655     },
31656
31657     /**
31658      * Adds any standard HTML element to the toolbar
31659      * @param {String/HTMLElement/Element} el The element or id of the element to add
31660      * @return {Roo.Toolbar.Item} The element's item
31661      */
31662     addElement : function(el){
31663         return this.addItem(new Roo.Toolbar.Item(el));
31664     },
31665     /**
31666      * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
31667      * @type Roo.util.MixedCollection  
31668      */
31669     items : false,
31670      
31671     /**
31672      * Adds any Toolbar.Item or subclass
31673      * @param {Roo.Toolbar.Item} item
31674      * @return {Roo.Toolbar.Item} The item
31675      */
31676     addItem : function(item){
31677         var td = this.nextBlock();
31678         item.render(td);
31679         this.items.add(item);
31680         return item;
31681     },
31682     
31683     /**
31684      * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
31685      * @param {Object/Array} config A button config or array of configs
31686      * @return {Roo.Toolbar.Button/Array}
31687      */
31688     addButton : function(config){
31689         if(config instanceof Array){
31690             var buttons = [];
31691             for(var i = 0, len = config.length; i < len; i++) {
31692                 buttons.push(this.addButton(config[i]));
31693             }
31694             return buttons;
31695         }
31696         var b = config;
31697         if(!(config instanceof Roo.Toolbar.Button)){
31698             b = config.split ?
31699                 new Roo.Toolbar.SplitButton(config) :
31700                 new Roo.Toolbar.Button(config);
31701         }
31702         var td = this.nextBlock();
31703         b.render(td);
31704         this.items.add(b);
31705         return b;
31706     },
31707     
31708     /**
31709      * Adds text to the toolbar
31710      * @param {String} text The text to add
31711      * @return {Roo.Toolbar.Item} The element's item
31712      */
31713     addText : function(text){
31714         return this.addItem(new Roo.Toolbar.TextItem(text));
31715     },
31716     
31717     /**
31718      * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
31719      * @param {Number} index The index where the item is to be inserted
31720      * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
31721      * @return {Roo.Toolbar.Button/Item}
31722      */
31723     insertButton : function(index, item){
31724         if(item instanceof Array){
31725             var buttons = [];
31726             for(var i = 0, len = item.length; i < len; i++) {
31727                buttons.push(this.insertButton(index + i, item[i]));
31728             }
31729             return buttons;
31730         }
31731         if (!(item instanceof Roo.Toolbar.Button)){
31732            item = new Roo.Toolbar.Button(item);
31733         }
31734         var td = document.createElement("td");
31735         this.tr.insertBefore(td, this.tr.childNodes[index]);
31736         item.render(td);
31737         this.items.insert(index, item);
31738         return item;
31739     },
31740     
31741     /**
31742      * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
31743      * @param {Object} config
31744      * @return {Roo.Toolbar.Item} The element's item
31745      */
31746     addDom : function(config, returnEl){
31747         var td = this.nextBlock();
31748         Roo.DomHelper.overwrite(td, config);
31749         var ti = new Roo.Toolbar.Item(td.firstChild);
31750         ti.render(td);
31751         this.items.add(ti);
31752         return ti;
31753     },
31754
31755     /**
31756      * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
31757      * @type Roo.util.MixedCollection  
31758      */
31759     fields : false,
31760     
31761     /**
31762      * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
31763      * Note: the field should not have been rendered yet. For a field that has already been
31764      * rendered, use {@link #addElement}.
31765      * @param {Roo.form.Field} field
31766      * @return {Roo.ToolbarItem}
31767      */
31768      
31769       
31770     addField : function(field) {
31771         if (!this.fields) {
31772             var autoId = 0;
31773             this.fields = new Roo.util.MixedCollection(false, function(o){
31774                 return o.id || ("item" + (++autoId));
31775             });
31776
31777         }
31778         
31779         var td = this.nextBlock();
31780         field.render(td);
31781         var ti = new Roo.Toolbar.Item(td.firstChild);
31782         ti.render(td);
31783         this.items.add(ti);
31784         this.fields.add(field);
31785         return ti;
31786     },
31787     /**
31788      * Hide the toolbar
31789      * @method hide
31790      */
31791      
31792       
31793     hide : function()
31794     {
31795         this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
31796         this.el.child('div').hide();
31797     },
31798     /**
31799      * Show the toolbar
31800      * @method show
31801      */
31802     show : function()
31803     {
31804         this.el.child('div').show();
31805     },
31806       
31807     // private
31808     nextBlock : function(){
31809         var td = document.createElement("td");
31810         this.tr.appendChild(td);
31811         return td;
31812     },
31813
31814     // private
31815     destroy : function(){
31816         if(this.items){ // rendered?
31817             Roo.destroy.apply(Roo, this.items.items);
31818         }
31819         if(this.fields){ // rendered?
31820             Roo.destroy.apply(Roo, this.fields.items);
31821         }
31822         Roo.Element.uncache(this.el, this.tr);
31823     }
31824 };
31825
31826 /**
31827  * @class Roo.Toolbar.Item
31828  * The base class that other classes should extend in order to get some basic common toolbar item functionality.
31829  * @constructor
31830  * Creates a new Item
31831  * @param {HTMLElement} el 
31832  */
31833 Roo.Toolbar.Item = function(el){
31834     var cfg = {};
31835     if (typeof (el.xtype) != 'undefined') {
31836         cfg = el;
31837         el = cfg.el;
31838     }
31839     
31840     this.el = Roo.getDom(el);
31841     this.id = Roo.id(this.el);
31842     this.hidden = false;
31843     
31844     this.addEvents({
31845          /**
31846              * @event render
31847              * Fires when the button is rendered
31848              * @param {Button} this
31849              */
31850         'render': true
31851     });
31852     Roo.Toolbar.Item.superclass.constructor.call(this,cfg);
31853 };
31854 Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
31855 //Roo.Toolbar.Item.prototype = {
31856     
31857     /**
31858      * Get this item's HTML Element
31859      * @return {HTMLElement}
31860      */
31861     getEl : function(){
31862        return this.el;  
31863     },
31864
31865     // private
31866     render : function(td){
31867         
31868          this.td = td;
31869         td.appendChild(this.el);
31870         
31871         this.fireEvent('render', this);
31872     },
31873     
31874     /**
31875      * Removes and destroys this item.
31876      */
31877     destroy : function(){
31878         this.td.parentNode.removeChild(this.td);
31879     },
31880     
31881     /**
31882      * Shows this item.
31883      */
31884     show: function(){
31885         this.hidden = false;
31886         this.td.style.display = "";
31887     },
31888     
31889     /**
31890      * Hides this item.
31891      */
31892     hide: function(){
31893         this.hidden = true;
31894         this.td.style.display = "none";
31895     },
31896     
31897     /**
31898      * Convenience function for boolean show/hide.
31899      * @param {Boolean} visible true to show/false to hide
31900      */
31901     setVisible: function(visible){
31902         if(visible) {
31903             this.show();
31904         }else{
31905             this.hide();
31906         }
31907     },
31908     
31909     /**
31910      * Try to focus this item.
31911      */
31912     focus : function(){
31913         Roo.fly(this.el).focus();
31914     },
31915     
31916     /**
31917      * Disables this item.
31918      */
31919     disable : function(){
31920         Roo.fly(this.td).addClass("x-item-disabled");
31921         this.disabled = true;
31922         this.el.disabled = true;
31923     },
31924     
31925     /**
31926      * Enables this item.
31927      */
31928     enable : function(){
31929         Roo.fly(this.td).removeClass("x-item-disabled");
31930         this.disabled = false;
31931         this.el.disabled = false;
31932     }
31933 });
31934
31935
31936 /**
31937  * @class Roo.Toolbar.Separator
31938  * @extends Roo.Toolbar.Item
31939  * A simple toolbar separator class
31940  * @constructor
31941  * Creates a new Separator
31942  */
31943 Roo.Toolbar.Separator = function(cfg){
31944     
31945     var s = document.createElement("span");
31946     s.className = "ytb-sep";
31947     if (cfg) {
31948         cfg.el = s;
31949     }
31950     
31951     Roo.Toolbar.Separator.superclass.constructor.call(this, cfg || s);
31952 };
31953 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
31954     enable:Roo.emptyFn,
31955     disable:Roo.emptyFn,
31956     focus:Roo.emptyFn
31957 });
31958
31959 /**
31960  * @class Roo.Toolbar.Spacer
31961  * @extends Roo.Toolbar.Item
31962  * A simple element that adds extra horizontal space to a toolbar.
31963  * @constructor
31964  * Creates a new Spacer
31965  */
31966 Roo.Toolbar.Spacer = function(cfg){
31967     var s = document.createElement("div");
31968     s.className = "ytb-spacer";
31969     if (cfg) {
31970         cfg.el = s;
31971     }
31972     Roo.Toolbar.Spacer.superclass.constructor.call(this, cfg || s);
31973 };
31974 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
31975     enable:Roo.emptyFn,
31976     disable:Roo.emptyFn,
31977     focus:Roo.emptyFn
31978 });
31979
31980 /**
31981  * @class Roo.Toolbar.Fill
31982  * @extends Roo.Toolbar.Spacer
31983  * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
31984  * @constructor
31985  * Creates a new Spacer
31986  */
31987 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
31988     // private
31989     render : function(td){
31990         td.style.width = '100%';
31991         Roo.Toolbar.Fill.superclass.render.call(this, td);
31992     }
31993 });
31994
31995 /**
31996  * @class Roo.Toolbar.TextItem
31997  * @extends Roo.Toolbar.Item
31998  * A simple class that renders text directly into a toolbar.
31999  * @constructor
32000  * Creates a new TextItem
32001  * @cfg {string} text 
32002  */
32003 Roo.Toolbar.TextItem = function(cfg){
32004     var  text = cfg || "";
32005     if (typeof(cfg) == 'object') {
32006         text = cfg.text || "";
32007     }  else {
32008         cfg = null;
32009     }
32010     var s = document.createElement("span");
32011     s.className = "ytb-text";
32012     s.innerHTML = text;
32013     if (cfg) {
32014         cfg.el  = s;
32015     }
32016     
32017     Roo.Toolbar.TextItem.superclass.constructor.call(this, cfg ||  s);
32018 };
32019 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
32020     
32021      
32022     enable:Roo.emptyFn,
32023     disable:Roo.emptyFn,
32024     focus:Roo.emptyFn,
32025      /**
32026      * Shows this button
32027      */
32028     show: function(){
32029         this.hidden = false;
32030         this.el.style.display = "";
32031     },
32032     
32033     /**
32034      * Hides this button
32035      */
32036     hide: function(){
32037         this.hidden = true;
32038         this.el.style.display = "none";
32039     }
32040     
32041 });
32042
32043 /**
32044  * @class Roo.Toolbar.Button
32045  * @extends Roo.Button
32046  * A button that renders into a toolbar.
32047  * @constructor
32048  * Creates a new Button
32049  * @param {Object} config A standard {@link Roo.Button} config object
32050  */
32051 Roo.Toolbar.Button = function(config){
32052     Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
32053 };
32054 Roo.extend(Roo.Toolbar.Button, Roo.Button,
32055 {
32056     
32057     
32058     render : function(td){
32059         this.td = td;
32060         Roo.Toolbar.Button.superclass.render.call(this, td);
32061     },
32062     
32063     /**
32064      * Removes and destroys this button
32065      */
32066     destroy : function(){
32067         Roo.Toolbar.Button.superclass.destroy.call(this);
32068         this.td.parentNode.removeChild(this.td);
32069     },
32070     
32071     /**
32072      * Shows this button
32073      */
32074     show: function(){
32075         this.hidden = false;
32076         this.td.style.display = "";
32077     },
32078     
32079     /**
32080      * Hides this button
32081      */
32082     hide: function(){
32083         this.hidden = true;
32084         this.td.style.display = "none";
32085     },
32086
32087     /**
32088      * Disables this item
32089      */
32090     disable : function(){
32091         Roo.fly(this.td).addClass("x-item-disabled");
32092         this.disabled = true;
32093     },
32094
32095     /**
32096      * Enables this item
32097      */
32098     enable : function(){
32099         Roo.fly(this.td).removeClass("x-item-disabled");
32100         this.disabled = false;
32101     }
32102 });
32103 // backwards compat
32104 Roo.ToolbarButton = Roo.Toolbar.Button;
32105
32106 /**
32107  * @class Roo.Toolbar.SplitButton
32108  * @extends Roo.SplitButton
32109  * A menu button that renders into a toolbar.
32110  * @constructor
32111  * Creates a new SplitButton
32112  * @param {Object} config A standard {@link Roo.SplitButton} config object
32113  */
32114 Roo.Toolbar.SplitButton = function(config){
32115     Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
32116 };
32117 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
32118     render : function(td){
32119         this.td = td;
32120         Roo.Toolbar.SplitButton.superclass.render.call(this, td);
32121     },
32122     
32123     /**
32124      * Removes and destroys this button
32125      */
32126     destroy : function(){
32127         Roo.Toolbar.SplitButton.superclass.destroy.call(this);
32128         this.td.parentNode.removeChild(this.td);
32129     },
32130     
32131     /**
32132      * Shows this button
32133      */
32134     show: function(){
32135         this.hidden = false;
32136         this.td.style.display = "";
32137     },
32138     
32139     /**
32140      * Hides this button
32141      */
32142     hide: function(){
32143         this.hidden = true;
32144         this.td.style.display = "none";
32145     }
32146 });
32147
32148 // backwards compat
32149 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
32150  * Based on:
32151  * Ext JS Library 1.1.1
32152  * Copyright(c) 2006-2007, Ext JS, LLC.
32153  *
32154  * Originally Released Under LGPL - original licence link has changed is not relivant.
32155  *
32156  * Fork - LGPL
32157  * <script type="text/javascript">
32158  */
32159  
32160 /**
32161  * @class Roo.PagingToolbar
32162  * @extends Roo.Toolbar
32163  * @children   Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field
32164  * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
32165  * @constructor
32166  * Create a new PagingToolbar
32167  * @param {Object} config The config object
32168  */
32169 Roo.PagingToolbar = function(el, ds, config)
32170 {
32171     // old args format still supported... - xtype is prefered..
32172     if (typeof(el) == 'object' && el.xtype) {
32173         // created from xtype...
32174         config = el;
32175         ds = el.dataSource;
32176         el = config.container;
32177     }
32178     var items = [];
32179     if (config.items) {
32180         items = config.items;
32181         config.items = [];
32182     }
32183     
32184     Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
32185     this.ds = ds;
32186     this.cursor = 0;
32187     this.renderButtons(this.el);
32188     this.bind(ds);
32189     
32190     // supprot items array.
32191    
32192     Roo.each(items, function(e) {
32193         this.add(Roo.factory(e));
32194     },this);
32195     
32196 };
32197
32198 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
32199    
32200     /**
32201      * @cfg {String/HTMLElement/Element} container
32202      * container The id or element that will contain the toolbar
32203      */
32204     /**
32205      * @cfg {Boolean} displayInfo
32206      * True to display the displayMsg (defaults to false)
32207      */
32208     
32209     
32210     /**
32211      * @cfg {Number} pageSize
32212      * The number of records to display per page (defaults to 20)
32213      */
32214     pageSize: 20,
32215     /**
32216      * @cfg {String} displayMsg
32217      * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
32218      */
32219     displayMsg : 'Displaying {0} - {1} of {2}',
32220     /**
32221      * @cfg {String} emptyMsg
32222      * The message to display when no records are found (defaults to "No data to display")
32223      */
32224     emptyMsg : 'No data to display',
32225     /**
32226      * Customizable piece of the default paging text (defaults to "Page")
32227      * @type String
32228      */
32229     beforePageText : "Page",
32230     /**
32231      * Customizable piece of the default paging text (defaults to "of %0")
32232      * @type String
32233      */
32234     afterPageText : "of {0}",
32235     /**
32236      * Customizable piece of the default paging text (defaults to "First Page")
32237      * @type String
32238      */
32239     firstText : "First Page",
32240     /**
32241      * Customizable piece of the default paging text (defaults to "Previous Page")
32242      * @type String
32243      */
32244     prevText : "Previous Page",
32245     /**
32246      * Customizable piece of the default paging text (defaults to "Next Page")
32247      * @type String
32248      */
32249     nextText : "Next Page",
32250     /**
32251      * Customizable piece of the default paging text (defaults to "Last Page")
32252      * @type String
32253      */
32254     lastText : "Last Page",
32255     /**
32256      * Customizable piece of the default paging text (defaults to "Refresh")
32257      * @type String
32258      */
32259     refreshText : "Refresh",
32260
32261     // private
32262     renderButtons : function(el){
32263         Roo.PagingToolbar.superclass.render.call(this, el);
32264         this.first = this.addButton({
32265             tooltip: this.firstText,
32266             cls: "x-btn-icon x-grid-page-first",
32267             disabled: true,
32268             handler: this.onClick.createDelegate(this, ["first"])
32269         });
32270         this.prev = this.addButton({
32271             tooltip: this.prevText,
32272             cls: "x-btn-icon x-grid-page-prev",
32273             disabled: true,
32274             handler: this.onClick.createDelegate(this, ["prev"])
32275         });
32276         //this.addSeparator();
32277         this.add(this.beforePageText);
32278         this.field = Roo.get(this.addDom({
32279            tag: "input",
32280            type: "text",
32281            size: "3",
32282            value: "1",
32283            cls: "x-grid-page-number"
32284         }).el);
32285         this.field.on("keydown", this.onPagingKeydown, this);
32286         this.field.on("focus", function(){this.dom.select();});
32287         this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
32288         this.field.setHeight(18);
32289         //this.addSeparator();
32290         this.next = this.addButton({
32291             tooltip: this.nextText,
32292             cls: "x-btn-icon x-grid-page-next",
32293             disabled: true,
32294             handler: this.onClick.createDelegate(this, ["next"])
32295         });
32296         this.last = this.addButton({
32297             tooltip: this.lastText,
32298             cls: "x-btn-icon x-grid-page-last",
32299             disabled: true,
32300             handler: this.onClick.createDelegate(this, ["last"])
32301         });
32302         //this.addSeparator();
32303         this.loading = this.addButton({
32304             tooltip: this.refreshText,
32305             cls: "x-btn-icon x-grid-loading",
32306             handler: this.onClick.createDelegate(this, ["refresh"])
32307         });
32308
32309         if(this.displayInfo){
32310             this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
32311         }
32312     },
32313
32314     // private
32315     updateInfo : function(){
32316         if(this.displayEl){
32317             var count = this.ds.getCount();
32318             var msg = count == 0 ?
32319                 this.emptyMsg :
32320                 String.format(
32321                     this.displayMsg,
32322                     this.cursor+1, this.cursor+count, this.ds.getTotalCount()    
32323                 );
32324             this.displayEl.update(msg);
32325         }
32326     },
32327
32328     // private
32329     onLoad : function(ds, r, o){
32330        this.cursor = o.params ? o.params.start : 0;
32331        var d = this.getPageData(), ap = d.activePage, ps = d.pages;
32332
32333        this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
32334        this.field.dom.value = ap;
32335        this.first.setDisabled(ap == 1);
32336        this.prev.setDisabled(ap == 1);
32337        this.next.setDisabled(ap == ps);
32338        this.last.setDisabled(ap == ps);
32339        this.loading.enable();
32340        this.updateInfo();
32341     },
32342
32343     // private
32344     getPageData : function(){
32345         var total = this.ds.getTotalCount();
32346         return {
32347             total : total,
32348             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
32349             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
32350         };
32351     },
32352
32353     // private
32354     onLoadError : function(){
32355         this.loading.enable();
32356     },
32357
32358     // private
32359     onPagingKeydown : function(e){
32360         var k = e.getKey();
32361         var d = this.getPageData();
32362         if(k == e.RETURN){
32363             var v = this.field.dom.value, pageNum;
32364             if(!v || isNaN(pageNum = parseInt(v, 10))){
32365                 this.field.dom.value = d.activePage;
32366                 return;
32367             }
32368             pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
32369             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
32370             e.stopEvent();
32371         }
32372         else if(k == e.HOME || (k == e.UP && e.ctrlKey) || (k == e.PAGEUP && e.ctrlKey) || (k == e.RIGHT && e.ctrlKey) || k == e.END || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey))
32373         {
32374           var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
32375           this.field.dom.value = pageNum;
32376           this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
32377           e.stopEvent();
32378         }
32379         else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
32380         {
32381           var v = this.field.dom.value, pageNum; 
32382           var increment = (e.shiftKey) ? 10 : 1;
32383           if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
32384             increment *= -1;
32385           }
32386           if(!v || isNaN(pageNum = parseInt(v, 10))) {
32387             this.field.dom.value = d.activePage;
32388             return;
32389           }
32390           else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
32391           {
32392             this.field.dom.value = parseInt(v, 10) + increment;
32393             pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
32394             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
32395           }
32396           e.stopEvent();
32397         }
32398     },
32399
32400     // private
32401     beforeLoad : function(){
32402         if(this.loading){
32403             this.loading.disable();
32404         }
32405     },
32406
32407     // private
32408     onClick : function(which){
32409         var ds = this.ds;
32410         switch(which){
32411             case "first":
32412                 ds.load({params:{start: 0, limit: this.pageSize}});
32413             break;
32414             case "prev":
32415                 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
32416             break;
32417             case "next":
32418                 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
32419             break;
32420             case "last":
32421                 var total = ds.getTotalCount();
32422                 var extra = total % this.pageSize;
32423                 var lastStart = extra ? (total - extra) : total-this.pageSize;
32424                 ds.load({params:{start: lastStart, limit: this.pageSize}});
32425             break;
32426             case "refresh":
32427                 ds.load({params:{start: this.cursor, limit: this.pageSize}});
32428             break;
32429         }
32430     },
32431
32432     /**
32433      * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
32434      * @param {Roo.data.Store} store The data store to unbind
32435      */
32436     unbind : function(ds){
32437         ds.un("beforeload", this.beforeLoad, this);
32438         ds.un("load", this.onLoad, this);
32439         ds.un("loadexception", this.onLoadError, this);
32440         ds.un("remove", this.updateInfo, this);
32441         ds.un("add", this.updateInfo, this);
32442         this.ds = undefined;
32443     },
32444
32445     /**
32446      * Binds the paging toolbar to the specified {@link Roo.data.Store}
32447      * @param {Roo.data.Store} store The data store to bind
32448      */
32449     bind : function(ds){
32450         ds.on("beforeload", this.beforeLoad, this);
32451         ds.on("load", this.onLoad, this);
32452         ds.on("loadexception", this.onLoadError, this);
32453         ds.on("remove", this.updateInfo, this);
32454         ds.on("add", this.updateInfo, this);
32455         this.ds = ds;
32456     }
32457 });/*
32458  * Based on:
32459  * Ext JS Library 1.1.1
32460  * Copyright(c) 2006-2007, Ext JS, LLC.
32461  *
32462  * Originally Released Under LGPL - original licence link has changed is not relivant.
32463  *
32464  * Fork - LGPL
32465  * <script type="text/javascript">
32466  */
32467
32468 /**
32469  * @class Roo.Resizable
32470  * @extends Roo.util.Observable
32471  * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
32472  * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
32473  * the textarea in a div and set "resizeChild" to true (or to the id of the element), <b>or</b> set wrap:true in your config and
32474  * the element will be wrapped for you automatically.</p>
32475  * <p>Here is the list of valid resize handles:</p>
32476  * <pre>
32477 Value   Description
32478 ------  -------------------
32479  'n'     north
32480  's'     south
32481  'e'     east
32482  'w'     west
32483  'nw'    northwest
32484  'sw'    southwest
32485  'se'    southeast
32486  'ne'    northeast
32487  'hd'    horizontal drag
32488  'all'   all
32489 </pre>
32490  * <p>Here's an example showing the creation of a typical Resizable:</p>
32491  * <pre><code>
32492 var resizer = new Roo.Resizable("element-id", {
32493     handles: 'all',
32494     minWidth: 200,
32495     minHeight: 100,
32496     maxWidth: 500,
32497     maxHeight: 400,
32498     pinned: true
32499 });
32500 resizer.on("resize", myHandler);
32501 </code></pre>
32502  * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
32503  * resizer.east.setDisplayed(false);</p>
32504  * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
32505  * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
32506  * resize operation's new size (defaults to [0, 0])
32507  * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
32508  * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
32509  * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
32510  * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
32511  * @cfg {Boolean} enabled False to disable resizing (defaults to true)
32512  * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
32513  * @cfg {Number} width The width of the element in pixels (defaults to null)
32514  * @cfg {Number} height The height of the element in pixels (defaults to null)
32515  * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
32516  * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
32517  * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
32518  * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
32519  * @cfg {Boolean} multiDirectional <b>Deprecated</b>.  The old style of adding multi-direction resize handles, deprecated
32520  * in favor of the handles config option (defaults to false)
32521  * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
32522  * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
32523  * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
32524  * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
32525  * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
32526  * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
32527  * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
32528  * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
32529  * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
32530  * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
32531  * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
32532  * @constructor
32533  * Create a new resizable component
32534  * @param {String/HTMLElement/Roo.Element} el The id or element to resize
32535  * @param {Object} config configuration options
32536   */
32537 Roo.Resizable = function(el, config)
32538 {
32539     this.el = Roo.get(el);
32540
32541     if(config && config.wrap){
32542         config.resizeChild = this.el;
32543         this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
32544         this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
32545         this.el.setStyle("overflow", "hidden");
32546         this.el.setPositioning(config.resizeChild.getPositioning());
32547         config.resizeChild.clearPositioning();
32548         if(!config.width || !config.height){
32549             var csize = config.resizeChild.getSize();
32550             this.el.setSize(csize.width, csize.height);
32551         }
32552         if(config.pinned && !config.adjustments){
32553             config.adjustments = "auto";
32554         }
32555     }
32556
32557     this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
32558     this.proxy.unselectable();
32559     this.proxy.enableDisplayMode('block');
32560
32561     Roo.apply(this, config);
32562
32563     if(this.pinned){
32564         this.disableTrackOver = true;
32565         this.el.addClass("x-resizable-pinned");
32566     }
32567     // if the element isn't positioned, make it relative
32568     var position = this.el.getStyle("position");
32569     if(position != "absolute" && position != "fixed"){
32570         this.el.setStyle("position", "relative");
32571     }
32572     if(!this.handles){ // no handles passed, must be legacy style
32573         this.handles = 's,e,se';
32574         if(this.multiDirectional){
32575             this.handles += ',n,w';
32576         }
32577     }
32578     if(this.handles == "all"){
32579         this.handles = "n s e w ne nw se sw";
32580     }
32581     var hs = this.handles.split(/\s*?[,;]\s*?| /);
32582     var ps = Roo.Resizable.positions;
32583     for(var i = 0, len = hs.length; i < len; i++){
32584         if(hs[i] && ps[hs[i]]){
32585             var pos = ps[hs[i]];
32586             this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
32587         }
32588     }
32589     // legacy
32590     this.corner = this.southeast;
32591     
32592     // updateBox = the box can move..
32593     if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
32594         this.updateBox = true;
32595     }
32596
32597     this.activeHandle = null;
32598
32599     if(this.resizeChild){
32600         if(typeof this.resizeChild == "boolean"){
32601             this.resizeChild = Roo.get(this.el.dom.firstChild, true);
32602         }else{
32603             this.resizeChild = Roo.get(this.resizeChild, true);
32604         }
32605     }
32606     
32607     if(this.adjustments == "auto"){
32608         var rc = this.resizeChild;
32609         var hw = this.west, he = this.east, hn = this.north, hs = this.south;
32610         if(rc && (hw || hn)){
32611             rc.position("relative");
32612             rc.setLeft(hw ? hw.el.getWidth() : 0);
32613             rc.setTop(hn ? hn.el.getHeight() : 0);
32614         }
32615         this.adjustments = [
32616             (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
32617             (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
32618         ];
32619     }
32620
32621     if(this.draggable){
32622         this.dd = this.dynamic ?
32623             this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
32624         this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
32625     }
32626
32627     // public events
32628     this.addEvents({
32629         /**
32630          * @event beforeresize
32631          * Fired before resize is allowed. Set enabled to false to cancel resize.
32632          * @param {Roo.Resizable} this
32633          * @param {Roo.EventObject} e The mousedown event
32634          */
32635         "beforeresize" : true,
32636         /**
32637          * @event resizing
32638          * Fired a resizing.
32639          * @param {Roo.Resizable} this
32640          * @param {Number} x The new x position
32641          * @param {Number} y The new y position
32642          * @param {Number} w The new w width
32643          * @param {Number} h The new h hight
32644          * @param {Roo.EventObject} e The mouseup event
32645          */
32646         "resizing" : true,
32647         /**
32648          * @event resize
32649          * Fired after a resize.
32650          * @param {Roo.Resizable} this
32651          * @param {Number} width The new width
32652          * @param {Number} height The new height
32653          * @param {Roo.EventObject} e The mouseup event
32654          */
32655         "resize" : true
32656     });
32657
32658     if(this.width !== null && this.height !== null){
32659         this.resizeTo(this.width, this.height);
32660     }else{
32661         this.updateChildSize();
32662     }
32663     if(Roo.isIE){
32664         this.el.dom.style.zoom = 1;
32665     }
32666     Roo.Resizable.superclass.constructor.call(this);
32667 };
32668
32669 Roo.extend(Roo.Resizable, Roo.util.Observable, {
32670         resizeChild : false,
32671         adjustments : [0, 0],
32672         minWidth : 5,
32673         minHeight : 5,
32674         maxWidth : 10000,
32675         maxHeight : 10000,
32676         enabled : true,
32677         animate : false,
32678         duration : .35,
32679         dynamic : false,
32680         handles : false,
32681         multiDirectional : false,
32682         disableTrackOver : false,
32683         easing : 'easeOutStrong',
32684         widthIncrement : 0,
32685         heightIncrement : 0,
32686         pinned : false,
32687         width : null,
32688         height : null,
32689         preserveRatio : false,
32690         transparent: false,
32691         minX: 0,
32692         minY: 0,
32693         draggable: false,
32694
32695         /**
32696          * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
32697          */
32698         constrainTo: undefined,
32699         /**
32700          * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
32701          */
32702         resizeRegion: undefined,
32703
32704
32705     /**
32706      * Perform a manual resize
32707      * @param {Number} width
32708      * @param {Number} height
32709      */
32710     resizeTo : function(width, height){
32711         this.el.setSize(width, height);
32712         this.updateChildSize();
32713         this.fireEvent("resize", this, width, height, null);
32714     },
32715
32716     // private
32717     startSizing : function(e, handle){
32718         this.fireEvent("beforeresize", this, e);
32719         if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
32720
32721             if(!this.overlay){
32722                 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: "&#160;"});
32723                 this.overlay.unselectable();
32724                 this.overlay.enableDisplayMode("block");
32725                 this.overlay.on("mousemove", this.onMouseMove, this);
32726                 this.overlay.on("mouseup", this.onMouseUp, this);
32727             }
32728             this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
32729
32730             this.resizing = true;
32731             this.startBox = this.el.getBox();
32732             this.startPoint = e.getXY();
32733             this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
32734                             (this.startBox.y + this.startBox.height) - this.startPoint[1]];
32735
32736             this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
32737             this.overlay.show();
32738
32739             if(this.constrainTo) {
32740                 var ct = Roo.get(this.constrainTo);
32741                 this.resizeRegion = ct.getRegion().adjust(
32742                     ct.getFrameWidth('t'),
32743                     ct.getFrameWidth('l'),
32744                     -ct.getFrameWidth('b'),
32745                     -ct.getFrameWidth('r')
32746                 );
32747             }
32748
32749             this.proxy.setStyle('visibility', 'hidden'); // workaround display none
32750             this.proxy.show();
32751             this.proxy.setBox(this.startBox);
32752             if(!this.dynamic){
32753                 this.proxy.setStyle('visibility', 'visible');
32754             }
32755         }
32756     },
32757
32758     // private
32759     onMouseDown : function(handle, e){
32760         if(this.enabled){
32761             e.stopEvent();
32762             this.activeHandle = handle;
32763             this.startSizing(e, handle);
32764         }
32765     },
32766
32767     // private
32768     onMouseUp : function(e){
32769         var size = this.resizeElement();
32770         this.resizing = false;
32771         this.handleOut();
32772         this.overlay.hide();
32773         this.proxy.hide();
32774         this.fireEvent("resize", this, size.width, size.height, e);
32775     },
32776
32777     // private
32778     updateChildSize : function(){
32779         
32780         if(this.resizeChild){
32781             var el = this.el;
32782             var child = this.resizeChild;
32783             var adj = this.adjustments;
32784             if(el.dom.offsetWidth){
32785                 var b = el.getSize(true);
32786                 child.setSize(b.width+adj[0], b.height+adj[1]);
32787             }
32788             // Second call here for IE
32789             // The first call enables instant resizing and
32790             // the second call corrects scroll bars if they
32791             // exist
32792             if(Roo.isIE){
32793                 setTimeout(function(){
32794                     if(el.dom.offsetWidth){
32795                         var b = el.getSize(true);
32796                         child.setSize(b.width+adj[0], b.height+adj[1]);
32797                     }
32798                 }, 10);
32799             }
32800         }
32801     },
32802
32803     // private
32804     snap : function(value, inc, min){
32805         if(!inc || !value) {
32806             return value;
32807         }
32808         var newValue = value;
32809         var m = value % inc;
32810         if(m > 0){
32811             if(m > (inc/2)){
32812                 newValue = value + (inc-m);
32813             }else{
32814                 newValue = value - m;
32815             }
32816         }
32817         return Math.max(min, newValue);
32818     },
32819
32820     // private
32821     resizeElement : function(){
32822         var box = this.proxy.getBox();
32823         if(this.updateBox){
32824             this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
32825         }else{
32826             this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
32827         }
32828         this.updateChildSize();
32829         if(!this.dynamic){
32830             this.proxy.hide();
32831         }
32832         return box;
32833     },
32834
32835     // private
32836     constrain : function(v, diff, m, mx){
32837         if(v - diff < m){
32838             diff = v - m;
32839         }else if(v - diff > mx){
32840             diff = mx - v;
32841         }
32842         return diff;
32843     },
32844
32845     // private
32846     onMouseMove : function(e){
32847         
32848         if(this.enabled){
32849             try{// try catch so if something goes wrong the user doesn't get hung
32850
32851             if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
32852                 return;
32853             }
32854
32855             //var curXY = this.startPoint;
32856             var curSize = this.curSize || this.startBox;
32857             var x = this.startBox.x, y = this.startBox.y;
32858             var ox = x, oy = y;
32859             var w = curSize.width, h = curSize.height;
32860             var ow = w, oh = h;
32861             var mw = this.minWidth, mh = this.minHeight;
32862             var mxw = this.maxWidth, mxh = this.maxHeight;
32863             var wi = this.widthIncrement;
32864             var hi = this.heightIncrement;
32865
32866             var eventXY = e.getXY();
32867             var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
32868             var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
32869
32870             var pos = this.activeHandle.position;
32871
32872             switch(pos){
32873                 case "east":
32874                     w += diffX;
32875                     w = Math.min(Math.max(mw, w), mxw);
32876                     break;
32877              
32878                 case "south":
32879                     h += diffY;
32880                     h = Math.min(Math.max(mh, h), mxh);
32881                     break;
32882                 case "southeast":
32883                     w += diffX;
32884                     h += diffY;
32885                     w = Math.min(Math.max(mw, w), mxw);
32886                     h = Math.min(Math.max(mh, h), mxh);
32887                     break;
32888                 case "north":
32889                     diffY = this.constrain(h, diffY, mh, mxh);
32890                     y += diffY;
32891                     h -= diffY;
32892                     break;
32893                 case "hdrag":
32894                     
32895                     if (wi) {
32896                         var adiffX = Math.abs(diffX);
32897                         var sub = (adiffX % wi); // how much 
32898                         if (sub > (wi/2)) { // far enough to snap
32899                             diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
32900                         } else {
32901                             // remove difference.. 
32902                             diffX = (diffX > 0) ? diffX-sub : diffX+sub;
32903                         }
32904                     }
32905                     x += diffX;
32906                     x = Math.max(this.minX, x);
32907                     break;
32908                 case "west":
32909                     diffX = this.constrain(w, diffX, mw, mxw);
32910                     x += diffX;
32911                     w -= diffX;
32912                     break;
32913                 case "northeast":
32914                     w += diffX;
32915                     w = Math.min(Math.max(mw, w), mxw);
32916                     diffY = this.constrain(h, diffY, mh, mxh);
32917                     y += diffY;
32918                     h -= diffY;
32919                     break;
32920                 case "northwest":
32921                     diffX = this.constrain(w, diffX, mw, mxw);
32922                     diffY = this.constrain(h, diffY, mh, mxh);
32923                     y += diffY;
32924                     h -= diffY;
32925                     x += diffX;
32926                     w -= diffX;
32927                     break;
32928                case "southwest":
32929                     diffX = this.constrain(w, diffX, mw, mxw);
32930                     h += diffY;
32931                     h = Math.min(Math.max(mh, h), mxh);
32932                     x += diffX;
32933                     w -= diffX;
32934                     break;
32935             }
32936
32937             var sw = this.snap(w, wi, mw);
32938             var sh = this.snap(h, hi, mh);
32939             if(sw != w || sh != h){
32940                 switch(pos){
32941                     case "northeast":
32942                         y -= sh - h;
32943                     break;
32944                     case "north":
32945                         y -= sh - h;
32946                         break;
32947                     case "southwest":
32948                         x -= sw - w;
32949                     break;
32950                     case "west":
32951                         x -= sw - w;
32952                         break;
32953                     case "northwest":
32954                         x -= sw - w;
32955                         y -= sh - h;
32956                     break;
32957                 }
32958                 w = sw;
32959                 h = sh;
32960             }
32961
32962             if(this.preserveRatio){
32963                 switch(pos){
32964                     case "southeast":
32965                     case "east":
32966                         h = oh * (w/ow);
32967                         h = Math.min(Math.max(mh, h), mxh);
32968                         w = ow * (h/oh);
32969                        break;
32970                     case "south":
32971                         w = ow * (h/oh);
32972                         w = Math.min(Math.max(mw, w), mxw);
32973                         h = oh * (w/ow);
32974                         break;
32975                     case "northeast":
32976                         w = ow * (h/oh);
32977                         w = Math.min(Math.max(mw, w), mxw);
32978                         h = oh * (w/ow);
32979                     break;
32980                     case "north":
32981                         var tw = w;
32982                         w = ow * (h/oh);
32983                         w = Math.min(Math.max(mw, w), mxw);
32984                         h = oh * (w/ow);
32985                         x += (tw - w) / 2;
32986                         break;
32987                     case "southwest":
32988                         h = oh * (w/ow);
32989                         h = Math.min(Math.max(mh, h), mxh);
32990                         var tw = w;
32991                         w = ow * (h/oh);
32992                         x += tw - w;
32993                         break;
32994                     case "west":
32995                         var th = h;
32996                         h = oh * (w/ow);
32997                         h = Math.min(Math.max(mh, h), mxh);
32998                         y += (th - h) / 2;
32999                         var tw = w;
33000                         w = ow * (h/oh);
33001                         x += tw - w;
33002                        break;
33003                     case "northwest":
33004                         var tw = w;
33005                         var th = h;
33006                         h = oh * (w/ow);
33007                         h = Math.min(Math.max(mh, h), mxh);
33008                         w = ow * (h/oh);
33009                         y += th - h;
33010                         x += tw - w;
33011                        break;
33012
33013                 }
33014             }
33015             if (pos == 'hdrag') {
33016                 w = ow;
33017             }
33018             this.proxy.setBounds(x, y, w, h);
33019             if(this.dynamic){
33020                 this.resizeElement();
33021             }
33022             }catch(e){}
33023         }
33024         this.fireEvent("resizing", this, x, y, w, h, e);
33025     },
33026
33027     // private
33028     handleOver : function(){
33029         if(this.enabled){
33030             this.el.addClass("x-resizable-over");
33031         }
33032     },
33033
33034     // private
33035     handleOut : function(){
33036         if(!this.resizing){
33037             this.el.removeClass("x-resizable-over");
33038         }
33039     },
33040
33041     /**
33042      * Returns the element this component is bound to.
33043      * @return {Roo.Element}
33044      */
33045     getEl : function(){
33046         return this.el;
33047     },
33048
33049     /**
33050      * Returns the resizeChild element (or null).
33051      * @return {Roo.Element}
33052      */
33053     getResizeChild : function(){
33054         return this.resizeChild;
33055     },
33056     groupHandler : function()
33057     {
33058         
33059     },
33060     /**
33061      * Destroys this resizable. If the element was wrapped and
33062      * removeEl is not true then the element remains.
33063      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
33064      */
33065     destroy : function(removeEl){
33066         this.proxy.remove();
33067         if(this.overlay){
33068             this.overlay.removeAllListeners();
33069             this.overlay.remove();
33070         }
33071         var ps = Roo.Resizable.positions;
33072         for(var k in ps){
33073             if(typeof ps[k] != "function" && this[ps[k]]){
33074                 var h = this[ps[k]];
33075                 h.el.removeAllListeners();
33076                 h.el.remove();
33077             }
33078         }
33079         if(removeEl){
33080             this.el.update("");
33081             this.el.remove();
33082         }
33083     }
33084 });
33085
33086 // private
33087 // hash to map config positions to true positions
33088 Roo.Resizable.positions = {
33089     n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast", 
33090     hd: "hdrag"
33091 };
33092
33093 // private
33094 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
33095     if(!this.tpl){
33096         // only initialize the template if resizable is used
33097         var tpl = Roo.DomHelper.createTemplate(
33098             {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
33099         );
33100         tpl.compile();
33101         Roo.Resizable.Handle.prototype.tpl = tpl;
33102     }
33103     this.position = pos;
33104     this.rz = rz;
33105     // show north drag fro topdra
33106     var handlepos = pos == 'hdrag' ? 'north' : pos;
33107     
33108     this.el = this.tpl.append(rz.el.dom, [handlepos], true);
33109     if (pos == 'hdrag') {
33110         this.el.setStyle('cursor', 'pointer');
33111     }
33112     this.el.unselectable();
33113     if(transparent){
33114         this.el.setOpacity(0);
33115     }
33116     this.el.on("mousedown", this.onMouseDown, this);
33117     if(!disableTrackOver){
33118         this.el.on("mouseover", this.onMouseOver, this);
33119         this.el.on("mouseout", this.onMouseOut, this);
33120     }
33121 };
33122
33123 // private
33124 Roo.Resizable.Handle.prototype = {
33125     afterResize : function(rz){
33126         Roo.log('after?');
33127         // do nothing
33128     },
33129     // private
33130     onMouseDown : function(e){
33131         this.rz.onMouseDown(this, e);
33132     },
33133     // private
33134     onMouseOver : function(e){
33135         this.rz.handleOver(this, e);
33136     },
33137     // private
33138     onMouseOut : function(e){
33139         this.rz.handleOut(this, e);
33140     }
33141 };/*
33142  * Based on:
33143  * Ext JS Library 1.1.1
33144  * Copyright(c) 2006-2007, Ext JS, LLC.
33145  *
33146  * Originally Released Under LGPL - original licence link has changed is not relivant.
33147  *
33148  * Fork - LGPL
33149  * <script type="text/javascript">
33150  */
33151
33152 /**
33153  * @class Roo.Editor
33154  * @extends Roo.Component
33155  * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
33156  * @constructor
33157  * Create a new Editor
33158  * @param {Roo.form.Field} field The Field object (or descendant)
33159  * @param {Object} config The config object
33160  */
33161 Roo.Editor = function(field, config){
33162     Roo.Editor.superclass.constructor.call(this, config);
33163     this.field = field;
33164     this.addEvents({
33165         /**
33166              * @event beforestartedit
33167              * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
33168              * false from the handler of this event.
33169              * @param {Editor} this
33170              * @param {Roo.Element} boundEl The underlying element bound to this editor
33171              * @param {Mixed} value The field value being set
33172              */
33173         "beforestartedit" : true,
33174         /**
33175              * @event startedit
33176              * Fires when this editor is displayed
33177              * @param {Roo.Element} boundEl The underlying element bound to this editor
33178              * @param {Mixed} value The starting field value
33179              */
33180         "startedit" : true,
33181         /**
33182              * @event beforecomplete
33183              * Fires after a change has been made to the field, but before the change is reflected in the underlying
33184              * field.  Saving the change to the field can be canceled by returning false from the handler of this event.
33185              * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
33186              * event will not fire since no edit actually occurred.
33187              * @param {Editor} this
33188              * @param {Mixed} value The current field value
33189              * @param {Mixed} startValue The original field value
33190              */
33191         "beforecomplete" : true,
33192         /**
33193              * @event complete
33194              * Fires after editing is complete and any changed value has been written to the underlying field.
33195              * @param {Editor} this
33196              * @param {Mixed} value The current field value
33197              * @param {Mixed} startValue The original field value
33198              */
33199         "complete" : true,
33200         /**
33201          * @event specialkey
33202          * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
33203          * {@link Roo.EventObject#getKey} to determine which key was pressed.
33204          * @param {Roo.form.Field} this
33205          * @param {Roo.EventObject} e The event object
33206          */
33207         "specialkey" : true
33208     });
33209 };
33210
33211 Roo.extend(Roo.Editor, Roo.Component, {
33212     /**
33213      * @cfg {Boolean/String} autosize
33214      * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
33215      * or "height" to adopt the height only (defaults to false)
33216      */
33217     /**
33218      * @cfg {Boolean} revertInvalid
33219      * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
33220      * validation fails (defaults to true)
33221      */
33222     /**
33223      * @cfg {Boolean} ignoreNoChange
33224      * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
33225      * the value has not changed (defaults to false).  Applies only to string values - edits for other data types
33226      * will never be ignored.
33227      */
33228     /**
33229      * @cfg {Boolean} hideEl
33230      * False to keep the bound element visible while the editor is displayed (defaults to true)
33231      */
33232     /**
33233      * @cfg {Mixed} value
33234      * The data value of the underlying field (defaults to "")
33235      */
33236     value : "",
33237     /**
33238      * @cfg {String} alignment
33239      * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
33240      */
33241     alignment: "c-c?",
33242     /**
33243      * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
33244      * for bottom-right shadow (defaults to "frame")
33245      */
33246     shadow : "frame",
33247     /**
33248      * @cfg {Boolean} constrain True to constrain the editor to the viewport
33249      */
33250     constrain : false,
33251     /**
33252      * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
33253      */
33254     completeOnEnter : false,
33255     /**
33256      * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
33257      */
33258     cancelOnEsc : false,
33259     /**
33260      * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
33261      */
33262     updateEl : false,
33263
33264     // private
33265     onRender : function(ct, position){
33266         this.el = new Roo.Layer({
33267             shadow: this.shadow,
33268             cls: "x-editor",
33269             parentEl : ct,
33270             shim : this.shim,
33271             shadowOffset:4,
33272             id: this.id,
33273             constrain: this.constrain
33274         });
33275         this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
33276         if(this.field.msgTarget != 'title'){
33277             this.field.msgTarget = 'qtip';
33278         }
33279         this.field.render(this.el);
33280         if(Roo.isGecko){
33281             this.field.el.dom.setAttribute('autocomplete', 'off');
33282         }
33283         this.field.on("specialkey", this.onSpecialKey, this);
33284         if(this.swallowKeys){
33285             this.field.el.swallowEvent(['keydown','keypress']);
33286         }
33287         this.field.show();
33288         this.field.on("blur", this.onBlur, this);
33289         if(this.field.grow){
33290             this.field.on("autosize", this.el.sync,  this.el, {delay:1});
33291         }
33292     },
33293
33294     onSpecialKey : function(field, e)
33295     {
33296         //Roo.log('editor onSpecialKey');
33297         if(this.completeOnEnter && e.getKey() == e.ENTER){
33298             e.stopEvent();
33299             this.completeEdit();
33300             return;
33301         }
33302         // do not fire special key otherwise it might hide close the editor...
33303         if(e.getKey() == e.ENTER){    
33304             return;
33305         }
33306         if(this.cancelOnEsc && e.getKey() == e.ESC){
33307             this.cancelEdit();
33308             return;
33309         } 
33310         this.fireEvent('specialkey', field, e);
33311     
33312     },
33313
33314     /**
33315      * Starts the editing process and shows the editor.
33316      * @param {String/HTMLElement/Element} el The element to edit
33317      * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
33318       * to the innerHTML of el.
33319      */
33320     startEdit : function(el, value){
33321         if(this.editing){
33322             this.completeEdit();
33323         }
33324         this.boundEl = Roo.get(el);
33325         var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
33326         if(!this.rendered){
33327             this.render(this.parentEl || document.body);
33328         }
33329         if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
33330             return;
33331         }
33332         this.startValue = v;
33333         this.field.setValue(v);
33334         if(this.autoSize){
33335             var sz = this.boundEl.getSize();
33336             switch(this.autoSize){
33337                 case "width":
33338                 this.setSize(sz.width,  "");
33339                 break;
33340                 case "height":
33341                 this.setSize("",  sz.height);
33342                 break;
33343                 default:
33344                 this.setSize(sz.width,  sz.height);
33345             }
33346         }
33347         this.el.alignTo(this.boundEl, this.alignment);
33348         this.editing = true;
33349         if(Roo.QuickTips){
33350             Roo.QuickTips.disable();
33351         }
33352         this.show();
33353     },
33354
33355     /**
33356      * Sets the height and width of this editor.
33357      * @param {Number} width The new width
33358      * @param {Number} height The new height
33359      */
33360     setSize : function(w, h){
33361         this.field.setSize(w, h);
33362         if(this.el){
33363             this.el.sync();
33364         }
33365     },
33366
33367     /**
33368      * Realigns the editor to the bound field based on the current alignment config value.
33369      */
33370     realign : function(){
33371         this.el.alignTo(this.boundEl, this.alignment);
33372     },
33373
33374     /**
33375      * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
33376      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
33377      */
33378     completeEdit : function(remainVisible){
33379         if(!this.editing){
33380             return;
33381         }
33382         var v = this.getValue();
33383         if(this.revertInvalid !== false && !this.field.isValid()){
33384             v = this.startValue;
33385             this.cancelEdit(true);
33386         }
33387         if(String(v) === String(this.startValue) && this.ignoreNoChange){
33388             this.editing = false;
33389             this.hide();
33390             return;
33391         }
33392         if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
33393             this.editing = false;
33394             if(this.updateEl && this.boundEl){
33395                 this.boundEl.update(v);
33396             }
33397             if(remainVisible !== true){
33398                 this.hide();
33399             }
33400             this.fireEvent("complete", this, v, this.startValue);
33401         }
33402     },
33403
33404     // private
33405     onShow : function(){
33406         this.el.show();
33407         if(this.hideEl !== false){
33408             this.boundEl.hide();
33409         }
33410         this.field.show();
33411         if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
33412             this.fixIEFocus = true;
33413             this.deferredFocus.defer(50, this);
33414         }else{
33415             this.field.focus();
33416         }
33417         this.fireEvent("startedit", this.boundEl, this.startValue);
33418     },
33419
33420     deferredFocus : function(){
33421         if(this.editing){
33422             this.field.focus();
33423         }
33424     },
33425
33426     /**
33427      * Cancels the editing process and hides the editor without persisting any changes.  The field value will be
33428      * reverted to the original starting value.
33429      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
33430      * cancel (defaults to false)
33431      */
33432     cancelEdit : function(remainVisible){
33433         if(this.editing){
33434             this.setValue(this.startValue);
33435             if(remainVisible !== true){
33436                 this.hide();
33437             }
33438         }
33439     },
33440
33441     // private
33442     onBlur : function(){
33443         if(this.allowBlur !== true && this.editing){
33444             this.completeEdit();
33445         }
33446     },
33447
33448     // private
33449     onHide : function(){
33450         if(this.editing){
33451             this.completeEdit();
33452             return;
33453         }
33454         this.field.blur();
33455         if(this.field.collapse){
33456             this.field.collapse();
33457         }
33458         this.el.hide();
33459         if(this.hideEl !== false){
33460             this.boundEl.show();
33461         }
33462         if(Roo.QuickTips){
33463             Roo.QuickTips.enable();
33464         }
33465     },
33466
33467     /**
33468      * Sets the data value of the editor
33469      * @param {Mixed} value Any valid value supported by the underlying field
33470      */
33471     setValue : function(v){
33472         this.field.setValue(v);
33473     },
33474
33475     /**
33476      * Gets the data value of the editor
33477      * @return {Mixed} The data value
33478      */
33479     getValue : function(){
33480         return this.field.getValue();
33481     }
33482 });/*
33483  * Based on:
33484  * Ext JS Library 1.1.1
33485  * Copyright(c) 2006-2007, Ext JS, LLC.
33486  *
33487  * Originally Released Under LGPL - original licence link has changed is not relivant.
33488  *
33489  * Fork - LGPL
33490  * <script type="text/javascript">
33491  */
33492  
33493 /**
33494  * @class Roo.BasicDialog
33495  * @extends Roo.util.Observable
33496  * @parent none builder
33497  * Lightweight Dialog Class.  The code below shows the creation of a typical dialog using existing HTML markup:
33498  * <pre><code>
33499 var dlg = new Roo.BasicDialog("my-dlg", {
33500     height: 200,
33501     width: 300,
33502     minHeight: 100,
33503     minWidth: 150,
33504     modal: true,
33505     proxyDrag: true,
33506     shadow: true
33507 });
33508 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
33509 dlg.addButton('OK', dlg.hide, dlg);    // Could call a save function instead of hiding
33510 dlg.addButton('Cancel', dlg.hide, dlg);
33511 dlg.show();
33512 </code></pre>
33513   <b>A Dialog should always be a direct child of the body element.</b>
33514  * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
33515  * @cfg {String} title Default text to display in the title bar (defaults to null)
33516  * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS).  Determined by browser if unspecified.
33517  * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS).  Determined by browser if unspecified.
33518  * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
33519  * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
33520  * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
33521  * (defaults to null with no animation)
33522  * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
33523  * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
33524  * property for valid values (defaults to 'all')
33525  * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
33526  * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
33527  * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
33528  * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
33529  * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
33530  * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
33531  * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
33532  * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
33533  * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
33534  * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
33535  * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
33536  * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
33537  * draggable = true (defaults to false)
33538  * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
33539  * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
33540  * shadow (defaults to false)
33541  * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
33542  * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
33543  * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
33544  * @cfg {Array} buttons Array of buttons
33545  * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
33546  * @constructor
33547  * Create a new BasicDialog.
33548  * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
33549  * @param {Object} config Configuration options
33550  */
33551 Roo.BasicDialog = function(el, config){
33552     this.el = Roo.get(el);
33553     var dh = Roo.DomHelper;
33554     if(!this.el && config && config.autoCreate){
33555         if(typeof config.autoCreate == "object"){
33556             if(!config.autoCreate.id){
33557                 config.autoCreate.id = el;
33558             }
33559             this.el = dh.append(document.body,
33560                         config.autoCreate, true);
33561         }else{
33562             this.el = dh.append(document.body,
33563                         {tag: "div", id: el, style:'visibility:hidden;'}, true);
33564         }
33565     }
33566     el = this.el;
33567     el.setDisplayed(true);
33568     el.hide = this.hideAction;
33569     this.id = el.id;
33570     el.addClass("x-dlg");
33571
33572     Roo.apply(this, config);
33573
33574     this.proxy = el.createProxy("x-dlg-proxy");
33575     this.proxy.hide = this.hideAction;
33576     this.proxy.setOpacity(.5);
33577     this.proxy.hide();
33578
33579     if(config.width){
33580         el.setWidth(config.width);
33581     }
33582     if(config.height){
33583         el.setHeight(config.height);
33584     }
33585     this.size = el.getSize();
33586     if(typeof config.x != "undefined" && typeof config.y != "undefined"){
33587         this.xy = [config.x,config.y];
33588     }else{
33589         this.xy = el.getCenterXY(true);
33590     }
33591     /** The header element @type Roo.Element */
33592     this.header = el.child("> .x-dlg-hd");
33593     /** The body element @type Roo.Element */
33594     this.body = el.child("> .x-dlg-bd");
33595     /** The footer element @type Roo.Element */
33596     this.footer = el.child("> .x-dlg-ft");
33597
33598     if(!this.header){
33599         this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: "&#160;"}, this.body ? this.body.dom : null);
33600     }
33601     if(!this.body){
33602         this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
33603     }
33604
33605     this.header.unselectable();
33606     if(this.title){
33607         this.header.update(this.title);
33608     }
33609     // this element allows the dialog to be focused for keyboard event
33610     this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
33611     this.focusEl.swallowEvent("click", true);
33612
33613     this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
33614
33615     // wrap the body and footer for special rendering
33616     this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
33617     if(this.footer){
33618         this.bwrap.dom.appendChild(this.footer.dom);
33619     }
33620
33621     this.bg = this.el.createChild({
33622         tag: "div", cls:"x-dlg-bg",
33623         html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center">&#160;</div></div></div>'
33624     });
33625     this.centerBg = this.bg.child("div.x-dlg-bg-center");
33626
33627
33628     if(this.autoScroll !== false && !this.autoTabs){
33629         this.body.setStyle("overflow", "auto");
33630     }
33631
33632     this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
33633
33634     if(this.closable !== false){
33635         this.el.addClass("x-dlg-closable");
33636         this.close = this.toolbox.createChild({cls:"x-dlg-close"});
33637         this.close.on("click", this.closeClick, this);
33638         this.close.addClassOnOver("x-dlg-close-over");
33639     }
33640     if(this.collapsible !== false){
33641         this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
33642         this.collapseBtn.on("click", this.collapseClick, this);
33643         this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
33644         this.header.on("dblclick", this.collapseClick, this);
33645     }
33646     if(this.resizable !== false){
33647         this.el.addClass("x-dlg-resizable");
33648         this.resizer = new Roo.Resizable(el, {
33649             minWidth: this.minWidth || 80,
33650             minHeight:this.minHeight || 80,
33651             handles: this.resizeHandles || "all",
33652             pinned: true
33653         });
33654         this.resizer.on("beforeresize", this.beforeResize, this);
33655         this.resizer.on("resize", this.onResize, this);
33656     }
33657     if(this.draggable !== false){
33658         el.addClass("x-dlg-draggable");
33659         if (!this.proxyDrag) {
33660             var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
33661         }
33662         else {
33663             var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
33664         }
33665         dd.setHandleElId(this.header.id);
33666         dd.endDrag = this.endMove.createDelegate(this);
33667         dd.startDrag = this.startMove.createDelegate(this);
33668         dd.onDrag = this.onDrag.createDelegate(this);
33669         dd.scroll = false;
33670         this.dd = dd;
33671     }
33672     if(this.modal){
33673         this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
33674         this.mask.enableDisplayMode("block");
33675         this.mask.hide();
33676         this.el.addClass("x-dlg-modal");
33677     }
33678     if(this.shadow){
33679         this.shadow = new Roo.Shadow({
33680             mode : typeof this.shadow == "string" ? this.shadow : "sides",
33681             offset : this.shadowOffset
33682         });
33683     }else{
33684         this.shadowOffset = 0;
33685     }
33686     if(Roo.useShims && this.shim !== false){
33687         this.shim = this.el.createShim();
33688         this.shim.hide = this.hideAction;
33689         this.shim.hide();
33690     }else{
33691         this.shim = false;
33692     }
33693     if(this.autoTabs){
33694         this.initTabs();
33695     }
33696     if (this.buttons) { 
33697         var bts= this.buttons;
33698         this.buttons = [];
33699         Roo.each(bts, function(b) {
33700             this.addButton(b);
33701         }, this);
33702     }
33703     
33704     
33705     this.addEvents({
33706         /**
33707          * @event keydown
33708          * Fires when a key is pressed
33709          * @param {Roo.BasicDialog} this
33710          * @param {Roo.EventObject} e
33711          */
33712         "keydown" : true,
33713         /**
33714          * @event move
33715          * Fires when this dialog is moved by the user.
33716          * @param {Roo.BasicDialog} this
33717          * @param {Number} x The new page X
33718          * @param {Number} y The new page Y
33719          */
33720         "move" : true,
33721         /**
33722          * @event resize
33723          * Fires when this dialog is resized by the user.
33724          * @param {Roo.BasicDialog} this
33725          * @param {Number} width The new width
33726          * @param {Number} height The new height
33727          */
33728         "resize" : true,
33729         /**
33730          * @event beforehide
33731          * Fires before this dialog is hidden.
33732          * @param {Roo.BasicDialog} this
33733          */
33734         "beforehide" : true,
33735         /**
33736          * @event hide
33737          * Fires when this dialog is hidden.
33738          * @param {Roo.BasicDialog} this
33739          */
33740         "hide" : true,
33741         /**
33742          * @event beforeshow
33743          * Fires before this dialog is shown.
33744          * @param {Roo.BasicDialog} this
33745          */
33746         "beforeshow" : true,
33747         /**
33748          * @event show
33749          * Fires when this dialog is shown.
33750          * @param {Roo.BasicDialog} this
33751          */
33752         "show" : true
33753     });
33754     el.on("keydown", this.onKeyDown, this);
33755     el.on("mousedown", this.toFront, this);
33756     Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
33757     this.el.hide();
33758     Roo.DialogManager.register(this);
33759     Roo.BasicDialog.superclass.constructor.call(this);
33760 };
33761
33762 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
33763     shadowOffset: Roo.isIE ? 6 : 5,
33764     minHeight: 80,
33765     minWidth: 200,
33766     minButtonWidth: 75,
33767     defaultButton: null,
33768     buttonAlign: "right",
33769     tabTag: 'div',
33770     firstShow: true,
33771
33772     /**
33773      * Sets the dialog title text
33774      * @param {String} text The title text to display
33775      * @return {Roo.BasicDialog} this
33776      */
33777     setTitle : function(text){
33778         this.header.update(text);
33779         return this;
33780     },
33781
33782     // private
33783     closeClick : function(){
33784         this.hide();
33785     },
33786
33787     // private
33788     collapseClick : function(){
33789         this[this.collapsed ? "expand" : "collapse"]();
33790     },
33791
33792     /**
33793      * Collapses the dialog to its minimized state (only the title bar is visible).
33794      * Equivalent to the user clicking the collapse dialog button.
33795      */
33796     collapse : function(){
33797         if(!this.collapsed){
33798             this.collapsed = true;
33799             this.el.addClass("x-dlg-collapsed");
33800             this.restoreHeight = this.el.getHeight();
33801             this.resizeTo(this.el.getWidth(), this.header.getHeight());
33802         }
33803     },
33804
33805     /**
33806      * Expands a collapsed dialog back to its normal state.  Equivalent to the user
33807      * clicking the expand dialog button.
33808      */
33809     expand : function(){
33810         if(this.collapsed){
33811             this.collapsed = false;
33812             this.el.removeClass("x-dlg-collapsed");
33813             this.resizeTo(this.el.getWidth(), this.restoreHeight);
33814         }
33815     },
33816
33817     /**
33818      * Reinitializes the tabs component, clearing out old tabs and finding new ones.
33819      * @return {Roo.TabPanel} The tabs component
33820      */
33821     initTabs : function(){
33822         var tabs = this.getTabs();
33823         while(tabs.getTab(0)){
33824             tabs.removeTab(0);
33825         }
33826         this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
33827             var dom = el.dom;
33828             tabs.addTab(Roo.id(dom), dom.title);
33829             dom.title = "";
33830         });
33831         tabs.activate(0);
33832         return tabs;
33833     },
33834
33835     // private
33836     beforeResize : function(){
33837         this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
33838     },
33839
33840     // private
33841     onResize : function(){
33842         this.refreshSize();
33843         this.syncBodyHeight();
33844         this.adjustAssets();
33845         this.focus();
33846         this.fireEvent("resize", this, this.size.width, this.size.height);
33847     },
33848
33849     // private
33850     onKeyDown : function(e){
33851         if(this.isVisible()){
33852             this.fireEvent("keydown", this, e);
33853         }
33854     },
33855
33856     /**
33857      * Resizes the dialog.
33858      * @param {Number} width
33859      * @param {Number} height
33860      * @return {Roo.BasicDialog} this
33861      */
33862     resizeTo : function(width, height){
33863         this.el.setSize(width, height);
33864         this.size = {width: width, height: height};
33865         this.syncBodyHeight();
33866         if(this.fixedcenter){
33867             this.center();
33868         }
33869         if(this.isVisible()){
33870             this.constrainXY();
33871             this.adjustAssets();
33872         }
33873         this.fireEvent("resize", this, width, height);
33874         return this;
33875     },
33876
33877
33878     /**
33879      * Resizes the dialog to fit the specified content size.
33880      * @param {Number} width
33881      * @param {Number} height
33882      * @return {Roo.BasicDialog} this
33883      */
33884     setContentSize : function(w, h){
33885         h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
33886         w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
33887         //if(!this.el.isBorderBox()){
33888             h +=  this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
33889             w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
33890         //}
33891         if(this.tabs){
33892             h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
33893             w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
33894         }
33895         this.resizeTo(w, h);
33896         return this;
33897     },
33898
33899     /**
33900      * Adds a key listener for when this dialog is displayed.  This allows you to hook in a function that will be
33901      * executed in response to a particular key being pressed while the dialog is active.
33902      * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
33903      *                                  {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
33904      * @param {Function} fn The function to call
33905      * @param {Object} scope (optional) The scope of the function
33906      * @return {Roo.BasicDialog} this
33907      */
33908     addKeyListener : function(key, fn, scope){
33909         var keyCode, shift, ctrl, alt;
33910         if(typeof key == "object" && !(key instanceof Array)){
33911             keyCode = key["key"];
33912             shift = key["shift"];
33913             ctrl = key["ctrl"];
33914             alt = key["alt"];
33915         }else{
33916             keyCode = key;
33917         }
33918         var handler = function(dlg, e){
33919             if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) &&  (!alt || e.altKey)){
33920                 var k = e.getKey();
33921                 if(keyCode instanceof Array){
33922                     for(var i = 0, len = keyCode.length; i < len; i++){
33923                         if(keyCode[i] == k){
33924                           fn.call(scope || window, dlg, k, e);
33925                           return;
33926                         }
33927                     }
33928                 }else{
33929                     if(k == keyCode){
33930                         fn.call(scope || window, dlg, k, e);
33931                     }
33932                 }
33933             }
33934         };
33935         this.on("keydown", handler);
33936         return this;
33937     },
33938
33939     /**
33940      * Returns the TabPanel component (creates it if it doesn't exist).
33941      * Note: If you wish to simply check for the existence of tabs without creating them,
33942      * check for a null 'tabs' property.
33943      * @return {Roo.TabPanel} The tabs component
33944      */
33945     getTabs : function(){
33946         if(!this.tabs){
33947             this.el.addClass("x-dlg-auto-tabs");
33948             this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
33949             this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
33950         }
33951         return this.tabs;
33952     },
33953
33954     /**
33955      * Adds a button to the footer section of the dialog.
33956      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
33957      * object or a valid Roo.DomHelper element config
33958      * @param {Function} handler The function called when the button is clicked
33959      * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
33960      * @return {Roo.Button} The new button
33961      */
33962     addButton : function(config, handler, scope){
33963         var dh = Roo.DomHelper;
33964         if(!this.footer){
33965             this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
33966         }
33967         if(!this.btnContainer){
33968             var tb = this.footer.createChild({
33969
33970                 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
33971                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
33972             }, null, true);
33973             this.btnContainer = tb.firstChild.firstChild.firstChild;
33974         }
33975         var bconfig = {
33976             handler: handler,
33977             scope: scope,
33978             minWidth: this.minButtonWidth,
33979             hideParent:true
33980         };
33981         if(typeof config == "string"){
33982             bconfig.text = config;
33983         }else{
33984             if(config.tag){
33985                 bconfig.dhconfig = config;
33986             }else{
33987                 Roo.apply(bconfig, config);
33988             }
33989         }
33990         var fc = false;
33991         if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
33992             bconfig.position = Math.max(0, bconfig.position);
33993             fc = this.btnContainer.childNodes[bconfig.position];
33994         }
33995          
33996         var btn = new Roo.Button(
33997             fc ? 
33998                 this.btnContainer.insertBefore(document.createElement("td"),fc)
33999                 : this.btnContainer.appendChild(document.createElement("td")),
34000             //Roo.get(this.btnContainer).createChild( { tag: 'td'},  fc ),
34001             bconfig
34002         );
34003         this.syncBodyHeight();
34004         if(!this.buttons){
34005             /**
34006              * Array of all the buttons that have been added to this dialog via addButton
34007              * @type Array
34008              */
34009             this.buttons = [];
34010         }
34011         this.buttons.push(btn);
34012         return btn;
34013     },
34014
34015     /**
34016      * Sets the default button to be focused when the dialog is displayed.
34017      * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
34018      * @return {Roo.BasicDialog} this
34019      */
34020     setDefaultButton : function(btn){
34021         this.defaultButton = btn;
34022         return this;
34023     },
34024
34025     // private
34026     getHeaderFooterHeight : function(safe){
34027         var height = 0;
34028         if(this.header){
34029            height += this.header.getHeight();
34030         }
34031         if(this.footer){
34032            var fm = this.footer.getMargins();
34033             height += (this.footer.getHeight()+fm.top+fm.bottom);
34034         }
34035         height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
34036         height += this.centerBg.getPadding("tb");
34037         return height;
34038     },
34039
34040     // private
34041     syncBodyHeight : function()
34042     {
34043         var bd = this.body, // the text
34044             cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
34045             bw = this.bwrap;
34046         var height = this.size.height - this.getHeaderFooterHeight(false);
34047         bd.setHeight(height-bd.getMargins("tb"));
34048         var hh = this.header.getHeight();
34049         var h = this.size.height-hh;
34050         cb.setHeight(h);
34051         
34052         bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
34053         bw.setHeight(h-cb.getPadding("tb"));
34054         
34055         bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
34056         bd.setWidth(bw.getWidth(true));
34057         if(this.tabs){
34058             this.tabs.syncHeight();
34059             if(Roo.isIE){
34060                 this.tabs.el.repaint();
34061             }
34062         }
34063     },
34064
34065     /**
34066      * Restores the previous state of the dialog if Roo.state is configured.
34067      * @return {Roo.BasicDialog} this
34068      */
34069     restoreState : function(){
34070         var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
34071         if(box && box.width){
34072             this.xy = [box.x, box.y];
34073             this.resizeTo(box.width, box.height);
34074         }
34075         return this;
34076     },
34077
34078     // private
34079     beforeShow : function(){
34080         this.expand();
34081         if(this.fixedcenter){
34082             this.xy = this.el.getCenterXY(true);
34083         }
34084         if(this.modal){
34085             Roo.get(document.body).addClass("x-body-masked");
34086             this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
34087             this.mask.show();
34088         }
34089         this.constrainXY();
34090     },
34091
34092     // private
34093     animShow : function(){
34094         var b = Roo.get(this.animateTarget).getBox();
34095         this.proxy.setSize(b.width, b.height);
34096         this.proxy.setLocation(b.x, b.y);
34097         this.proxy.show();
34098         this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
34099                     true, .35, this.showEl.createDelegate(this));
34100     },
34101
34102     /**
34103      * Shows the dialog.
34104      * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
34105      * @return {Roo.BasicDialog} this
34106      */
34107     show : function(animateTarget){
34108         if (this.fireEvent("beforeshow", this) === false){
34109             return;
34110         }
34111         if(this.syncHeightBeforeShow){
34112             this.syncBodyHeight();
34113         }else if(this.firstShow){
34114             this.firstShow = false;
34115             this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
34116         }
34117         this.animateTarget = animateTarget || this.animateTarget;
34118         if(!this.el.isVisible()){
34119             this.beforeShow();
34120             if(this.animateTarget && Roo.get(this.animateTarget)){
34121                 this.animShow();
34122             }else{
34123                 this.showEl();
34124             }
34125         }
34126         return this;
34127     },
34128
34129     // private
34130     showEl : function(){
34131         this.proxy.hide();
34132         this.el.setXY(this.xy);
34133         this.el.show();
34134         this.adjustAssets(true);
34135         this.toFront();
34136         this.focus();
34137         // IE peekaboo bug - fix found by Dave Fenwick
34138         if(Roo.isIE){
34139             this.el.repaint();
34140         }
34141         this.fireEvent("show", this);
34142     },
34143
34144     /**
34145      * Focuses the dialog.  If a defaultButton is set, it will receive focus, otherwise the
34146      * dialog itself will receive focus.
34147      */
34148     focus : function(){
34149         if(this.defaultButton){
34150             this.defaultButton.focus();
34151         }else{
34152             this.focusEl.focus();
34153         }
34154     },
34155
34156     // private
34157     constrainXY : function(){
34158         if(this.constraintoviewport !== false){
34159             if(!this.viewSize){
34160                 if(this.container){
34161                     var s = this.container.getSize();
34162                     this.viewSize = [s.width, s.height];
34163                 }else{
34164                     this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
34165                 }
34166             }
34167             var s = Roo.get(this.container||document).getScroll();
34168
34169             var x = this.xy[0], y = this.xy[1];
34170             var w = this.size.width, h = this.size.height;
34171             var vw = this.viewSize[0], vh = this.viewSize[1];
34172             // only move it if it needs it
34173             var moved = false;
34174             // first validate right/bottom
34175             if(x + w > vw+s.left){
34176                 x = vw - w;
34177                 moved = true;
34178             }
34179             if(y + h > vh+s.top){
34180                 y = vh - h;
34181                 moved = true;
34182             }
34183             // then make sure top/left isn't negative
34184             if(x < s.left){
34185                 x = s.left;
34186                 moved = true;
34187             }
34188             if(y < s.top){
34189                 y = s.top;
34190                 moved = true;
34191             }
34192             if(moved){
34193                 // cache xy
34194                 this.xy = [x, y];
34195                 if(this.isVisible()){
34196                     this.el.setLocation(x, y);
34197                     this.adjustAssets();
34198                 }
34199             }
34200         }
34201     },
34202
34203     // private
34204     onDrag : function(){
34205         if(!this.proxyDrag){
34206             this.xy = this.el.getXY();
34207             this.adjustAssets();
34208         }
34209     },
34210
34211     // private
34212     adjustAssets : function(doShow){
34213         var x = this.xy[0], y = this.xy[1];
34214         var w = this.size.width, h = this.size.height;
34215         if(doShow === true){
34216             if(this.shadow){
34217                 this.shadow.show(this.el);
34218             }
34219             if(this.shim){
34220                 this.shim.show();
34221             }
34222         }
34223         if(this.shadow && this.shadow.isVisible()){
34224             this.shadow.show(this.el);
34225         }
34226         if(this.shim && this.shim.isVisible()){
34227             this.shim.setBounds(x, y, w, h);
34228         }
34229     },
34230
34231     // private
34232     adjustViewport : function(w, h){
34233         if(!w || !h){
34234             w = Roo.lib.Dom.getViewWidth();
34235             h = Roo.lib.Dom.getViewHeight();
34236         }
34237         // cache the size
34238         this.viewSize = [w, h];
34239         if(this.modal && this.mask.isVisible()){
34240             this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
34241             this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
34242         }
34243         if(this.isVisible()){
34244             this.constrainXY();
34245         }
34246     },
34247
34248     /**
34249      * Destroys this dialog and all its supporting elements (including any tabs, shim,
34250      * shadow, proxy, mask, etc.)  Also removes all event listeners.
34251      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
34252      */
34253     destroy : function(removeEl){
34254         if(this.isVisible()){
34255             this.animateTarget = null;
34256             this.hide();
34257         }
34258         Roo.EventManager.removeResizeListener(this.adjustViewport, this);
34259         if(this.tabs){
34260             this.tabs.destroy(removeEl);
34261         }
34262         Roo.destroy(
34263              this.shim,
34264              this.proxy,
34265              this.resizer,
34266              this.close,
34267              this.mask
34268         );
34269         if(this.dd){
34270             this.dd.unreg();
34271         }
34272         if(this.buttons){
34273            for(var i = 0, len = this.buttons.length; i < len; i++){
34274                this.buttons[i].destroy();
34275            }
34276         }
34277         this.el.removeAllListeners();
34278         if(removeEl === true){
34279             this.el.update("");
34280             this.el.remove();
34281         }
34282         Roo.DialogManager.unregister(this);
34283     },
34284
34285     // private
34286     startMove : function(){
34287         if(this.proxyDrag){
34288             this.proxy.show();
34289         }
34290         if(this.constraintoviewport !== false){
34291             this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
34292         }
34293     },
34294
34295     // private
34296     endMove : function(){
34297         if(!this.proxyDrag){
34298             Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
34299         }else{
34300             Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
34301             this.proxy.hide();
34302         }
34303         this.refreshSize();
34304         this.adjustAssets();
34305         this.focus();
34306         this.fireEvent("move", this, this.xy[0], this.xy[1]);
34307     },
34308
34309     /**
34310      * Brings this dialog to the front of any other visible dialogs
34311      * @return {Roo.BasicDialog} this
34312      */
34313     toFront : function(){
34314         Roo.DialogManager.bringToFront(this);
34315         return this;
34316     },
34317
34318     /**
34319      * Sends this dialog to the back (under) of any other visible dialogs
34320      * @return {Roo.BasicDialog} this
34321      */
34322     toBack : function(){
34323         Roo.DialogManager.sendToBack(this);
34324         return this;
34325     },
34326
34327     /**
34328      * Centers this dialog in the viewport
34329      * @return {Roo.BasicDialog} this
34330      */
34331     center : function(){
34332         var xy = this.el.getCenterXY(true);
34333         this.moveTo(xy[0], xy[1]);
34334         return this;
34335     },
34336
34337     /**
34338      * Moves the dialog's top-left corner to the specified point
34339      * @param {Number} x
34340      * @param {Number} y
34341      * @return {Roo.BasicDialog} this
34342      */
34343     moveTo : function(x, y){
34344         this.xy = [x,y];
34345         if(this.isVisible()){
34346             this.el.setXY(this.xy);
34347             this.adjustAssets();
34348         }
34349         return this;
34350     },
34351
34352     /**
34353      * Aligns the dialog to the specified element
34354      * @param {String/HTMLElement/Roo.Element} element The element to align to.
34355      * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
34356      * @param {Array} offsets (optional) Offset the positioning by [x, y]
34357      * @return {Roo.BasicDialog} this
34358      */
34359     alignTo : function(element, position, offsets){
34360         this.xy = this.el.getAlignToXY(element, position, offsets);
34361         if(this.isVisible()){
34362             this.el.setXY(this.xy);
34363             this.adjustAssets();
34364         }
34365         return this;
34366     },
34367
34368     /**
34369      * Anchors an element to another element and realigns it when the window is resized.
34370      * @param {String/HTMLElement/Roo.Element} element The element to align to.
34371      * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
34372      * @param {Array} offsets (optional) Offset the positioning by [x, y]
34373      * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
34374      * is a number, it is used as the buffer delay (defaults to 50ms).
34375      * @return {Roo.BasicDialog} this
34376      */
34377     anchorTo : function(el, alignment, offsets, monitorScroll){
34378         var action = function(){
34379             this.alignTo(el, alignment, offsets);
34380         };
34381         Roo.EventManager.onWindowResize(action, this);
34382         var tm = typeof monitorScroll;
34383         if(tm != 'undefined'){
34384             Roo.EventManager.on(window, 'scroll', action, this,
34385                 {buffer: tm == 'number' ? monitorScroll : 50});
34386         }
34387         action.call(this);
34388         return this;
34389     },
34390
34391     /**
34392      * Returns true if the dialog is visible
34393      * @return {Boolean}
34394      */
34395     isVisible : function(){
34396         return this.el.isVisible();
34397     },
34398
34399     // private
34400     animHide : function(callback){
34401         var b = Roo.get(this.animateTarget).getBox();
34402         this.proxy.show();
34403         this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
34404         this.el.hide();
34405         this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
34406                     this.hideEl.createDelegate(this, [callback]));
34407     },
34408
34409     /**
34410      * Hides the dialog.
34411      * @param {Function} callback (optional) Function to call when the dialog is hidden
34412      * @return {Roo.BasicDialog} this
34413      */
34414     hide : function(callback){
34415         if (this.fireEvent("beforehide", this) === false){
34416             return;
34417         }
34418         if(this.shadow){
34419             this.shadow.hide();
34420         }
34421         if(this.shim) {
34422           this.shim.hide();
34423         }
34424         // sometimes animateTarget seems to get set.. causing problems...
34425         // this just double checks..
34426         if(this.animateTarget && Roo.get(this.animateTarget)) {
34427            this.animHide(callback);
34428         }else{
34429             this.el.hide();
34430             this.hideEl(callback);
34431         }
34432         return this;
34433     },
34434
34435     // private
34436     hideEl : function(callback){
34437         this.proxy.hide();
34438         if(this.modal){
34439             this.mask.hide();
34440             Roo.get(document.body).removeClass("x-body-masked");
34441         }
34442         this.fireEvent("hide", this);
34443         if(typeof callback == "function"){
34444             callback();
34445         }
34446     },
34447
34448     // private
34449     hideAction : function(){
34450         this.setLeft("-10000px");
34451         this.setTop("-10000px");
34452         this.setStyle("visibility", "hidden");
34453     },
34454
34455     // private
34456     refreshSize : function(){
34457         this.size = this.el.getSize();
34458         this.xy = this.el.getXY();
34459         Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
34460     },
34461
34462     // private
34463     // z-index is managed by the DialogManager and may be overwritten at any time
34464     setZIndex : function(index){
34465         if(this.modal){
34466             this.mask.setStyle("z-index", index);
34467         }
34468         if(this.shim){
34469             this.shim.setStyle("z-index", ++index);
34470         }
34471         if(this.shadow){
34472             this.shadow.setZIndex(++index);
34473         }
34474         this.el.setStyle("z-index", ++index);
34475         if(this.proxy){
34476             this.proxy.setStyle("z-index", ++index);
34477         }
34478         if(this.resizer){
34479             this.resizer.proxy.setStyle("z-index", ++index);
34480         }
34481
34482         this.lastZIndex = index;
34483     },
34484
34485     /**
34486      * Returns the element for this dialog
34487      * @return {Roo.Element} The underlying dialog Element
34488      */
34489     getEl : function(){
34490         return this.el;
34491     }
34492 });
34493
34494 /**
34495  * @class Roo.DialogManager
34496  * Provides global access to BasicDialogs that have been created and
34497  * support for z-indexing (layering) multiple open dialogs.
34498  */
34499 Roo.DialogManager = function(){
34500     var list = {};
34501     var accessList = [];
34502     var front = null;
34503
34504     // private
34505     var sortDialogs = function(d1, d2){
34506         return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
34507     };
34508
34509     // private
34510     var orderDialogs = function(){
34511         accessList.sort(sortDialogs);
34512         var seed = Roo.DialogManager.zseed;
34513         for(var i = 0, len = accessList.length; i < len; i++){
34514             var dlg = accessList[i];
34515             if(dlg){
34516                 dlg.setZIndex(seed + (i*10));
34517             }
34518         }
34519     };
34520
34521     return {
34522         /**
34523          * The starting z-index for BasicDialogs (defaults to 9000)
34524          * @type Number The z-index value
34525          */
34526         zseed : 9000,
34527
34528         // private
34529         register : function(dlg){
34530             list[dlg.id] = dlg;
34531             accessList.push(dlg);
34532         },
34533
34534         // private
34535         unregister : function(dlg){
34536             delete list[dlg.id];
34537             var i=0;
34538             var len=0;
34539             if(!accessList.indexOf){
34540                 for(  i = 0, len = accessList.length; i < len; i++){
34541                     if(accessList[i] == dlg){
34542                         accessList.splice(i, 1);
34543                         return;
34544                     }
34545                 }
34546             }else{
34547                  i = accessList.indexOf(dlg);
34548                 if(i != -1){
34549                     accessList.splice(i, 1);
34550                 }
34551             }
34552         },
34553
34554         /**
34555          * Gets a registered dialog by id
34556          * @param {String/Object} id The id of the dialog or a dialog
34557          * @return {Roo.BasicDialog} this
34558          */
34559         get : function(id){
34560             return typeof id == "object" ? id : list[id];
34561         },
34562
34563         /**
34564          * Brings the specified dialog to the front
34565          * @param {String/Object} dlg The id of the dialog or a dialog
34566          * @return {Roo.BasicDialog} this
34567          */
34568         bringToFront : function(dlg){
34569             dlg = this.get(dlg);
34570             if(dlg != front){
34571                 front = dlg;
34572                 dlg._lastAccess = new Date().getTime();
34573                 orderDialogs();
34574             }
34575             return dlg;
34576         },
34577
34578         /**
34579          * Sends the specified dialog to the back
34580          * @param {String/Object} dlg The id of the dialog or a dialog
34581          * @return {Roo.BasicDialog} this
34582          */
34583         sendToBack : function(dlg){
34584             dlg = this.get(dlg);
34585             dlg._lastAccess = -(new Date().getTime());
34586             orderDialogs();
34587             return dlg;
34588         },
34589
34590         /**
34591          * Hides all dialogs
34592          */
34593         hideAll : function(){
34594             for(var id in list){
34595                 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
34596                     list[id].hide();
34597                 }
34598             }
34599         }
34600     };
34601 }();
34602
34603 /**
34604  * @class Roo.LayoutDialog
34605  * @extends Roo.BasicDialog
34606  * @children Roo.ContentPanel
34607  * @parent builder none
34608  * Dialog which provides adjustments for working with a layout in a Dialog.
34609  * Add your necessary layout config options to the dialog's config.<br>
34610  * Example usage (including a nested layout):
34611  * <pre><code>
34612 if(!dialog){
34613     dialog = new Roo.LayoutDialog("download-dlg", {
34614         modal: true,
34615         width:600,
34616         height:450,
34617         shadow:true,
34618         minWidth:500,
34619         minHeight:350,
34620         autoTabs:true,
34621         proxyDrag:true,
34622         // layout config merges with the dialog config
34623         center:{
34624             tabPosition: "top",
34625             alwaysShowTabs: true
34626         }
34627     });
34628     dialog.addKeyListener(27, dialog.hide, dialog);
34629     dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
34630     dialog.addButton("Build It!", this.getDownload, this);
34631
34632     // we can even add nested layouts
34633     var innerLayout = new Roo.BorderLayout("dl-inner", {
34634         east: {
34635             initialSize: 200,
34636             autoScroll:true,
34637             split:true
34638         },
34639         center: {
34640             autoScroll:true
34641         }
34642     });
34643     innerLayout.beginUpdate();
34644     innerLayout.add("east", new Roo.ContentPanel("dl-details"));
34645     innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
34646     innerLayout.endUpdate(true);
34647
34648     var layout = dialog.getLayout();
34649     layout.beginUpdate();
34650     layout.add("center", new Roo.ContentPanel("standard-panel",
34651                         {title: "Download the Source", fitToFrame:true}));
34652     layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
34653                {title: "Build your own roo.js"}));
34654     layout.getRegion("center").showPanel(sp);
34655     layout.endUpdate();
34656 }
34657 </code></pre>
34658     * @constructor
34659     * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
34660     * @param {Object} config configuration options
34661   */
34662 Roo.LayoutDialog = function(el, cfg){
34663     
34664     var config=  cfg;
34665     if (typeof(cfg) == 'undefined') {
34666         config = Roo.apply({}, el);
34667         // not sure why we use documentElement here.. - it should always be body.
34668         // IE7 borks horribly if we use documentElement.
34669         // webkit also does not like documentElement - it creates a body element...
34670         el = Roo.get( document.body || document.documentElement ).createChild();
34671         //config.autoCreate = true;
34672     }
34673     
34674     
34675     config.autoTabs = false;
34676     Roo.LayoutDialog.superclass.constructor.call(this, el, config);
34677     this.body.setStyle({overflow:"hidden", position:"relative"});
34678     this.layout = new Roo.BorderLayout(this.body.dom, config);
34679     this.layout.monitorWindowResize = false;
34680     this.el.addClass("x-dlg-auto-layout");
34681     // fix case when center region overwrites center function
34682     this.center = Roo.BasicDialog.prototype.center;
34683     this.on("show", this.layout.layout, this.layout, true);
34684     if (config.items) {
34685         var xitems = config.items;
34686         delete config.items;
34687         Roo.each(xitems, this.addxtype, this);
34688     }
34689     
34690     
34691 };
34692 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
34693     
34694     
34695     /**
34696      * @cfg {Roo.LayoutRegion} east  
34697      */
34698     /**
34699      * @cfg {Roo.LayoutRegion} west
34700      */
34701     /**
34702      * @cfg {Roo.LayoutRegion} south
34703      */
34704     /**
34705      * @cfg {Roo.LayoutRegion} north
34706      */
34707     /**
34708      * @cfg {Roo.LayoutRegion} center
34709      */
34710     /**
34711      * @cfg {Roo.Button} buttons[]  Bottom buttons..
34712      */
34713     
34714     
34715     /**
34716      * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
34717      * @deprecated
34718      */
34719     endUpdate : function(){
34720         this.layout.endUpdate();
34721     },
34722
34723     /**
34724      * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
34725      *  @deprecated
34726      */
34727     beginUpdate : function(){
34728         this.layout.beginUpdate();
34729     },
34730
34731     /**
34732      * Get the BorderLayout for this dialog
34733      * @return {Roo.BorderLayout}
34734      */
34735     getLayout : function(){
34736         return this.layout;
34737     },
34738
34739     showEl : function(){
34740         Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
34741         if(Roo.isIE7){
34742             this.layout.layout();
34743         }
34744     },
34745
34746     // private
34747     // Use the syncHeightBeforeShow config option to control this automatically
34748     syncBodyHeight : function(){
34749         Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
34750         if(this.layout){this.layout.layout();}
34751     },
34752     
34753       /**
34754      * Add an xtype element (actually adds to the layout.)
34755      * @return {Object} xdata xtype object data.
34756      */
34757     
34758     addxtype : function(c) {
34759         return this.layout.addxtype(c);
34760     }
34761 });/*
34762  * Based on:
34763  * Ext JS Library 1.1.1
34764  * Copyright(c) 2006-2007, Ext JS, LLC.
34765  *
34766  * Originally Released Under LGPL - original licence link has changed is not relivant.
34767  *
34768  * Fork - LGPL
34769  * <script type="text/javascript">
34770  */
34771  
34772 /**
34773  * @class Roo.MessageBox
34774  * @static
34775  * Utility class for generating different styles of message boxes.  The alias Roo.Msg can also be used.
34776  * Example usage:
34777  *<pre><code>
34778 // Basic alert:
34779 Roo.Msg.alert('Status', 'Changes saved successfully.');
34780
34781 // Prompt for user data:
34782 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
34783     if (btn == 'ok'){
34784         // process text value...
34785     }
34786 });
34787
34788 // Show a dialog using config options:
34789 Roo.Msg.show({
34790    title:'Save Changes?',
34791    msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
34792    buttons: Roo.Msg.YESNOCANCEL,
34793    fn: processResult,
34794    animEl: 'elId'
34795 });
34796 </code></pre>
34797  * @static
34798  */
34799 Roo.MessageBox = function(){
34800     var dlg, opt, mask, waitTimer;
34801     var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
34802     var buttons, activeTextEl, bwidth;
34803
34804     // private
34805     var handleButton = function(button){
34806         dlg.hide();
34807         Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
34808     };
34809
34810     // private
34811     var handleHide = function(){
34812         if(opt && opt.cls){
34813             dlg.el.removeClass(opt.cls);
34814         }
34815         if(waitTimer){
34816             Roo.TaskMgr.stop(waitTimer);
34817             waitTimer = null;
34818         }
34819     };
34820
34821     // private
34822     var updateButtons = function(b){
34823         var width = 0;
34824         if(!b){
34825             buttons["ok"].hide();
34826             buttons["cancel"].hide();
34827             buttons["yes"].hide();
34828             buttons["no"].hide();
34829             dlg.footer.dom.style.display = 'none';
34830             return width;
34831         }
34832         dlg.footer.dom.style.display = '';
34833         for(var k in buttons){
34834             if(typeof buttons[k] != "function"){
34835                 if(b[k]){
34836                     buttons[k].show();
34837                     buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
34838                     width += buttons[k].el.getWidth()+15;
34839                 }else{
34840                     buttons[k].hide();
34841                 }
34842             }
34843         }
34844         return width;
34845     };
34846
34847     // private
34848     var handleEsc = function(d, k, e){
34849         if(opt && opt.closable !== false){
34850             dlg.hide();
34851         }
34852         if(e){
34853             e.stopEvent();
34854         }
34855     };
34856
34857     return {
34858         /**
34859          * Returns a reference to the underlying {@link Roo.BasicDialog} element
34860          * @return {Roo.BasicDialog} The BasicDialog element
34861          */
34862         getDialog : function(){
34863            if(!dlg){
34864                 dlg = new Roo.BasicDialog("x-msg-box", {
34865                     autoCreate : true,
34866                     shadow: true,
34867                     draggable: true,
34868                     resizable:false,
34869                     constraintoviewport:false,
34870                     fixedcenter:true,
34871                     collapsible : false,
34872                     shim:true,
34873                     modal: true,
34874                     width:400, height:100,
34875                     buttonAlign:"center",
34876                     closeClick : function(){
34877                         if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
34878                             handleButton("no");
34879                         }else{
34880                             handleButton("cancel");
34881                         }
34882                     }
34883                 });
34884                 dlg.on("hide", handleHide);
34885                 mask = dlg.mask;
34886                 dlg.addKeyListener(27, handleEsc);
34887                 buttons = {};
34888                 var bt = this.buttonText;
34889                 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
34890                 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
34891                 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
34892                 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
34893                 bodyEl = dlg.body.createChild({
34894
34895                     html:'<span class="roo-mb-text"></span><br /><input type="text" class="roo-mb-input" /><textarea class="roo-mb-textarea"></textarea><div class="roo-mb-progress-wrap"><div class="roo-mb-progress"><div class="roo-mb-progress-bar">&#160;</div></div></div>'
34896                 });
34897                 msgEl = bodyEl.dom.firstChild;
34898                 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
34899                 textboxEl.enableDisplayMode();
34900                 textboxEl.addKeyListener([10,13], function(){
34901                     if(dlg.isVisible() && opt && opt.buttons){
34902                         if(opt.buttons.ok){
34903                             handleButton("ok");
34904                         }else if(opt.buttons.yes){
34905                             handleButton("yes");
34906                         }
34907                     }
34908                 });
34909                 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
34910                 textareaEl.enableDisplayMode();
34911                 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
34912                 progressEl.enableDisplayMode();
34913                 var pf = progressEl.dom.firstChild;
34914                 if (pf) {
34915                     pp = Roo.get(pf.firstChild);
34916                     pp.setHeight(pf.offsetHeight);
34917                 }
34918                 
34919             }
34920             return dlg;
34921         },
34922
34923         /**
34924          * Updates the message box body text
34925          * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
34926          * the XHTML-compliant non-breaking space character '&amp;#160;')
34927          * @return {Roo.MessageBox} This message box
34928          */
34929         updateText : function(text){
34930             if(!dlg.isVisible() && !opt.width){
34931                 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
34932             }
34933             msgEl.innerHTML = text || '&#160;';
34934       
34935             var cw =  Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
34936             //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
34937             var w = Math.max(
34938                     Math.min(opt.width || cw , this.maxWidth), 
34939                     Math.max(opt.minWidth || this.minWidth, bwidth)
34940             );
34941             if(opt.prompt){
34942                 activeTextEl.setWidth(w);
34943             }
34944             if(dlg.isVisible()){
34945                 dlg.fixedcenter = false;
34946             }
34947             // to big, make it scroll. = But as usual stupid IE does not support
34948             // !important..
34949             
34950             if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
34951                 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
34952                 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
34953             } else {
34954                 bodyEl.dom.style.height = '';
34955                 bodyEl.dom.style.overflowY = '';
34956             }
34957             if (cw > w) {
34958                 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
34959             } else {
34960                 bodyEl.dom.style.overflowX = '';
34961             }
34962             
34963             dlg.setContentSize(w, bodyEl.getHeight());
34964             if(dlg.isVisible()){
34965                 dlg.fixedcenter = true;
34966             }
34967             return this;
34968         },
34969
34970         /**
34971          * Updates a progress-style message box's text and progress bar.  Only relevant on message boxes
34972          * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
34973          * @param {Number} value Any number between 0 and 1 (e.g., .5)
34974          * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
34975          * @return {Roo.MessageBox} This message box
34976          */
34977         updateProgress : function(value, text){
34978             if(text){
34979                 this.updateText(text);
34980             }
34981             if (pp) { // weird bug on my firefox - for some reason this is not defined
34982                 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
34983             }
34984             return this;
34985         },        
34986
34987         /**
34988          * Returns true if the message box is currently displayed
34989          * @return {Boolean} True if the message box is visible, else false
34990          */
34991         isVisible : function(){
34992             return dlg && dlg.isVisible();  
34993         },
34994
34995         /**
34996          * Hides the message box if it is displayed
34997          */
34998         hide : function(){
34999             if(this.isVisible()){
35000                 dlg.hide();
35001             }  
35002         },
35003
35004         /**
35005          * Displays a new message box, or reinitializes an existing message box, based on the config options
35006          * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
35007          * The following config object properties are supported:
35008          * <pre>
35009 Property    Type             Description
35010 ----------  ---------------  ------------------------------------------------------------------------------------
35011 animEl            String/Element   An id or Element from which the message box should animate as it opens and
35012                                    closes (defaults to undefined)
35013 buttons           Object/Boolean   A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
35014                                    cancel:'Bar'}), or false to not show any buttons (defaults to false)
35015 closable          Boolean          False to hide the top-right close button (defaults to true).  Note that
35016                                    progress and wait dialogs will ignore this property and always hide the
35017                                    close button as they can only be closed programmatically.
35018 cls               String           A custom CSS class to apply to the message box element
35019 defaultTextHeight Number           The default height in pixels of the message box's multiline textarea if
35020                                    displayed (defaults to 75)
35021 fn                Function         A callback function to execute after closing the dialog.  The arguments to the
35022                                    function will be btn (the name of the button that was clicked, if applicable,
35023                                    e.g. "ok"), and text (the value of the active text field, if applicable).
35024                                    Progress and wait dialogs will ignore this option since they do not respond to
35025                                    user actions and can only be closed programmatically, so any required function
35026                                    should be called by the same code after it closes the dialog.
35027 icon              String           A CSS class that provides a background image to be used as an icon for
35028                                    the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
35029 maxWidth          Number           The maximum width in pixels of the message box (defaults to 600)
35030 minWidth          Number           The minimum width in pixels of the message box (defaults to 100)
35031 modal             Boolean          False to allow user interaction with the page while the message box is
35032                                    displayed (defaults to true)
35033 msg               String           A string that will replace the existing message box body text (defaults
35034                                    to the XHTML-compliant non-breaking space character '&#160;')
35035 multiline         Boolean          True to prompt the user to enter multi-line text (defaults to false)
35036 progress          Boolean          True to display a progress bar (defaults to false)
35037 progressText      String           The text to display inside the progress bar if progress = true (defaults to '')
35038 prompt            Boolean          True to prompt the user to enter single-line text (defaults to false)
35039 proxyDrag         Boolean          True to display a lightweight proxy while dragging (defaults to false)
35040 title             String           The title text
35041 value             String           The string value to set into the active textbox element if displayed
35042 wait              Boolean          True to display a progress bar (defaults to false)
35043 width             Number           The width of the dialog in pixels
35044 </pre>
35045          *
35046          * Example usage:
35047          * <pre><code>
35048 Roo.Msg.show({
35049    title: 'Address',
35050    msg: 'Please enter your address:',
35051    width: 300,
35052    buttons: Roo.MessageBox.OKCANCEL,
35053    multiline: true,
35054    fn: saveAddress,
35055    animEl: 'addAddressBtn'
35056 });
35057 </code></pre>
35058          * @param {Object} config Configuration options
35059          * @return {Roo.MessageBox} This message box
35060          */
35061         show : function(options)
35062         {
35063             
35064             // this causes nightmares if you show one dialog after another
35065             // especially on callbacks..
35066              
35067             if(this.isVisible()){
35068                 
35069                 this.hide();
35070                 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
35071                 Roo.log("Old Dialog Message:" +  msgEl.innerHTML );
35072                 Roo.log("New Dialog Message:" +  options.msg )
35073                 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
35074                 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
35075                 
35076             }
35077             var d = this.getDialog();
35078             opt = options;
35079             d.setTitle(opt.title || "&#160;");
35080             d.close.setDisplayed(opt.closable !== false);
35081             activeTextEl = textboxEl;
35082             opt.prompt = opt.prompt || (opt.multiline ? true : false);
35083             if(opt.prompt){
35084                 if(opt.multiline){
35085                     textboxEl.hide();
35086                     textareaEl.show();
35087                     textareaEl.setHeight(typeof opt.multiline == "number" ?
35088                         opt.multiline : this.defaultTextHeight);
35089                     activeTextEl = textareaEl;
35090                 }else{
35091                     textboxEl.show();
35092                     textareaEl.hide();
35093                 }
35094             }else{
35095                 textboxEl.hide();
35096                 textareaEl.hide();
35097             }
35098             progressEl.setDisplayed(opt.progress === true);
35099             this.updateProgress(0);
35100             activeTextEl.dom.value = opt.value || "";
35101             if(opt.prompt){
35102                 dlg.setDefaultButton(activeTextEl);
35103             }else{
35104                 var bs = opt.buttons;
35105                 var db = null;
35106                 if(bs && bs.ok){
35107                     db = buttons["ok"];
35108                 }else if(bs && bs.yes){
35109                     db = buttons["yes"];
35110                 }
35111                 dlg.setDefaultButton(db);
35112             }
35113             bwidth = updateButtons(opt.buttons);
35114             this.updateText(opt.msg);
35115             if(opt.cls){
35116                 d.el.addClass(opt.cls);
35117             }
35118             d.proxyDrag = opt.proxyDrag === true;
35119             d.modal = opt.modal !== false;
35120             d.mask = opt.modal !== false ? mask : false;
35121             if(!d.isVisible()){
35122                 // force it to the end of the z-index stack so it gets a cursor in FF
35123                 document.body.appendChild(dlg.el.dom);
35124                 d.animateTarget = null;
35125                 d.show(options.animEl);
35126             }
35127             return this;
35128         },
35129
35130         /**
35131          * Displays a message box with a progress bar.  This message box has no buttons and is not closeable by
35132          * the user.  You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
35133          * and closing the message box when the process is complete.
35134          * @param {String} title The title bar text
35135          * @param {String} msg The message box body text
35136          * @return {Roo.MessageBox} This message box
35137          */
35138         progress : function(title, msg){
35139             this.show({
35140                 title : title,
35141                 msg : msg,
35142                 buttons: false,
35143                 progress:true,
35144                 closable:false,
35145                 minWidth: this.minProgressWidth,
35146                 modal : true
35147             });
35148             return this;
35149         },
35150
35151         /**
35152          * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
35153          * If a callback function is passed it will be called after the user clicks the button, and the
35154          * id of the button that was clicked will be passed as the only parameter to the callback
35155          * (could also be the top-right close button).
35156          * @param {String} title The title bar text
35157          * @param {String} msg The message box body text
35158          * @param {Function} fn (optional) The callback function invoked after the message box is closed
35159          * @param {Object} scope (optional) The scope of the callback function
35160          * @return {Roo.MessageBox} This message box
35161          */
35162         alert : function(title, msg, fn, scope){
35163             this.show({
35164                 title : title,
35165                 msg : msg,
35166                 buttons: this.OK,
35167                 fn: fn,
35168                 scope : scope,
35169                 modal : true
35170             });
35171             return this;
35172         },
35173
35174         /**
35175          * Displays a message box with an infinitely auto-updating progress bar.  This can be used to block user
35176          * interaction while waiting for a long-running process to complete that does not have defined intervals.
35177          * You are responsible for closing the message box when the process is complete.
35178          * @param {String} msg The message box body text
35179          * @param {String} title (optional) The title bar text
35180          * @return {Roo.MessageBox} This message box
35181          */
35182         wait : function(msg, title){
35183             this.show({
35184                 title : title,
35185                 msg : msg,
35186                 buttons: false,
35187                 closable:false,
35188                 progress:true,
35189                 modal:true,
35190                 width:300,
35191                 wait:true
35192             });
35193             waitTimer = Roo.TaskMgr.start({
35194                 run: function(i){
35195                     Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
35196                 },
35197                 interval: 1000
35198             });
35199             return this;
35200         },
35201
35202         /**
35203          * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
35204          * If a callback function is passed it will be called after the user clicks either button, and the id of the
35205          * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
35206          * @param {String} title The title bar text
35207          * @param {String} msg The message box body text
35208          * @param {Function} fn (optional) The callback function invoked after the message box is closed
35209          * @param {Object} scope (optional) The scope of the callback function
35210          * @return {Roo.MessageBox} This message box
35211          */
35212         confirm : function(title, msg, fn, scope){
35213             this.show({
35214                 title : title,
35215                 msg : msg,
35216                 buttons: this.YESNO,
35217                 fn: fn,
35218                 scope : scope,
35219                 modal : true
35220             });
35221             return this;
35222         },
35223
35224         /**
35225          * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
35226          * JavaScript's Window.prompt).  The prompt can be a single-line or multi-line textbox.  If a callback function
35227          * is passed it will be called after the user clicks either button, and the id of the button that was clicked
35228          * (could also be the top-right close button) and the text that was entered will be passed as the two
35229          * parameters to the callback.
35230          * @param {String} title The title bar text
35231          * @param {String} msg The message box body text
35232          * @param {Function} fn (optional) The callback function invoked after the message box is closed
35233          * @param {Object} scope (optional) The scope of the callback function
35234          * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
35235          * property, or the height in pixels to create the textbox (defaults to false / single-line)
35236          * @return {Roo.MessageBox} This message box
35237          */
35238         prompt : function(title, msg, fn, scope, multiline){
35239             this.show({
35240                 title : title,
35241                 msg : msg,
35242                 buttons: this.OKCANCEL,
35243                 fn: fn,
35244                 minWidth:250,
35245                 scope : scope,
35246                 prompt:true,
35247                 multiline: multiline,
35248                 modal : true
35249             });
35250             return this;
35251         },
35252
35253         /**
35254          * Button config that displays a single OK button
35255          * @type Object
35256          */
35257         OK : {ok:true},
35258         /**
35259          * Button config that displays Yes and No buttons
35260          * @type Object
35261          */
35262         YESNO : {yes:true, no:true},
35263         /**
35264          * Button config that displays OK and Cancel buttons
35265          * @type Object
35266          */
35267         OKCANCEL : {ok:true, cancel:true},
35268         /**
35269          * Button config that displays Yes, No and Cancel buttons
35270          * @type Object
35271          */
35272         YESNOCANCEL : {yes:true, no:true, cancel:true},
35273
35274         /**
35275          * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
35276          * @type Number
35277          */
35278         defaultTextHeight : 75,
35279         /**
35280          * The maximum width in pixels of the message box (defaults to 600)
35281          * @type Number
35282          */
35283         maxWidth : 600,
35284         /**
35285          * The minimum width in pixels of the message box (defaults to 100)
35286          * @type Number
35287          */
35288         minWidth : 100,
35289         /**
35290          * The minimum width in pixels of the message box if it is a progress-style dialog.  This is useful
35291          * for setting a different minimum width than text-only dialogs may need (defaults to 250)
35292          * @type Number
35293          */
35294         minProgressWidth : 250,
35295         /**
35296          * An object containing the default button text strings that can be overriden for localized language support.
35297          * Supported properties are: ok, cancel, yes and no.
35298          * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
35299          * @type Object
35300          */
35301         buttonText : {
35302             ok : "OK",
35303             cancel : "Cancel",
35304             yes : "Yes",
35305             no : "No"
35306         }
35307     };
35308 }();
35309
35310 /**
35311  * Shorthand for {@link Roo.MessageBox}
35312  */
35313 Roo.Msg = Roo.MessageBox;/*
35314  * Based on:
35315  * Ext JS Library 1.1.1
35316  * Copyright(c) 2006-2007, Ext JS, LLC.
35317  *
35318  * Originally Released Under LGPL - original licence link has changed is not relivant.
35319  *
35320  * Fork - LGPL
35321  * <script type="text/javascript">
35322  */
35323 /**
35324  * @class Roo.QuickTips
35325  * Provides attractive and customizable tooltips for any element.
35326  * @static
35327  */
35328 Roo.QuickTips = function(){
35329     var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
35330     var ce, bd, xy, dd;
35331     var visible = false, disabled = true, inited = false;
35332     var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
35333     
35334     var onOver = function(e){
35335         if(disabled){
35336             return;
35337         }
35338         var t = e.getTarget();
35339         if(!t || t.nodeType !== 1 || t == document || t == document.body){
35340             return;
35341         }
35342         if(ce && t == ce.el){
35343             clearTimeout(hideProc);
35344             return;
35345         }
35346         if(t && tagEls[t.id]){
35347             tagEls[t.id].el = t;
35348             showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
35349             return;
35350         }
35351         var ttp, et = Roo.fly(t);
35352         var ns = cfg.namespace;
35353         if(tm.interceptTitles && t.title){
35354             ttp = t.title;
35355             t.qtip = ttp;
35356             t.removeAttribute("title");
35357             e.preventDefault();
35358         }else{
35359             ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute) || et.getAttributeNS(cfg.alt_namespace, cfg.attribute) ;
35360         }
35361         if(ttp){
35362             showProc = show.defer(tm.showDelay, tm, [{
35363                 el: t, 
35364                 text: ttp.replace(/\\n/g,'<br/>'),
35365                 width: et.getAttributeNS(ns, cfg.width),
35366                 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
35367                 title: et.getAttributeNS(ns, cfg.title),
35368                     cls: et.getAttributeNS(ns, cfg.cls)
35369             }]);
35370         }
35371     };
35372     
35373     var onOut = function(e){
35374         clearTimeout(showProc);
35375         var t = e.getTarget();
35376         if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
35377             hideProc = setTimeout(hide, tm.hideDelay);
35378         }
35379     };
35380     
35381     var onMove = function(e){
35382         if(disabled){
35383             return;
35384         }
35385         xy = e.getXY();
35386         xy[1] += 18;
35387         if(tm.trackMouse && ce){
35388             el.setXY(xy);
35389         }
35390     };
35391     
35392     var onDown = function(e){
35393         clearTimeout(showProc);
35394         clearTimeout(hideProc);
35395         if(!e.within(el)){
35396             if(tm.hideOnClick){
35397                 hide();
35398                 tm.disable();
35399                 tm.enable.defer(100, tm);
35400             }
35401         }
35402     };
35403     
35404     var getPad = function(){
35405         return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
35406     };
35407
35408     var show = function(o){
35409         if(disabled){
35410             return;
35411         }
35412         clearTimeout(dismissProc);
35413         ce = o;
35414         if(removeCls){ // in case manually hidden
35415             el.removeClass(removeCls);
35416             removeCls = null;
35417         }
35418         if(ce.cls){
35419             el.addClass(ce.cls);
35420             removeCls = ce.cls;
35421         }
35422         if(ce.title){
35423             tipTitle.update(ce.title);
35424             tipTitle.show();
35425         }else{
35426             tipTitle.update('');
35427             tipTitle.hide();
35428         }
35429         el.dom.style.width  = tm.maxWidth+'px';
35430         //tipBody.dom.style.width = '';
35431         tipBodyText.update(o.text);
35432         var p = getPad(), w = ce.width;
35433         if(!w){
35434             var td = tipBodyText.dom;
35435             var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
35436             if(aw > tm.maxWidth){
35437                 w = tm.maxWidth;
35438             }else if(aw < tm.minWidth){
35439                 w = tm.minWidth;
35440             }else{
35441                 w = aw;
35442             }
35443         }
35444         //tipBody.setWidth(w);
35445         el.setWidth(parseInt(w, 10) + p);
35446         if(ce.autoHide === false){
35447             close.setDisplayed(true);
35448             if(dd){
35449                 dd.unlock();
35450             }
35451         }else{
35452             close.setDisplayed(false);
35453             if(dd){
35454                 dd.lock();
35455             }
35456         }
35457         if(xy){
35458             el.avoidY = xy[1]-18;
35459             el.setXY(xy);
35460         }
35461         if(tm.animate){
35462             el.setOpacity(.1);
35463             el.setStyle("visibility", "visible");
35464             el.fadeIn({callback: afterShow});
35465         }else{
35466             afterShow();
35467         }
35468     };
35469     
35470     var afterShow = function(){
35471         if(ce){
35472             el.show();
35473             esc.enable();
35474             if(tm.autoDismiss && ce.autoHide !== false){
35475                 dismissProc = setTimeout(hide, tm.autoDismissDelay);
35476             }
35477         }
35478     };
35479     
35480     var hide = function(noanim){
35481         clearTimeout(dismissProc);
35482         clearTimeout(hideProc);
35483         ce = null;
35484         if(el.isVisible()){
35485             esc.disable();
35486             if(noanim !== true && tm.animate){
35487                 el.fadeOut({callback: afterHide});
35488             }else{
35489                 afterHide();
35490             } 
35491         }
35492     };
35493     
35494     var afterHide = function(){
35495         el.hide();
35496         if(removeCls){
35497             el.removeClass(removeCls);
35498             removeCls = null;
35499         }
35500     };
35501     
35502     return {
35503         /**
35504         * @cfg {Number} minWidth
35505         * The minimum width of the quick tip (defaults to 40)
35506         */
35507        minWidth : 40,
35508         /**
35509         * @cfg {Number} maxWidth
35510         * The maximum width of the quick tip (defaults to 300)
35511         */
35512        maxWidth : 300,
35513         /**
35514         * @cfg {Boolean} interceptTitles
35515         * True to automatically use the element's DOM title value if available (defaults to false)
35516         */
35517        interceptTitles : false,
35518         /**
35519         * @cfg {Boolean} trackMouse
35520         * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
35521         */
35522        trackMouse : false,
35523         /**
35524         * @cfg {Boolean} hideOnClick
35525         * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
35526         */
35527        hideOnClick : true,
35528         /**
35529         * @cfg {Number} showDelay
35530         * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
35531         */
35532        showDelay : 500,
35533         /**
35534         * @cfg {Number} hideDelay
35535         * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
35536         */
35537        hideDelay : 200,
35538         /**
35539         * @cfg {Boolean} autoHide
35540         * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
35541         * Used in conjunction with hideDelay.
35542         */
35543        autoHide : true,
35544         /**
35545         * @cfg {Boolean}
35546         * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
35547         * (defaults to true).  Used in conjunction with autoDismissDelay.
35548         */
35549        autoDismiss : true,
35550         /**
35551         * @cfg {Number}
35552         * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
35553         */
35554        autoDismissDelay : 5000,
35555        /**
35556         * @cfg {Boolean} animate
35557         * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
35558         */
35559        animate : false,
35560
35561        /**
35562         * @cfg {String} title
35563         * Title text to display (defaults to '').  This can be any valid HTML markup.
35564         */
35565         title: '',
35566        /**
35567         * @cfg {String} text
35568         * Body text to display (defaults to '').  This can be any valid HTML markup.
35569         */
35570         text : '',
35571        /**
35572         * @cfg {String} cls
35573         * A CSS class to apply to the base quick tip element (defaults to '').
35574         */
35575         cls : '',
35576        /**
35577         * @cfg {Number} width
35578         * Width in pixels of the quick tip (defaults to auto).  Width will be ignored if it exceeds the bounds of
35579         * minWidth or maxWidth.
35580         */
35581         width : null,
35582
35583     /**
35584      * Initialize and enable QuickTips for first use.  This should be called once before the first attempt to access
35585      * or display QuickTips in a page.
35586      */
35587        init : function(){
35588           tm = Roo.QuickTips;
35589           cfg = tm.tagConfig;
35590           if(!inited){
35591               if(!Roo.isReady){ // allow calling of init() before onReady
35592                   Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
35593                   return;
35594               }
35595               el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
35596               el.fxDefaults = {stopFx: true};
35597               // maximum custom styling
35598               //el.update('<div class="x-tip-top-left"><div class="x-tip-top-right"><div class="x-tip-top"></div></div></div><div class="x-tip-bd-left"><div class="x-tip-bd-right"><div class="x-tip-bd"><div class="x-tip-close"></div><h3></h3><div class="x-tip-bd-inner"></div><div class="x-clear"></div></div></div></div><div class="x-tip-ft-left"><div class="x-tip-ft-right"><div class="x-tip-ft"></div></div></div>');
35599               el.update('<div class="x-tip-bd"><div class="x-tip-close"></div><h3></h3><div class="x-tip-bd-inner"></div><div class="x-clear"></div></div>');              
35600               tipTitle = el.child('h3');
35601               tipTitle.enableDisplayMode("block");
35602               tipBody = el.child('div.x-tip-bd');
35603               tipBodyText = el.child('div.x-tip-bd-inner');
35604               //bdLeft = el.child('div.x-tip-bd-left');
35605               //bdRight = el.child('div.x-tip-bd-right');
35606               close = el.child('div.x-tip-close');
35607               close.enableDisplayMode("block");
35608               close.on("click", hide);
35609               var d = Roo.get(document);
35610               d.on("mousedown", onDown);
35611               d.on("mouseover", onOver);
35612               d.on("mouseout", onOut);
35613               d.on("mousemove", onMove);
35614               esc = d.addKeyListener(27, hide);
35615               esc.disable();
35616               if(Roo.dd.DD){
35617                   dd = el.initDD("default", null, {
35618                       onDrag : function(){
35619                           el.sync();  
35620                       }
35621                   });
35622                   dd.setHandleElId(tipTitle.id);
35623                   dd.lock();
35624               }
35625               inited = true;
35626           }
35627           this.enable(); 
35628        },
35629
35630     /**
35631      * Configures a new quick tip instance and assigns it to a target element.  The following config options
35632      * are supported:
35633      * <pre>
35634 Property    Type                   Description
35635 ----------  ---------------------  ------------------------------------------------------------------------
35636 target      Element/String/Array   An Element, id or array of ids that this quick tip should be tied to
35637      * </ul>
35638      * @param {Object} config The config object
35639      */
35640        register : function(config){
35641            var cs = config instanceof Array ? config : arguments;
35642            for(var i = 0, len = cs.length; i < len; i++) {
35643                var c = cs[i];
35644                var target = c.target;
35645                if(target){
35646                    if(target instanceof Array){
35647                        for(var j = 0, jlen = target.length; j < jlen; j++){
35648                            tagEls[target[j]] = c;
35649                        }
35650                    }else{
35651                        tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
35652                    }
35653                }
35654            }
35655        },
35656
35657     /**
35658      * Removes this quick tip from its element and destroys it.
35659      * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
35660      */
35661        unregister : function(el){
35662            delete tagEls[Roo.id(el)];
35663        },
35664
35665     /**
35666      * Enable this quick tip.
35667      */
35668        enable : function(){
35669            if(inited && disabled){
35670                locks.pop();
35671                if(locks.length < 1){
35672                    disabled = false;
35673                }
35674            }
35675        },
35676
35677     /**
35678      * Disable this quick tip.
35679      */
35680        disable : function(){
35681           disabled = true;
35682           clearTimeout(showProc);
35683           clearTimeout(hideProc);
35684           clearTimeout(dismissProc);
35685           if(ce){
35686               hide(true);
35687           }
35688           locks.push(1);
35689        },
35690
35691     /**
35692      * Returns true if the quick tip is enabled, else false.
35693      */
35694        isEnabled : function(){
35695             return !disabled;
35696        },
35697
35698         // private
35699        tagConfig : {
35700            namespace : "roo", // was ext?? this may break..
35701            alt_namespace : "ext",
35702            attribute : "qtip",
35703            width : "width",
35704            target : "target",
35705            title : "qtitle",
35706            hide : "hide",
35707            cls : "qclass"
35708        }
35709    };
35710 }();
35711
35712 // backwards compat
35713 Roo.QuickTips.tips = Roo.QuickTips.register;/*
35714  * Based on:
35715  * Ext JS Library 1.1.1
35716  * Copyright(c) 2006-2007, Ext JS, LLC.
35717  *
35718  * Originally Released Under LGPL - original licence link has changed is not relivant.
35719  *
35720  * Fork - LGPL
35721  * <script type="text/javascript">
35722  */
35723  
35724
35725 /**
35726  * @class Roo.tree.TreePanel
35727  * @extends Roo.data.Tree
35728  * @cfg {Roo.tree.TreeNode} root The root node
35729  * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
35730  * @cfg {Boolean} lines false to disable tree lines (defaults to true)
35731  * @cfg {Boolean} enableDD true to enable drag and drop
35732  * @cfg {Boolean} enableDrag true to enable just drag
35733  * @cfg {Boolean} enableDrop true to enable just drop
35734  * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
35735  * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
35736  * @cfg {String} ddGroup The DD group this TreePanel belongs to
35737  * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
35738  * @cfg {Boolean} ddScroll true to enable YUI body scrolling
35739  * @cfg {Boolean} containerScroll true to register this container with ScrollManager
35740  * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
35741  * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
35742  * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
35743  * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
35744  * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
35745  * @cfg {Roo.tree.TreeLoader} loader A TreeLoader for use with this TreePanel
35746  * @cfg {Roo.tree.TreeEditor} editor The TreeEditor to display when clicked.
35747  * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
35748  * @cfg {Function} renderer DEPRECATED - use TreeLoader:create event / Sets the rendering (formatting) function for the nodes. to return HTML markup for the tree view. The render function is called with  the following parameters:<ul><li>The {Object} The data for the node.</li></ul>
35749  * @cfg {Function} rendererTip DEPRECATED - use TreeLoader:create event / Sets the rendering (formatting) function for the nodes hovertip to return HTML markup for the tree view. The render function is called with  the following parameters:<ul><li>The {Object} The data for the node.</li></ul>
35750  * 
35751  * @constructor
35752  * @param {String/HTMLElement/Element} el The container element
35753  * @param {Object} config
35754  */
35755 Roo.tree.TreePanel = function(el, config){
35756     var root = false;
35757     var loader = false;
35758     if (config.root) {
35759         root = config.root;
35760         delete config.root;
35761     }
35762     if (config.loader) {
35763         loader = config.loader;
35764         delete config.loader;
35765     }
35766     
35767     Roo.apply(this, config);
35768     Roo.tree.TreePanel.superclass.constructor.call(this);
35769     this.el = Roo.get(el);
35770     this.el.addClass('x-tree');
35771     //console.log(root);
35772     if (root) {
35773         this.setRootNode( Roo.factory(root, Roo.tree));
35774     }
35775     if (loader) {
35776         this.loader = Roo.factory(loader, Roo.tree);
35777     }
35778    /**
35779     * Read-only. The id of the container element becomes this TreePanel's id.
35780     */
35781     this.id = this.el.id;
35782     this.addEvents({
35783         /**
35784         * @event beforeload
35785         * Fires before a node is loaded, return false to cancel
35786         * @param {Node} node The node being loaded
35787         */
35788         "beforeload" : true,
35789         /**
35790         * @event load
35791         * Fires when a node is loaded
35792         * @param {Node} node The node that was loaded
35793         */
35794         "load" : true,
35795         /**
35796         * @event textchange
35797         * Fires when the text for a node is changed
35798         * @param {Node} node The node
35799         * @param {String} text The new text
35800         * @param {String} oldText The old text
35801         */
35802         "textchange" : true,
35803         /**
35804         * @event beforeexpand
35805         * Fires before a node is expanded, return false to cancel.
35806         * @param {Node} node The node
35807         * @param {Boolean} deep
35808         * @param {Boolean} anim
35809         */
35810         "beforeexpand" : true,
35811         /**
35812         * @event beforecollapse
35813         * Fires before a node is collapsed, return false to cancel.
35814         * @param {Node} node The node
35815         * @param {Boolean} deep
35816         * @param {Boolean} anim
35817         */
35818         "beforecollapse" : true,
35819         /**
35820         * @event expand
35821         * Fires when a node is expanded
35822         * @param {Node} node The node
35823         */
35824         "expand" : true,
35825         /**
35826         * @event disabledchange
35827         * Fires when the disabled status of a node changes
35828         * @param {Node} node The node
35829         * @param {Boolean} disabled
35830         */
35831         "disabledchange" : true,
35832         /**
35833         * @event collapse
35834         * Fires when a node is collapsed
35835         * @param {Node} node The node
35836         */
35837         "collapse" : true,
35838         /**
35839         * @event beforeclick
35840         * Fires before click processing on a node. Return false to cancel the default action.
35841         * @param {Node} node The node
35842         * @param {Roo.EventObject} e The event object
35843         */
35844         "beforeclick":true,
35845         /**
35846         * @event checkchange
35847         * Fires when a node with a checkbox's checked property changes
35848         * @param {Node} this This node
35849         * @param {Boolean} checked
35850         */
35851         "checkchange":true,
35852         /**
35853         * @event click
35854         * Fires when a node is clicked
35855         * @param {Node} node The node
35856         * @param {Roo.EventObject} e The event object
35857         */
35858         "click":true,
35859         /**
35860         * @event dblclick
35861         * Fires when a node is double clicked
35862         * @param {Node} node The node
35863         * @param {Roo.EventObject} e The event object
35864         */
35865         "dblclick":true,
35866         /**
35867         * @event contextmenu
35868         * Fires when a node is right clicked
35869         * @param {Node} node The node
35870         * @param {Roo.EventObject} e The event object
35871         */
35872         "contextmenu":true,
35873         /**
35874         * @event beforechildrenrendered
35875         * Fires right before the child nodes for a node are rendered
35876         * @param {Node} node The node
35877         */
35878         "beforechildrenrendered":true,
35879         /**
35880         * @event startdrag
35881         * Fires when a node starts being dragged
35882         * @param {Roo.tree.TreePanel} this
35883         * @param {Roo.tree.TreeNode} node
35884         * @param {event} e The raw browser event
35885         */ 
35886        "startdrag" : true,
35887        /**
35888         * @event enddrag
35889         * Fires when a drag operation is complete
35890         * @param {Roo.tree.TreePanel} this
35891         * @param {Roo.tree.TreeNode} node
35892         * @param {event} e The raw browser event
35893         */
35894        "enddrag" : true,
35895        /**
35896         * @event dragdrop
35897         * Fires when a dragged node is dropped on a valid DD target
35898         * @param {Roo.tree.TreePanel} this
35899         * @param {Roo.tree.TreeNode} node
35900         * @param {DD} dd The dd it was dropped on
35901         * @param {event} e The raw browser event
35902         */
35903        "dragdrop" : true,
35904        /**
35905         * @event beforenodedrop
35906         * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
35907         * passed to handlers has the following properties:<br />
35908         * <ul style="padding:5px;padding-left:16px;">
35909         * <li>tree - The TreePanel</li>
35910         * <li>target - The node being targeted for the drop</li>
35911         * <li>data - The drag data from the drag source</li>
35912         * <li>point - The point of the drop - append, above or below</li>
35913         * <li>source - The drag source</li>
35914         * <li>rawEvent - Raw mouse event</li>
35915         * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
35916         * to be inserted by setting them on this object.</li>
35917         * <li>cancel - Set this to true to cancel the drop.</li>
35918         * </ul>
35919         * @param {Object} dropEvent
35920         */
35921        "beforenodedrop" : true,
35922        /**
35923         * @event nodedrop
35924         * Fires after a DD object is dropped on a node in this tree. The dropEvent
35925         * passed to handlers has the following properties:<br />
35926         * <ul style="padding:5px;padding-left:16px;">
35927         * <li>tree - The TreePanel</li>
35928         * <li>target - The node being targeted for the drop</li>
35929         * <li>data - The drag data from the drag source</li>
35930         * <li>point - The point of the drop - append, above or below</li>
35931         * <li>source - The drag source</li>
35932         * <li>rawEvent - Raw mouse event</li>
35933         * <li>dropNode - Dropped node(s).</li>
35934         * </ul>
35935         * @param {Object} dropEvent
35936         */
35937        "nodedrop" : true,
35938         /**
35939         * @event nodedragover
35940         * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
35941         * passed to handlers has the following properties:<br />
35942         * <ul style="padding:5px;padding-left:16px;">
35943         * <li>tree - The TreePanel</li>
35944         * <li>target - The node being targeted for the drop</li>
35945         * <li>data - The drag data from the drag source</li>
35946         * <li>point - The point of the drop - append, above or below</li>
35947         * <li>source - The drag source</li>
35948         * <li>rawEvent - Raw mouse event</li>
35949         * <li>dropNode - Drop node(s) provided by the source.</li>
35950         * <li>cancel - Set this to true to signal drop not allowed.</li>
35951         * </ul>
35952         * @param {Object} dragOverEvent
35953         */
35954        "nodedragover" : true,
35955        /**
35956         * @event appendnode
35957         * Fires when append node to the tree
35958         * @param {Roo.tree.TreePanel} this
35959         * @param {Roo.tree.TreeNode} node
35960         * @param {Number} index The index of the newly appended node
35961         */
35962        "appendnode" : true
35963         
35964     });
35965     if(this.singleExpand){
35966        this.on("beforeexpand", this.restrictExpand, this);
35967     }
35968     if (this.editor) {
35969         this.editor.tree = this;
35970         this.editor = Roo.factory(this.editor, Roo.tree);
35971     }
35972     
35973     if (this.selModel) {
35974         this.selModel = Roo.factory(this.selModel, Roo.tree);
35975     }
35976    
35977 };
35978 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
35979     rootVisible : true,
35980     animate: Roo.enableFx,
35981     lines : true,
35982     enableDD : false,
35983     hlDrop : Roo.enableFx,
35984   
35985     renderer: false,
35986     
35987     rendererTip: false,
35988     // private
35989     restrictExpand : function(node){
35990         var p = node.parentNode;
35991         if(p){
35992             if(p.expandedChild && p.expandedChild.parentNode == p){
35993                 p.expandedChild.collapse();
35994             }
35995             p.expandedChild = node;
35996         }
35997     },
35998
35999     // private override
36000     setRootNode : function(node){
36001         Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
36002         if(!this.rootVisible){
36003             node.ui = new Roo.tree.RootTreeNodeUI(node);
36004         }
36005         return node;
36006     },
36007
36008     /**
36009      * Returns the container element for this TreePanel
36010      */
36011     getEl : function(){
36012         return this.el;
36013     },
36014
36015     /**
36016      * Returns the default TreeLoader for this TreePanel
36017      */
36018     getLoader : function(){
36019         return this.loader;
36020     },
36021
36022     /**
36023      * Expand all nodes
36024      */
36025     expandAll : function(){
36026         this.root.expand(true);
36027     },
36028
36029     /**
36030      * Collapse all nodes
36031      */
36032     collapseAll : function(){
36033         this.root.collapse(true);
36034     },
36035
36036     /**
36037      * Returns the selection model used by this TreePanel
36038      */
36039     getSelectionModel : function(){
36040         if(!this.selModel){
36041             this.selModel = new Roo.tree.DefaultSelectionModel();
36042         }
36043         return this.selModel;
36044     },
36045
36046     /**
36047      * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
36048      * @param {String} attribute (optional) Defaults to null (return the actual nodes)
36049      * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
36050      * @return {Array}
36051      */
36052     getChecked : function(a, startNode){
36053         startNode = startNode || this.root;
36054         var r = [];
36055         var f = function(){
36056             if(this.attributes.checked){
36057                 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
36058             }
36059         }
36060         startNode.cascade(f);
36061         return r;
36062     },
36063
36064     /**
36065      * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
36066      * @param {String} path
36067      * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
36068      * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
36069      * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
36070      */
36071     expandPath : function(path, attr, callback){
36072         attr = attr || "id";
36073         var keys = path.split(this.pathSeparator);
36074         var curNode = this.root;
36075         if(curNode.attributes[attr] != keys[1]){ // invalid root
36076             if(callback){
36077                 callback(false, null);
36078             }
36079             return;
36080         }
36081         var index = 1;
36082         var f = function(){
36083             if(++index == keys.length){
36084                 if(callback){
36085                     callback(true, curNode);
36086                 }
36087                 return;
36088             }
36089             var c = curNode.findChild(attr, keys[index]);
36090             if(!c){
36091                 if(callback){
36092                     callback(false, curNode);
36093                 }
36094                 return;
36095             }
36096             curNode = c;
36097             c.expand(false, false, f);
36098         };
36099         curNode.expand(false, false, f);
36100     },
36101
36102     /**
36103      * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
36104      * @param {String} path
36105      * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
36106      * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
36107      * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
36108      */
36109     selectPath : function(path, attr, callback){
36110         attr = attr || "id";
36111         var keys = path.split(this.pathSeparator);
36112         var v = keys.pop();
36113         if(keys.length > 0){
36114             var f = function(success, node){
36115                 if(success && node){
36116                     var n = node.findChild(attr, v);
36117                     if(n){
36118                         n.select();
36119                         if(callback){
36120                             callback(true, n);
36121                         }
36122                     }else if(callback){
36123                         callback(false, n);
36124                     }
36125                 }else{
36126                     if(callback){
36127                         callback(false, n);
36128                     }
36129                 }
36130             };
36131             this.expandPath(keys.join(this.pathSeparator), attr, f);
36132         }else{
36133             this.root.select();
36134             if(callback){
36135                 callback(true, this.root);
36136             }
36137         }
36138     },
36139
36140     getTreeEl : function(){
36141         return this.el;
36142     },
36143
36144     /**
36145      * Trigger rendering of this TreePanel
36146      */
36147     render : function(){
36148         if (this.innerCt) {
36149             return this; // stop it rendering more than once!!
36150         }
36151         
36152         this.innerCt = this.el.createChild({tag:"ul",
36153                cls:"x-tree-root-ct " +
36154                (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
36155
36156         if(this.containerScroll){
36157             Roo.dd.ScrollManager.register(this.el);
36158         }
36159         if((this.enableDD || this.enableDrop) && !this.dropZone){
36160            /**
36161             * The dropZone used by this tree if drop is enabled
36162             * @type Roo.tree.TreeDropZone
36163             */
36164              this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
36165                ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
36166            });
36167         }
36168         if((this.enableDD || this.enableDrag) && !this.dragZone){
36169            /**
36170             * The dragZone used by this tree if drag is enabled
36171             * @type Roo.tree.TreeDragZone
36172             */
36173             this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
36174                ddGroup: this.ddGroup || "TreeDD",
36175                scroll: this.ddScroll
36176            });
36177         }
36178         this.getSelectionModel().init(this);
36179         if (!this.root) {
36180             Roo.log("ROOT not set in tree");
36181             return this;
36182         }
36183         this.root.render();
36184         if(!this.rootVisible){
36185             this.root.renderChildren();
36186         }
36187         return this;
36188     }
36189 });/*
36190  * Based on:
36191  * Ext JS Library 1.1.1
36192  * Copyright(c) 2006-2007, Ext JS, LLC.
36193  *
36194  * Originally Released Under LGPL - original licence link has changed is not relivant.
36195  *
36196  * Fork - LGPL
36197  * <script type="text/javascript">
36198  */
36199  
36200
36201 /**
36202  * @class Roo.tree.DefaultSelectionModel
36203  * @extends Roo.util.Observable
36204  * The default single selection for a TreePanel.
36205  * @param {Object} cfg Configuration
36206  */
36207 Roo.tree.DefaultSelectionModel = function(cfg){
36208    this.selNode = null;
36209    
36210    
36211    
36212    this.addEvents({
36213        /**
36214         * @event selectionchange
36215         * Fires when the selected node changes
36216         * @param {DefaultSelectionModel} this
36217         * @param {TreeNode} node the new selection
36218         */
36219        "selectionchange" : true,
36220
36221        /**
36222         * @event beforeselect
36223         * Fires before the selected node changes, return false to cancel the change
36224         * @param {DefaultSelectionModel} this
36225         * @param {TreeNode} node the new selection
36226         * @param {TreeNode} node the old selection
36227         */
36228        "beforeselect" : true
36229    });
36230    
36231     Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
36232 };
36233
36234 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
36235     init : function(tree){
36236         this.tree = tree;
36237         tree.getTreeEl().on("keydown", this.onKeyDown, this);
36238         tree.on("click", this.onNodeClick, this);
36239     },
36240     
36241     onNodeClick : function(node, e){
36242         if (e.ctrlKey && this.selNode == node)  {
36243             this.unselect(node);
36244             return;
36245         }
36246         this.select(node);
36247     },
36248     
36249     /**
36250      * Select a node.
36251      * @param {TreeNode} node The node to select
36252      * @return {TreeNode} The selected node
36253      */
36254     select : function(node){
36255         var last = this.selNode;
36256         if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
36257             if(last){
36258                 last.ui.onSelectedChange(false);
36259             }
36260             this.selNode = node;
36261             node.ui.onSelectedChange(true);
36262             this.fireEvent("selectionchange", this, node, last);
36263         }
36264         return node;
36265     },
36266     
36267     /**
36268      * Deselect a node.
36269      * @param {TreeNode} node The node to unselect
36270      */
36271     unselect : function(node){
36272         if(this.selNode == node){
36273             this.clearSelections();
36274         }    
36275     },
36276     
36277     /**
36278      * Clear all selections
36279      */
36280     clearSelections : function(){
36281         var n = this.selNode;
36282         if(n){
36283             n.ui.onSelectedChange(false);
36284             this.selNode = null;
36285             this.fireEvent("selectionchange", this, null);
36286         }
36287         return n;
36288     },
36289     
36290     /**
36291      * Get the selected node
36292      * @return {TreeNode} The selected node
36293      */
36294     getSelectedNode : function(){
36295         return this.selNode;    
36296     },
36297     
36298     /**
36299      * Returns true if the node is selected
36300      * @param {TreeNode} node The node to check
36301      * @return {Boolean}
36302      */
36303     isSelected : function(node){
36304         return this.selNode == node;  
36305     },
36306
36307     /**
36308      * Selects the node above the selected node in the tree, intelligently walking the nodes
36309      * @return TreeNode The new selection
36310      */
36311     selectPrevious : function(){
36312         var s = this.selNode || this.lastSelNode;
36313         if(!s){
36314             return null;
36315         }
36316         var ps = s.previousSibling;
36317         if(ps){
36318             if(!ps.isExpanded() || ps.childNodes.length < 1){
36319                 return this.select(ps);
36320             } else{
36321                 var lc = ps.lastChild;
36322                 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
36323                     lc = lc.lastChild;
36324                 }
36325                 return this.select(lc);
36326             }
36327         } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
36328             return this.select(s.parentNode);
36329         }
36330         return null;
36331     },
36332
36333     /**
36334      * Selects the node above the selected node in the tree, intelligently walking the nodes
36335      * @return TreeNode The new selection
36336      */
36337     selectNext : function(){
36338         var s = this.selNode || this.lastSelNode;
36339         if(!s){
36340             return null;
36341         }
36342         if(s.firstChild && s.isExpanded()){
36343              return this.select(s.firstChild);
36344          }else if(s.nextSibling){
36345              return this.select(s.nextSibling);
36346          }else if(s.parentNode){
36347             var newS = null;
36348             s.parentNode.bubble(function(){
36349                 if(this.nextSibling){
36350                     newS = this.getOwnerTree().selModel.select(this.nextSibling);
36351                     return false;
36352                 }
36353             });
36354             return newS;
36355          }
36356         return null;
36357     },
36358
36359     onKeyDown : function(e){
36360         var s = this.selNode || this.lastSelNode;
36361         // undesirable, but required
36362         var sm = this;
36363         if(!s){
36364             return;
36365         }
36366         var k = e.getKey();
36367         switch(k){
36368              case e.DOWN:
36369                  e.stopEvent();
36370                  this.selectNext();
36371              break;
36372              case e.UP:
36373                  e.stopEvent();
36374                  this.selectPrevious();
36375              break;
36376              case e.RIGHT:
36377                  e.preventDefault();
36378                  if(s.hasChildNodes()){
36379                      if(!s.isExpanded()){
36380                          s.expand();
36381                      }else if(s.firstChild){
36382                          this.select(s.firstChild, e);
36383                      }
36384                  }
36385              break;
36386              case e.LEFT:
36387                  e.preventDefault();
36388                  if(s.hasChildNodes() && s.isExpanded()){
36389                      s.collapse();
36390                  }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
36391                      this.select(s.parentNode, e);
36392                  }
36393              break;
36394         };
36395     }
36396 });
36397
36398 /**
36399  * @class Roo.tree.MultiSelectionModel
36400  * @extends Roo.util.Observable
36401  * Multi selection for a TreePanel.
36402  * @param {Object} cfg Configuration
36403  */
36404 Roo.tree.MultiSelectionModel = function(){
36405    this.selNodes = [];
36406    this.selMap = {};
36407    this.addEvents({
36408        /**
36409         * @event selectionchange
36410         * Fires when the selected nodes change
36411         * @param {MultiSelectionModel} this
36412         * @param {Array} nodes Array of the selected nodes
36413         */
36414        "selectionchange" : true
36415    });
36416    Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
36417    
36418 };
36419
36420 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
36421     init : function(tree){
36422         this.tree = tree;
36423         tree.getTreeEl().on("keydown", this.onKeyDown, this);
36424         tree.on("click", this.onNodeClick, this);
36425     },
36426     
36427     onNodeClick : function(node, e){
36428         this.select(node, e, e.ctrlKey);
36429     },
36430     
36431     /**
36432      * Select a node.
36433      * @param {TreeNode} node The node to select
36434      * @param {EventObject} e (optional) An event associated with the selection
36435      * @param {Boolean} keepExisting True to retain existing selections
36436      * @return {TreeNode} The selected node
36437      */
36438     select : function(node, e, keepExisting){
36439         if(keepExisting !== true){
36440             this.clearSelections(true);
36441         }
36442         if(this.isSelected(node)){
36443             this.lastSelNode = node;
36444             return node;
36445         }
36446         this.selNodes.push(node);
36447         this.selMap[node.id] = node;
36448         this.lastSelNode = node;
36449         node.ui.onSelectedChange(true);
36450         this.fireEvent("selectionchange", this, this.selNodes);
36451         return node;
36452     },
36453     
36454     /**
36455      * Deselect a node.
36456      * @param {TreeNode} node The node to unselect
36457      */
36458     unselect : function(node){
36459         if(this.selMap[node.id]){
36460             node.ui.onSelectedChange(false);
36461             var sn = this.selNodes;
36462             var index = -1;
36463             if(sn.indexOf){
36464                 index = sn.indexOf(node);
36465             }else{
36466                 for(var i = 0, len = sn.length; i < len; i++){
36467                     if(sn[i] == node){
36468                         index = i;
36469                         break;
36470                     }
36471                 }
36472             }
36473             if(index != -1){
36474                 this.selNodes.splice(index, 1);
36475             }
36476             delete this.selMap[node.id];
36477             this.fireEvent("selectionchange", this, this.selNodes);
36478         }
36479     },
36480     
36481     /**
36482      * Clear all selections
36483      */
36484     clearSelections : function(suppressEvent){
36485         var sn = this.selNodes;
36486         if(sn.length > 0){
36487             for(var i = 0, len = sn.length; i < len; i++){
36488                 sn[i].ui.onSelectedChange(false);
36489             }
36490             this.selNodes = [];
36491             this.selMap = {};
36492             if(suppressEvent !== true){
36493                 this.fireEvent("selectionchange", this, this.selNodes);
36494             }
36495         }
36496     },
36497     
36498     /**
36499      * Returns true if the node is selected
36500      * @param {TreeNode} node The node to check
36501      * @return {Boolean}
36502      */
36503     isSelected : function(node){
36504         return this.selMap[node.id] ? true : false;  
36505     },
36506     
36507     /**
36508      * Returns an array of the selected nodes
36509      * @return {Array}
36510      */
36511     getSelectedNodes : function(){
36512         return this.selNodes;    
36513     },
36514
36515     onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
36516
36517     selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
36518
36519     selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
36520 });/*
36521  * Based on:
36522  * Ext JS Library 1.1.1
36523  * Copyright(c) 2006-2007, Ext JS, LLC.
36524  *
36525  * Originally Released Under LGPL - original licence link has changed is not relivant.
36526  *
36527  * Fork - LGPL
36528  * <script type="text/javascript">
36529  */
36530  
36531 /**
36532  * @class Roo.tree.TreeNode
36533  * @extends Roo.data.Node
36534  * @cfg {String} text The text for this node
36535  * @cfg {Boolean} expanded true to start the node expanded
36536  * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
36537  * @cfg {Boolean} allowDrop false if this node cannot be drop on
36538  * @cfg {Boolean} disabled true to start the node disabled
36539  * @cfg {String} icon The path to an icon for the node. The preferred way to do this
36540  *    is to use the cls or iconCls attributes and add the icon via a CSS background image.
36541  * @cfg {String} cls A css class to be added to the node
36542  * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
36543  * @cfg {String} href URL of the link used for the node (defaults to #)
36544  * @cfg {String} hrefTarget target frame for the link
36545  * @cfg {String} qtip An Ext QuickTip for the node
36546  * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
36547  * @cfg {Boolean} singleClickExpand True for single click expand on this node
36548  * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
36549  * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
36550  * (defaults to undefined with no checkbox rendered)
36551  * @constructor
36552  * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
36553  */
36554 Roo.tree.TreeNode = function(attributes){
36555     attributes = attributes || {};
36556     if(typeof attributes == "string"){
36557         attributes = {text: attributes};
36558     }
36559     this.childrenRendered = false;
36560     this.rendered = false;
36561     Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
36562     this.expanded = attributes.expanded === true;
36563     this.isTarget = attributes.isTarget !== false;
36564     this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
36565     this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
36566
36567     /**
36568      * Read-only. The text for this node. To change it use setText().
36569      * @type String
36570      */
36571     this.text = attributes.text;
36572     /**
36573      * True if this node is disabled.
36574      * @type Boolean
36575      */
36576     this.disabled = attributes.disabled === true;
36577
36578     this.addEvents({
36579         /**
36580         * @event textchange
36581         * Fires when the text for this node is changed
36582         * @param {Node} this This node
36583         * @param {String} text The new text
36584         * @param {String} oldText The old text
36585         */
36586         "textchange" : true,
36587         /**
36588         * @event beforeexpand
36589         * Fires before this node is expanded, return false to cancel.
36590         * @param {Node} this This node
36591         * @param {Boolean} deep
36592         * @param {Boolean} anim
36593         */
36594         "beforeexpand" : true,
36595         /**
36596         * @event beforecollapse
36597         * Fires before this node is collapsed, return false to cancel.
36598         * @param {Node} this This node
36599         * @param {Boolean} deep
36600         * @param {Boolean} anim
36601         */
36602         "beforecollapse" : true,
36603         /**
36604         * @event expand
36605         * Fires when this node is expanded
36606         * @param {Node} this This node
36607         */
36608         "expand" : true,
36609         /**
36610         * @event disabledchange
36611         * Fires when the disabled status of this node changes
36612         * @param {Node} this This node
36613         * @param {Boolean} disabled
36614         */
36615         "disabledchange" : true,
36616         /**
36617         * @event collapse
36618         * Fires when this node is collapsed
36619         * @param {Node} this This node
36620         */
36621         "collapse" : true,
36622         /**
36623         * @event beforeclick
36624         * Fires before click processing. Return false to cancel the default action.
36625         * @param {Node} this This node
36626         * @param {Roo.EventObject} e The event object
36627         */
36628         "beforeclick":true,
36629         /**
36630         * @event checkchange
36631         * Fires when a node with a checkbox's checked property changes
36632         * @param {Node} this This node
36633         * @param {Boolean} checked
36634         */
36635         "checkchange":true,
36636         /**
36637         * @event click
36638         * Fires when this node is clicked
36639         * @param {Node} this This node
36640         * @param {Roo.EventObject} e The event object
36641         */
36642         "click":true,
36643         /**
36644         * @event dblclick
36645         * Fires when this node is double clicked
36646         * @param {Node} this This node
36647         * @param {Roo.EventObject} e The event object
36648         */
36649         "dblclick":true,
36650         /**
36651         * @event contextmenu
36652         * Fires when this node is right clicked
36653         * @param {Node} this This node
36654         * @param {Roo.EventObject} e The event object
36655         */
36656         "contextmenu":true,
36657         /**
36658         * @event beforechildrenrendered
36659         * Fires right before the child nodes for this node are rendered
36660         * @param {Node} this This node
36661         */
36662         "beforechildrenrendered":true
36663     });
36664
36665     var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
36666
36667     /**
36668      * Read-only. The UI for this node
36669      * @type TreeNodeUI
36670      */
36671     this.ui = new uiClass(this);
36672     
36673     // finally support items[]
36674     if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
36675         return;
36676     }
36677     
36678     
36679     Roo.each(this.attributes.items, function(c) {
36680         this.appendChild(Roo.factory(c,Roo.Tree));
36681     }, this);
36682     delete this.attributes.items;
36683     
36684     
36685     
36686 };
36687 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
36688     preventHScroll: true,
36689     /**
36690      * Returns true if this node is expanded
36691      * @return {Boolean}
36692      */
36693     isExpanded : function(){
36694         return this.expanded;
36695     },
36696
36697     /**
36698      * Returns the UI object for this node
36699      * @return {TreeNodeUI}
36700      */
36701     getUI : function(){
36702         return this.ui;
36703     },
36704
36705     // private override
36706     setFirstChild : function(node){
36707         var of = this.firstChild;
36708         Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
36709         if(this.childrenRendered && of && node != of){
36710             of.renderIndent(true, true);
36711         }
36712         if(this.rendered){
36713             this.renderIndent(true, true);
36714         }
36715     },
36716
36717     // private override
36718     setLastChild : function(node){
36719         var ol = this.lastChild;
36720         Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
36721         if(this.childrenRendered && ol && node != ol){
36722             ol.renderIndent(true, true);
36723         }
36724         if(this.rendered){
36725             this.renderIndent(true, true);
36726         }
36727     },
36728
36729     // these methods are overridden to provide lazy rendering support
36730     // private override
36731     appendChild : function()
36732     {
36733         var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
36734         if(node && this.childrenRendered){
36735             node.render();
36736         }
36737         this.ui.updateExpandIcon();
36738         return node;
36739     },
36740
36741     // private override
36742     removeChild : function(node){
36743         this.ownerTree.getSelectionModel().unselect(node);
36744         Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
36745         // if it's been rendered remove dom node
36746         if(this.childrenRendered){
36747             node.ui.remove();
36748         }
36749         if(this.childNodes.length < 1){
36750             this.collapse(false, false);
36751         }else{
36752             this.ui.updateExpandIcon();
36753         }
36754         if(!this.firstChild) {
36755             this.childrenRendered = false;
36756         }
36757         return node;
36758     },
36759
36760     // private override
36761     insertBefore : function(node, refNode){
36762         var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
36763         if(newNode && refNode && this.childrenRendered){
36764             node.render();
36765         }
36766         this.ui.updateExpandIcon();
36767         return newNode;
36768     },
36769
36770     /**
36771      * Sets the text for this node
36772      * @param {String} text
36773      */
36774     setText : function(text){
36775         var oldText = this.text;
36776         this.text = text;
36777         this.attributes.text = text;
36778         if(this.rendered){ // event without subscribing
36779             this.ui.onTextChange(this, text, oldText);
36780         }
36781         this.fireEvent("textchange", this, text, oldText);
36782     },
36783
36784     /**
36785      * Triggers selection of this node
36786      */
36787     select : function(){
36788         this.getOwnerTree().getSelectionModel().select(this);
36789     },
36790
36791     /**
36792      * Triggers deselection of this node
36793      */
36794     unselect : function(){
36795         this.getOwnerTree().getSelectionModel().unselect(this);
36796     },
36797
36798     /**
36799      * Returns true if this node is selected
36800      * @return {Boolean}
36801      */
36802     isSelected : function(){
36803         return this.getOwnerTree().getSelectionModel().isSelected(this);
36804     },
36805
36806     /**
36807      * Expand this node.
36808      * @param {Boolean} deep (optional) True to expand all children as well
36809      * @param {Boolean} anim (optional) false to cancel the default animation
36810      * @param {Function} callback (optional) A callback to be called when
36811      * expanding this node completes (does not wait for deep expand to complete).
36812      * Called with 1 parameter, this node.
36813      */
36814     expand : function(deep, anim, callback){
36815         if(!this.expanded){
36816             if(this.fireEvent("beforeexpand", this, deep, anim) === false){
36817                 return;
36818             }
36819             if(!this.childrenRendered){
36820                 this.renderChildren();
36821             }
36822             this.expanded = true;
36823             
36824             if(!this.isHiddenRoot() && (this.getOwnerTree() && this.getOwnerTree().animate && anim !== false) || anim){
36825                 this.ui.animExpand(function(){
36826                     this.fireEvent("expand", this);
36827                     if(typeof callback == "function"){
36828                         callback(this);
36829                     }
36830                     if(deep === true){
36831                         this.expandChildNodes(true);
36832                     }
36833                 }.createDelegate(this));
36834                 return;
36835             }else{
36836                 this.ui.expand();
36837                 this.fireEvent("expand", this);
36838                 if(typeof callback == "function"){
36839                     callback(this);
36840                 }
36841             }
36842         }else{
36843            if(typeof callback == "function"){
36844                callback(this);
36845            }
36846         }
36847         if(deep === true){
36848             this.expandChildNodes(true);
36849         }
36850     },
36851
36852     isHiddenRoot : function(){
36853         return this.isRoot && !this.getOwnerTree().rootVisible;
36854     },
36855
36856     /**
36857      * Collapse this node.
36858      * @param {Boolean} deep (optional) True to collapse all children as well
36859      * @param {Boolean} anim (optional) false to cancel the default animation
36860      */
36861     collapse : function(deep, anim){
36862         if(this.expanded && !this.isHiddenRoot()){
36863             if(this.fireEvent("beforecollapse", this, deep, anim) === false){
36864                 return;
36865             }
36866             this.expanded = false;
36867             if((this.getOwnerTree().animate && anim !== false) || anim){
36868                 this.ui.animCollapse(function(){
36869                     this.fireEvent("collapse", this);
36870                     if(deep === true){
36871                         this.collapseChildNodes(true);
36872                     }
36873                 }.createDelegate(this));
36874                 return;
36875             }else{
36876                 this.ui.collapse();
36877                 this.fireEvent("collapse", this);
36878             }
36879         }
36880         if(deep === true){
36881             var cs = this.childNodes;
36882             for(var i = 0, len = cs.length; i < len; i++) {
36883                 cs[i].collapse(true, false);
36884             }
36885         }
36886     },
36887
36888     // private
36889     delayedExpand : function(delay){
36890         if(!this.expandProcId){
36891             this.expandProcId = this.expand.defer(delay, this);
36892         }
36893     },
36894
36895     // private
36896     cancelExpand : function(){
36897         if(this.expandProcId){
36898             clearTimeout(this.expandProcId);
36899         }
36900         this.expandProcId = false;
36901     },
36902
36903     /**
36904      * Toggles expanded/collapsed state of the node
36905      */
36906     toggle : function(){
36907         if(this.expanded){
36908             this.collapse();
36909         }else{
36910             this.expand();
36911         }
36912     },
36913
36914     /**
36915      * Ensures all parent nodes are expanded
36916      */
36917     ensureVisible : function(callback){
36918         var tree = this.getOwnerTree();
36919         tree.expandPath(this.parentNode.getPath(), false, function(){
36920             tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
36921             Roo.callback(callback);
36922         }.createDelegate(this));
36923     },
36924
36925     /**
36926      * Expand all child nodes
36927      * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
36928      */
36929     expandChildNodes : function(deep){
36930         var cs = this.childNodes;
36931         for(var i = 0, len = cs.length; i < len; i++) {
36932                 cs[i].expand(deep);
36933         }
36934     },
36935
36936     /**
36937      * Collapse all child nodes
36938      * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
36939      */
36940     collapseChildNodes : function(deep){
36941         var cs = this.childNodes;
36942         for(var i = 0, len = cs.length; i < len; i++) {
36943                 cs[i].collapse(deep);
36944         }
36945     },
36946
36947     /**
36948      * Disables this node
36949      */
36950     disable : function(){
36951         this.disabled = true;
36952         this.unselect();
36953         if(this.rendered && this.ui.onDisableChange){ // event without subscribing
36954             this.ui.onDisableChange(this, true);
36955         }
36956         this.fireEvent("disabledchange", this, true);
36957     },
36958
36959     /**
36960      * Enables this node
36961      */
36962     enable : function(){
36963         this.disabled = false;
36964         if(this.rendered && this.ui.onDisableChange){ // event without subscribing
36965             this.ui.onDisableChange(this, false);
36966         }
36967         this.fireEvent("disabledchange", this, false);
36968     },
36969
36970     // private
36971     renderChildren : function(suppressEvent){
36972         if(suppressEvent !== false){
36973             this.fireEvent("beforechildrenrendered", this);
36974         }
36975         var cs = this.childNodes;
36976         for(var i = 0, len = cs.length; i < len; i++){
36977             cs[i].render(true);
36978         }
36979         this.childrenRendered = true;
36980     },
36981
36982     // private
36983     sort : function(fn, scope){
36984         Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
36985         if(this.childrenRendered){
36986             var cs = this.childNodes;
36987             for(var i = 0, len = cs.length; i < len; i++){
36988                 cs[i].render(true);
36989             }
36990         }
36991     },
36992
36993     // private
36994     render : function(bulkRender){
36995         this.ui.render(bulkRender);
36996         if(!this.rendered){
36997             this.rendered = true;
36998             if(this.expanded){
36999                 this.expanded = false;
37000                 this.expand(false, false);
37001             }
37002         }
37003     },
37004
37005     // private
37006     renderIndent : function(deep, refresh){
37007         if(refresh){
37008             this.ui.childIndent = null;
37009         }
37010         this.ui.renderIndent();
37011         if(deep === true && this.childrenRendered){
37012             var cs = this.childNodes;
37013             for(var i = 0, len = cs.length; i < len; i++){
37014                 cs[i].renderIndent(true, refresh);
37015             }
37016         }
37017     }
37018 });/*
37019  * Based on:
37020  * Ext JS Library 1.1.1
37021  * Copyright(c) 2006-2007, Ext JS, LLC.
37022  *
37023  * Originally Released Under LGPL - original licence link has changed is not relivant.
37024  *
37025  * Fork - LGPL
37026  * <script type="text/javascript">
37027  */
37028  
37029 /**
37030  * @class Roo.tree.AsyncTreeNode
37031  * @extends Roo.tree.TreeNode
37032  * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
37033  * @constructor
37034  * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node 
37035  */
37036  Roo.tree.AsyncTreeNode = function(config){
37037     this.loaded = false;
37038     this.loading = false;
37039     Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
37040     /**
37041     * @event beforeload
37042     * Fires before this node is loaded, return false to cancel
37043     * @param {Node} this This node
37044     */
37045     this.addEvents({'beforeload':true, 'load': true});
37046     /**
37047     * @event load
37048     * Fires when this node is loaded
37049     * @param {Node} this This node
37050     */
37051     /**
37052      * The loader used by this node (defaults to using the tree's defined loader)
37053      * @type TreeLoader
37054      * @property loader
37055      */
37056 };
37057 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
37058     expand : function(deep, anim, callback){
37059         if(this.loading){ // if an async load is already running, waiting til it's done
37060             var timer;
37061             var f = function(){
37062                 if(!this.loading){ // done loading
37063                     clearInterval(timer);
37064                     this.expand(deep, anim, callback);
37065                 }
37066             }.createDelegate(this);
37067             timer = setInterval(f, 200);
37068             return;
37069         }
37070         if(!this.loaded){
37071             if(this.fireEvent("beforeload", this) === false){
37072                 return;
37073             }
37074             this.loading = true;
37075             this.ui.beforeLoad(this);
37076             var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
37077             if(loader){
37078                 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
37079                 return;
37080             }
37081         }
37082         Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
37083     },
37084     
37085     /**
37086      * Returns true if this node is currently loading
37087      * @return {Boolean}
37088      */
37089     isLoading : function(){
37090         return this.loading;  
37091     },
37092     
37093     loadComplete : function(deep, anim, callback){
37094         this.loading = false;
37095         this.loaded = true;
37096         this.ui.afterLoad(this);
37097         this.fireEvent("load", this);
37098         this.expand(deep, anim, callback);
37099     },
37100     
37101     /**
37102      * Returns true if this node has been loaded
37103      * @return {Boolean}
37104      */
37105     isLoaded : function(){
37106         return this.loaded;
37107     },
37108     
37109     hasChildNodes : function(){
37110         if(!this.isLeaf() && !this.loaded){
37111             return true;
37112         }else{
37113             return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
37114         }
37115     },
37116
37117     /**
37118      * Trigger a reload for this node
37119      * @param {Function} callback
37120      */
37121     reload : function(callback){
37122         this.collapse(false, false);
37123         while(this.firstChild){
37124             this.removeChild(this.firstChild);
37125         }
37126         this.childrenRendered = false;
37127         this.loaded = false;
37128         if(this.isHiddenRoot()){
37129             this.expanded = false;
37130         }
37131         this.expand(false, false, callback);
37132     }
37133 });/*
37134  * Based on:
37135  * Ext JS Library 1.1.1
37136  * Copyright(c) 2006-2007, Ext JS, LLC.
37137  *
37138  * Originally Released Under LGPL - original licence link has changed is not relivant.
37139  *
37140  * Fork - LGPL
37141  * <script type="text/javascript">
37142  */
37143  
37144 /**
37145  * @class Roo.tree.TreeNodeUI
37146  * @constructor
37147  * @param {Object} node The node to render
37148  * The TreeNode UI implementation is separate from the
37149  * tree implementation. Unless you are customizing the tree UI,
37150  * you should never have to use this directly.
37151  */
37152 Roo.tree.TreeNodeUI = function(node){
37153     this.node = node;
37154     this.rendered = false;
37155     this.animating = false;
37156     this.emptyIcon = Roo.BLANK_IMAGE_URL;
37157 };
37158
37159 Roo.tree.TreeNodeUI.prototype = {
37160     removeChild : function(node){
37161         if(this.rendered){
37162             this.ctNode.removeChild(node.ui.getEl());
37163         }
37164     },
37165
37166     beforeLoad : function(){
37167          this.addClass("x-tree-node-loading");
37168     },
37169
37170     afterLoad : function(){
37171          this.removeClass("x-tree-node-loading");
37172     },
37173
37174     onTextChange : function(node, text, oldText){
37175         if(this.rendered){
37176             this.textNode.innerHTML = text;
37177         }
37178     },
37179
37180     onDisableChange : function(node, state){
37181         this.disabled = state;
37182         if(state){
37183             this.addClass("x-tree-node-disabled");
37184         }else{
37185             this.removeClass("x-tree-node-disabled");
37186         }
37187     },
37188
37189     onSelectedChange : function(state){
37190         if(state){
37191             this.focus();
37192             this.addClass("x-tree-selected");
37193         }else{
37194             //this.blur();
37195             this.removeClass("x-tree-selected");
37196         }
37197     },
37198
37199     onMove : function(tree, node, oldParent, newParent, index, refNode){
37200         this.childIndent = null;
37201         if(this.rendered){
37202             var targetNode = newParent.ui.getContainer();
37203             if(!targetNode){//target not rendered
37204                 this.holder = document.createElement("div");
37205                 this.holder.appendChild(this.wrap);
37206                 return;
37207             }
37208             var insertBefore = refNode ? refNode.ui.getEl() : null;
37209             if(insertBefore){
37210                 targetNode.insertBefore(this.wrap, insertBefore);
37211             }else{
37212                 targetNode.appendChild(this.wrap);
37213             }
37214             this.node.renderIndent(true);
37215         }
37216     },
37217
37218     addClass : function(cls){
37219         if(this.elNode){
37220             Roo.fly(this.elNode).addClass(cls);
37221         }
37222     },
37223
37224     removeClass : function(cls){
37225         if(this.elNode){
37226             Roo.fly(this.elNode).removeClass(cls);
37227         }
37228     },
37229
37230     remove : function(){
37231         if(this.rendered){
37232             this.holder = document.createElement("div");
37233             this.holder.appendChild(this.wrap);
37234         }
37235     },
37236
37237     fireEvent : function(){
37238         return this.node.fireEvent.apply(this.node, arguments);
37239     },
37240
37241     initEvents : function(){
37242         this.node.on("move", this.onMove, this);
37243         var E = Roo.EventManager;
37244         var a = this.anchor;
37245
37246         var el = Roo.fly(a, '_treeui');
37247
37248         if(Roo.isOpera){ // opera render bug ignores the CSS
37249             el.setStyle("text-decoration", "none");
37250         }
37251
37252         el.on("click", this.onClick, this);
37253         el.on("dblclick", this.onDblClick, this);
37254
37255         if(this.checkbox){
37256             Roo.EventManager.on(this.checkbox,
37257                     Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
37258         }
37259
37260         el.on("contextmenu", this.onContextMenu, this);
37261
37262         var icon = Roo.fly(this.iconNode);
37263         icon.on("click", this.onClick, this);
37264         icon.on("dblclick", this.onDblClick, this);
37265         icon.on("contextmenu", this.onContextMenu, this);
37266         E.on(this.ecNode, "click", this.ecClick, this, true);
37267
37268         if(this.node.disabled){
37269             this.addClass("x-tree-node-disabled");
37270         }
37271         if(this.node.hidden){
37272             this.addClass("x-tree-node-disabled");
37273         }
37274         var ot = this.node.getOwnerTree();
37275         var dd = ot ? (ot.enableDD || ot.enableDrag || ot.enableDrop) : false;
37276         if(dd && (!this.node.isRoot || ot.rootVisible)){
37277             Roo.dd.Registry.register(this.elNode, {
37278                 node: this.node,
37279                 handles: this.getDDHandles(),
37280                 isHandle: false
37281             });
37282         }
37283     },
37284
37285     getDDHandles : function(){
37286         return [this.iconNode, this.textNode];
37287     },
37288
37289     hide : function(){
37290         if(this.rendered){
37291             this.wrap.style.display = "none";
37292         }
37293     },
37294
37295     show : function(){
37296         if(this.rendered){
37297             this.wrap.style.display = "";
37298         }
37299     },
37300
37301     onContextMenu : function(e){
37302         if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
37303             e.preventDefault();
37304             this.focus();
37305             this.fireEvent("contextmenu", this.node, e);
37306         }
37307     },
37308
37309     onClick : function(e){
37310         if(this.dropping){
37311             e.stopEvent();
37312             return;
37313         }
37314         if(this.fireEvent("beforeclick", this.node, e) !== false){
37315             if(!this.disabled && this.node.attributes.href){
37316                 this.fireEvent("click", this.node, e);
37317                 return;
37318             }
37319             e.preventDefault();
37320             if(this.disabled){
37321                 return;
37322             }
37323
37324             if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
37325                 this.node.toggle();
37326             }
37327
37328             this.fireEvent("click", this.node, e);
37329         }else{
37330             e.stopEvent();
37331         }
37332     },
37333
37334     onDblClick : function(e){
37335         e.preventDefault();
37336         if(this.disabled){
37337             return;
37338         }
37339         if(this.checkbox){
37340             this.toggleCheck();
37341         }
37342         if(!this.animating && this.node.hasChildNodes()){
37343             this.node.toggle();
37344         }
37345         this.fireEvent("dblclick", this.node, e);
37346     },
37347
37348     onCheckChange : function(){
37349         var checked = this.checkbox.checked;
37350         this.node.attributes.checked = checked;
37351         this.fireEvent('checkchange', this.node, checked);
37352     },
37353
37354     ecClick : function(e){
37355         if(!this.animating && this.node.hasChildNodes()){
37356             this.node.toggle();
37357         }
37358     },
37359
37360     startDrop : function(){
37361         this.dropping = true;
37362     },
37363
37364     // delayed drop so the click event doesn't get fired on a drop
37365     endDrop : function(){
37366        setTimeout(function(){
37367            this.dropping = false;
37368        }.createDelegate(this), 50);
37369     },
37370
37371     expand : function(){
37372         this.updateExpandIcon();
37373         this.ctNode.style.display = "";
37374     },
37375
37376     focus : function(){
37377         if(!this.node.preventHScroll){
37378             try{this.anchor.focus();
37379             }catch(e){}
37380         }else if(!Roo.isIE){
37381             try{
37382                 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
37383                 var l = noscroll.scrollLeft;
37384                 this.anchor.focus();
37385                 noscroll.scrollLeft = l;
37386             }catch(e){}
37387         }
37388     },
37389
37390     toggleCheck : function(value){
37391         var cb = this.checkbox;
37392         if(cb){
37393             cb.checked = (value === undefined ? !cb.checked : value);
37394         }
37395     },
37396
37397     blur : function(){
37398         try{
37399             this.anchor.blur();
37400         }catch(e){}
37401     },
37402
37403     animExpand : function(callback){
37404         var ct = Roo.get(this.ctNode);
37405         ct.stopFx();
37406         if(!this.node.hasChildNodes()){
37407             this.updateExpandIcon();
37408             this.ctNode.style.display = "";
37409             Roo.callback(callback);
37410             return;
37411         }
37412         this.animating = true;
37413         this.updateExpandIcon();
37414
37415         ct.slideIn('t', {
37416            callback : function(){
37417                this.animating = false;
37418                Roo.callback(callback);
37419             },
37420             scope: this,
37421             duration: this.node.ownerTree.duration || .25
37422         });
37423     },
37424
37425     highlight : function(){
37426         var tree = this.node.getOwnerTree();
37427         Roo.fly(this.wrap).highlight(
37428             tree.hlColor || "C3DAF9",
37429             {endColor: tree.hlBaseColor}
37430         );
37431     },
37432
37433     collapse : function(){
37434         this.updateExpandIcon();
37435         this.ctNode.style.display = "none";
37436     },
37437
37438     animCollapse : function(callback){
37439         var ct = Roo.get(this.ctNode);
37440         ct.enableDisplayMode('block');
37441         ct.stopFx();
37442
37443         this.animating = true;
37444         this.updateExpandIcon();
37445
37446         ct.slideOut('t', {
37447             callback : function(){
37448                this.animating = false;
37449                Roo.callback(callback);
37450             },
37451             scope: this,
37452             duration: this.node.ownerTree.duration || .25
37453         });
37454     },
37455
37456     getContainer : function(){
37457         return this.ctNode;
37458     },
37459
37460     getEl : function(){
37461         return this.wrap;
37462     },
37463
37464     appendDDGhost : function(ghostNode){
37465         ghostNode.appendChild(this.elNode.cloneNode(true));
37466     },
37467
37468     getDDRepairXY : function(){
37469         return Roo.lib.Dom.getXY(this.iconNode);
37470     },
37471
37472     onRender : function(){
37473         this.render();
37474     },
37475
37476     render : function(bulkRender){
37477         var n = this.node, a = n.attributes;
37478         var targetNode = n.parentNode ?
37479               n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
37480
37481         if(!this.rendered){
37482             this.rendered = true;
37483
37484             this.renderElements(n, a, targetNode, bulkRender);
37485
37486             if(a.qtip){
37487                if(this.textNode.setAttributeNS){
37488                    this.textNode.setAttributeNS("ext", "qtip", a.qtip);
37489                    if(a.qtipTitle){
37490                        this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
37491                    }
37492                }else{
37493                    this.textNode.setAttribute("ext:qtip", a.qtip);
37494                    if(a.qtipTitle){
37495                        this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
37496                    }
37497                }
37498             }else if(a.qtipCfg){
37499                 a.qtipCfg.target = Roo.id(this.textNode);
37500                 Roo.QuickTips.register(a.qtipCfg);
37501             }
37502             this.initEvents();
37503             if(!this.node.expanded){
37504                 this.updateExpandIcon();
37505             }
37506         }else{
37507             if(bulkRender === true) {
37508                 targetNode.appendChild(this.wrap);
37509             }
37510         }
37511     },
37512
37513     renderElements : function(n, a, targetNode, bulkRender)
37514     {
37515         // add some indent caching, this helps performance when rendering a large tree
37516         this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
37517         var t = n.getOwnerTree();
37518         var txt = t && t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
37519         if (typeof(n.attributes.html) != 'undefined') {
37520             txt = n.attributes.html;
37521         }
37522         var tip = t && t.rendererTip ? t.rendererTip(n.attributes) : txt;
37523         var cb = typeof a.checked == 'boolean';
37524         var href = a.href ? a.href : Roo.isGecko ? "" : "#";
37525         var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
37526             '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
37527             '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
37528             '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
37529             cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
37530             '<a hidefocus="on" href="',href,'" tabIndex="1" ',
37531              a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", 
37532                 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
37533             '<ul class="x-tree-node-ct" style="display:none;"></ul>',
37534             "</li>"];
37535
37536         if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
37537             this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
37538                                 n.nextSibling.ui.getEl(), buf.join(""));
37539         }else{
37540             this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
37541         }
37542
37543         this.elNode = this.wrap.childNodes[0];
37544         this.ctNode = this.wrap.childNodes[1];
37545         var cs = this.elNode.childNodes;
37546         this.indentNode = cs[0];
37547         this.ecNode = cs[1];
37548         this.iconNode = cs[2];
37549         var index = 3;
37550         if(cb){
37551             this.checkbox = cs[3];
37552             index++;
37553         }
37554         this.anchor = cs[index];
37555         this.textNode = cs[index].firstChild;
37556     },
37557
37558     getAnchor : function(){
37559         return this.anchor;
37560     },
37561
37562     getTextEl : function(){
37563         return this.textNode;
37564     },
37565
37566     getIconEl : function(){
37567         return this.iconNode;
37568     },
37569
37570     isChecked : function(){
37571         return this.checkbox ? this.checkbox.checked : false;
37572     },
37573
37574     updateExpandIcon : function(){
37575         if(this.rendered){
37576             var n = this.node, c1, c2;
37577             var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
37578             var hasChild = n.hasChildNodes();
37579             if(hasChild){
37580                 if(n.expanded){
37581                     cls += "-minus";
37582                     c1 = "x-tree-node-collapsed";
37583                     c2 = "x-tree-node-expanded";
37584                 }else{
37585                     cls += "-plus";
37586                     c1 = "x-tree-node-expanded";
37587                     c2 = "x-tree-node-collapsed";
37588                 }
37589                 if(this.wasLeaf){
37590                     this.removeClass("x-tree-node-leaf");
37591                     this.wasLeaf = false;
37592                 }
37593                 if(this.c1 != c1 || this.c2 != c2){
37594                     Roo.fly(this.elNode).replaceClass(c1, c2);
37595                     this.c1 = c1; this.c2 = c2;
37596                 }
37597             }else{
37598                 // this changes non-leafs into leafs if they have no children.
37599                 // it's not very rational behaviour..
37600                 
37601                 if(!this.wasLeaf && this.node.leaf){
37602                     Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
37603                     delete this.c1;
37604                     delete this.c2;
37605                     this.wasLeaf = true;
37606                 }
37607             }
37608             var ecc = "x-tree-ec-icon "+cls;
37609             if(this.ecc != ecc){
37610                 this.ecNode.className = ecc;
37611                 this.ecc = ecc;
37612             }
37613         }
37614     },
37615
37616     getChildIndent : function(){
37617         if(!this.childIndent){
37618             var buf = [];
37619             var p = this.node;
37620             while(p){
37621                 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
37622                     if(!p.isLast()) {
37623                         buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
37624                     } else {
37625                         buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
37626                     }
37627                 }
37628                 p = p.parentNode;
37629             }
37630             this.childIndent = buf.join("");
37631         }
37632         return this.childIndent;
37633     },
37634
37635     renderIndent : function(){
37636         if(this.rendered){
37637             var indent = "";
37638             var p = this.node.parentNode;
37639             if(p){
37640                 indent = p.ui.getChildIndent();
37641             }
37642             if(this.indentMarkup != indent){ // don't rerender if not required
37643                 this.indentNode.innerHTML = indent;
37644                 this.indentMarkup = indent;
37645             }
37646             this.updateExpandIcon();
37647         }
37648     }
37649 };
37650
37651 Roo.tree.RootTreeNodeUI = function(){
37652     Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
37653 };
37654 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
37655     render : function(){
37656         if(!this.rendered){
37657             var targetNode = this.node.ownerTree.innerCt.dom;
37658             this.node.expanded = true;
37659             targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
37660             this.wrap = this.ctNode = targetNode.firstChild;
37661         }
37662     },
37663     collapse : function(){
37664     },
37665     expand : function(){
37666     }
37667 });/*
37668  * Based on:
37669  * Ext JS Library 1.1.1
37670  * Copyright(c) 2006-2007, Ext JS, LLC.
37671  *
37672  * Originally Released Under LGPL - original licence link has changed is not relivant.
37673  *
37674  * Fork - LGPL
37675  * <script type="text/javascript">
37676  */
37677 /**
37678  * @class Roo.tree.TreeLoader
37679  * @extends Roo.util.Observable
37680  * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
37681  * nodes from a specified URL. The response must be a javascript Array definition
37682  * who's elements are node definition objects. eg:
37683  * <pre><code>
37684 {  success : true,
37685    data :      [
37686    
37687     { 'id': 1, 'text': 'A folder Node', 'leaf': false },
37688     { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
37689     ]
37690 }
37691
37692
37693 </code></pre>
37694  * <br><br>
37695  * The old style respose with just an array is still supported, but not recommended.
37696  * <br><br>
37697  *
37698  * A server request is sent, and child nodes are loaded only when a node is expanded.
37699  * The loading node's id is passed to the server under the parameter name "node" to
37700  * enable the server to produce the correct child nodes.
37701  * <br><br>
37702  * To pass extra parameters, an event handler may be attached to the "beforeload"
37703  * event, and the parameters specified in the TreeLoader's baseParams property:
37704  * <pre><code>
37705     myTreeLoader.on("beforeload", function(treeLoader, node) {
37706         this.baseParams.category = node.attributes.category;
37707     }, this);
37708     
37709 </code></pre>
37710  *
37711  * This would pass an HTTP parameter called "category" to the server containing
37712  * the value of the Node's "category" attribute.
37713  * @constructor
37714  * Creates a new Treeloader.
37715  * @param {Object} config A config object containing config properties.
37716  */
37717 Roo.tree.TreeLoader = function(config){
37718     this.baseParams = {};
37719     this.requestMethod = "POST";
37720     Roo.apply(this, config);
37721
37722     this.addEvents({
37723     
37724         /**
37725          * @event beforeload
37726          * Fires before a network request is made to retrieve the Json text which specifies a node's children.
37727          * @param {Object} This TreeLoader object.
37728          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
37729          * @param {Object} callback The callback function specified in the {@link #load} call.
37730          */
37731         beforeload : true,
37732         /**
37733          * @event load
37734          * Fires when the node has been successfuly loaded.
37735          * @param {Object} This TreeLoader object.
37736          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
37737          * @param {Object} response The response object containing the data from the server.
37738          */
37739         load : true,
37740         /**
37741          * @event loadexception
37742          * Fires if the network request failed.
37743          * @param {Object} This TreeLoader object.
37744          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
37745          * @param {Object} response The response object containing the data from the server.
37746          */
37747         loadexception : true,
37748         /**
37749          * @event create
37750          * Fires before a node is created, enabling you to return custom Node types 
37751          * @param {Object} This TreeLoader object.
37752          * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
37753          */
37754         create : true
37755     });
37756
37757     Roo.tree.TreeLoader.superclass.constructor.call(this);
37758 };
37759
37760 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
37761     /**
37762     * @cfg {String} dataUrl The URL from which to request a Json string which
37763     * specifies an array of node definition object representing the child nodes
37764     * to be loaded.
37765     */
37766     /**
37767     * @cfg {String} requestMethod either GET or POST
37768     * defaults to POST (due to BC)
37769     * to be loaded.
37770     */
37771     /**
37772     * @cfg {Object} baseParams (optional) An object containing properties which
37773     * specify HTTP parameters to be passed to each request for child nodes.
37774     */
37775     /**
37776     * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
37777     * created by this loader. If the attributes sent by the server have an attribute in this object,
37778     * they take priority.
37779     */
37780     /**
37781     * @cfg {Object} uiProviders (optional) An object containing properties which
37782     * 
37783     * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
37784     * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
37785     * <i>uiProvider</i> attribute of a returned child node is a string rather
37786     * than a reference to a TreeNodeUI implementation, this that string value
37787     * is used as a property name in the uiProviders object. You can define the provider named
37788     * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
37789     */
37790     uiProviders : {},
37791
37792     /**
37793     * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
37794     * child nodes before loading.
37795     */
37796     clearOnLoad : true,
37797
37798     /**
37799     * @cfg {String} root (optional) Default to false. Use this to read data from an object 
37800     * property on loading, rather than expecting an array. (eg. more compatible to a standard
37801     * Grid query { data : [ .....] }
37802     */
37803     
37804     root : false,
37805      /**
37806     * @cfg {String} queryParam (optional) 
37807     * Name of the query as it will be passed on the querystring (defaults to 'node')
37808     * eg. the request will be ?node=[id]
37809     */
37810     
37811     
37812     queryParam: false,
37813     
37814     /**
37815      * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
37816      * This is called automatically when a node is expanded, but may be used to reload
37817      * a node (or append new children if the {@link #clearOnLoad} option is false.)
37818      * @param {Roo.tree.TreeNode} node
37819      * @param {Function} callback
37820      */
37821     load : function(node, callback){
37822         if(this.clearOnLoad){
37823             while(node.firstChild){
37824                 node.removeChild(node.firstChild);
37825             }
37826         }
37827         if(node.attributes.children){ // preloaded json children
37828             var cs = node.attributes.children;
37829             for(var i = 0, len = cs.length; i < len; i++){
37830                 node.appendChild(this.createNode(cs[i]));
37831             }
37832             if(typeof callback == "function"){
37833                 callback();
37834             }
37835         }else if(this.dataUrl){
37836             this.requestData(node, callback);
37837         }
37838     },
37839
37840     getParams: function(node){
37841         var buf = [], bp = this.baseParams;
37842         for(var key in bp){
37843             if(typeof bp[key] != "function"){
37844                 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
37845             }
37846         }
37847         var n = this.queryParam === false ? 'node' : this.queryParam;
37848         buf.push(n + "=", encodeURIComponent(node.id));
37849         return buf.join("");
37850     },
37851
37852     requestData : function(node, callback){
37853         if(this.fireEvent("beforeload", this, node, callback) !== false){
37854             this.transId = Roo.Ajax.request({
37855                 method:this.requestMethod,
37856                 url: this.dataUrl||this.url,
37857                 success: this.handleResponse,
37858                 failure: this.handleFailure,
37859                 scope: this,
37860                 argument: {callback: callback, node: node},
37861                 params: this.getParams(node)
37862             });
37863         }else{
37864             // if the load is cancelled, make sure we notify
37865             // the node that we are done
37866             if(typeof callback == "function"){
37867                 callback();
37868             }
37869         }
37870     },
37871
37872     isLoading : function(){
37873         return this.transId ? true : false;
37874     },
37875
37876     abort : function(){
37877         if(this.isLoading()){
37878             Roo.Ajax.abort(this.transId);
37879         }
37880     },
37881
37882     // private
37883     createNode : function(attr)
37884     {
37885         // apply baseAttrs, nice idea Corey!
37886         if(this.baseAttrs){
37887             Roo.applyIf(attr, this.baseAttrs);
37888         }
37889         if(this.applyLoader !== false){
37890             attr.loader = this;
37891         }
37892         // uiProvider = depreciated..
37893         
37894         if(typeof(attr.uiProvider) == 'string'){
37895            attr.uiProvider = this.uiProviders[attr.uiProvider] || 
37896                 /**  eval:var:attr */ eval(attr.uiProvider);
37897         }
37898         if(typeof(this.uiProviders['default']) != 'undefined') {
37899             attr.uiProvider = this.uiProviders['default'];
37900         }
37901         
37902         this.fireEvent('create', this, attr);
37903         
37904         attr.leaf  = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
37905         return(attr.leaf ?
37906                         new Roo.tree.TreeNode(attr) :
37907                         new Roo.tree.AsyncTreeNode(attr));
37908     },
37909
37910     processResponse : function(response, node, callback)
37911     {
37912         var json = response.responseText;
37913         try {
37914             
37915             var o = Roo.decode(json);
37916             
37917             if (this.root === false && typeof(o.success) != undefined) {
37918                 this.root = 'data'; // the default behaviour for list like data..
37919                 }
37920                 
37921             if (this.root !== false &&  !o.success) {
37922                 // it's a failure condition.
37923                 var a = response.argument;
37924                 this.fireEvent("loadexception", this, a.node, response);
37925                 Roo.log("Load failed - should have a handler really");
37926                 return;
37927             }
37928             
37929             
37930             
37931             if (this.root !== false) {
37932                  o = o[this.root];
37933             }
37934             
37935             for(var i = 0, len = o.length; i < len; i++){
37936                 var n = this.createNode(o[i]);
37937                 if(n){
37938                     node.appendChild(n);
37939                 }
37940             }
37941             if(typeof callback == "function"){
37942                 callback(this, node);
37943             }
37944         }catch(e){
37945             this.handleFailure(response);
37946         }
37947     },
37948
37949     handleResponse : function(response){
37950         this.transId = false;
37951         var a = response.argument;
37952         this.processResponse(response, a.node, a.callback);
37953         this.fireEvent("load", this, a.node, response);
37954     },
37955
37956     handleFailure : function(response)
37957     {
37958         // should handle failure better..
37959         this.transId = false;
37960         var a = response.argument;
37961         this.fireEvent("loadexception", this, a.node, response);
37962         if(typeof a.callback == "function"){
37963             a.callback(this, a.node);
37964         }
37965     }
37966 });/*
37967  * Based on:
37968  * Ext JS Library 1.1.1
37969  * Copyright(c) 2006-2007, Ext JS, LLC.
37970  *
37971  * Originally Released Under LGPL - original licence link has changed is not relivant.
37972  *
37973  * Fork - LGPL
37974  * <script type="text/javascript">
37975  */
37976
37977 /**
37978 * @class Roo.tree.TreeFilter
37979 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
37980 * @param {TreePanel} tree
37981 * @param {Object} config (optional)
37982  */
37983 Roo.tree.TreeFilter = function(tree, config){
37984     this.tree = tree;
37985     this.filtered = {};
37986     Roo.apply(this, config);
37987 };
37988
37989 Roo.tree.TreeFilter.prototype = {
37990     clearBlank:false,
37991     reverse:false,
37992     autoClear:false,
37993     remove:false,
37994
37995      /**
37996      * Filter the data by a specific attribute.
37997      * @param {String/RegExp} value Either string that the attribute value
37998      * should start with or a RegExp to test against the attribute
37999      * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
38000      * @param {TreeNode} startNode (optional) The node to start the filter at.
38001      */
38002     filter : function(value, attr, startNode){
38003         attr = attr || "text";
38004         var f;
38005         if(typeof value == "string"){
38006             var vlen = value.length;
38007             // auto clear empty filter
38008             if(vlen == 0 && this.clearBlank){
38009                 this.clear();
38010                 return;
38011             }
38012             value = value.toLowerCase();
38013             f = function(n){
38014                 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
38015             };
38016         }else if(value.exec){ // regex?
38017             f = function(n){
38018                 return value.test(n.attributes[attr]);
38019             };
38020         }else{
38021             throw 'Illegal filter type, must be string or regex';
38022         }
38023         this.filterBy(f, null, startNode);
38024         },
38025
38026     /**
38027      * Filter by a function. The passed function will be called with each
38028      * node in the tree (or from the startNode). If the function returns true, the node is kept
38029      * otherwise it is filtered. If a node is filtered, its children are also filtered.
38030      * @param {Function} fn The filter function
38031      * @param {Object} scope (optional) The scope of the function (defaults to the current node)
38032      */
38033     filterBy : function(fn, scope, startNode){
38034         startNode = startNode || this.tree.root;
38035         if(this.autoClear){
38036             this.clear();
38037         }
38038         var af = this.filtered, rv = this.reverse;
38039         var f = function(n){
38040             if(n == startNode){
38041                 return true;
38042             }
38043             if(af[n.id]){
38044                 return false;
38045             }
38046             var m = fn.call(scope || n, n);
38047             if(!m || rv){
38048                 af[n.id] = n;
38049                 n.ui.hide();
38050                 return false;
38051             }
38052             return true;
38053         };
38054         startNode.cascade(f);
38055         if(this.remove){
38056            for(var id in af){
38057                if(typeof id != "function"){
38058                    var n = af[id];
38059                    if(n && n.parentNode){
38060                        n.parentNode.removeChild(n);
38061                    }
38062                }
38063            }
38064         }
38065     },
38066
38067     /**
38068      * Clears the current filter. Note: with the "remove" option
38069      * set a filter cannot be cleared.
38070      */
38071     clear : function(){
38072         var t = this.tree;
38073         var af = this.filtered;
38074         for(var id in af){
38075             if(typeof id != "function"){
38076                 var n = af[id];
38077                 if(n){
38078                     n.ui.show();
38079                 }
38080             }
38081         }
38082         this.filtered = {};
38083     }
38084 };
38085 /*
38086  * Based on:
38087  * Ext JS Library 1.1.1
38088  * Copyright(c) 2006-2007, Ext JS, LLC.
38089  *
38090  * Originally Released Under LGPL - original licence link has changed is not relivant.
38091  *
38092  * Fork - LGPL
38093  * <script type="text/javascript">
38094  */
38095  
38096
38097 /**
38098  * @class Roo.tree.TreeSorter
38099  * Provides sorting of nodes in a TreePanel
38100  * 
38101  * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
38102  * @cfg {String} property The named attribute on the node to sort by (defaults to text)
38103  * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
38104  * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
38105  * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
38106  * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
38107  * @constructor
38108  * @param {TreePanel} tree
38109  * @param {Object} config
38110  */
38111 Roo.tree.TreeSorter = function(tree, config){
38112     Roo.apply(this, config);
38113     tree.on("beforechildrenrendered", this.doSort, this);
38114     tree.on("append", this.updateSort, this);
38115     tree.on("insert", this.updateSort, this);
38116     
38117     var dsc = this.dir && this.dir.toLowerCase() == "desc";
38118     var p = this.property || "text";
38119     var sortType = this.sortType;
38120     var fs = this.folderSort;
38121     var cs = this.caseSensitive === true;
38122     var leafAttr = this.leafAttr || 'leaf';
38123
38124     this.sortFn = function(n1, n2){
38125         if(fs){
38126             if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
38127                 return 1;
38128             }
38129             if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
38130                 return -1;
38131             }
38132         }
38133         var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
38134         var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
38135         if(v1 < v2){
38136                         return dsc ? +1 : -1;
38137                 }else if(v1 > v2){
38138                         return dsc ? -1 : +1;
38139         }else{
38140                 return 0;
38141         }
38142     };
38143 };
38144
38145 Roo.tree.TreeSorter.prototype = {
38146     doSort : function(node){
38147         node.sort(this.sortFn);
38148     },
38149     
38150     compareNodes : function(n1, n2){
38151         return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
38152     },
38153     
38154     updateSort : function(tree, node){
38155         if(node.childrenRendered){
38156             this.doSort.defer(1, this, [node]);
38157         }
38158     }
38159 };/*
38160  * Based on:
38161  * Ext JS Library 1.1.1
38162  * Copyright(c) 2006-2007, Ext JS, LLC.
38163  *
38164  * Originally Released Under LGPL - original licence link has changed is not relivant.
38165  *
38166  * Fork - LGPL
38167  * <script type="text/javascript">
38168  */
38169
38170 if(Roo.dd.DropZone){
38171     
38172 Roo.tree.TreeDropZone = function(tree, config){
38173     this.allowParentInsert = false;
38174     this.allowContainerDrop = false;
38175     this.appendOnly = false;
38176     Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
38177     this.tree = tree;
38178     this.lastInsertClass = "x-tree-no-status";
38179     this.dragOverData = {};
38180 };
38181
38182 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
38183     ddGroup : "TreeDD",
38184     scroll:  true,
38185     
38186     expandDelay : 1000,
38187     
38188     expandNode : function(node){
38189         if(node.hasChildNodes() && !node.isExpanded()){
38190             node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
38191         }
38192     },
38193     
38194     queueExpand : function(node){
38195         this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
38196     },
38197     
38198     cancelExpand : function(){
38199         if(this.expandProcId){
38200             clearTimeout(this.expandProcId);
38201             this.expandProcId = false;
38202         }
38203     },
38204     
38205     isValidDropPoint : function(n, pt, dd, e, data){
38206         if(!n || !data){ return false; }
38207         var targetNode = n.node;
38208         var dropNode = data.node;
38209         // default drop rules
38210         if(!(targetNode && targetNode.isTarget && pt)){
38211             return false;
38212         }
38213         if(pt == "append" && targetNode.allowChildren === false){
38214             return false;
38215         }
38216         if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
38217             return false;
38218         }
38219         if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
38220             return false;
38221         }
38222         // reuse the object
38223         var overEvent = this.dragOverData;
38224         overEvent.tree = this.tree;
38225         overEvent.target = targetNode;
38226         overEvent.data = data;
38227         overEvent.point = pt;
38228         overEvent.source = dd;
38229         overEvent.rawEvent = e;
38230         overEvent.dropNode = dropNode;
38231         overEvent.cancel = false;  
38232         var result = this.tree.fireEvent("nodedragover", overEvent);
38233         return overEvent.cancel === false && result !== false;
38234     },
38235     
38236     getDropPoint : function(e, n, dd)
38237     {
38238         var tn = n.node;
38239         if(tn.isRoot){
38240             return tn.allowChildren !== false ? "append" : false; // always append for root
38241         }
38242         var dragEl = n.ddel;
38243         var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
38244         var y = Roo.lib.Event.getPageY(e);
38245         //var noAppend = tn.allowChildren === false || tn.isLeaf();
38246         
38247         // we may drop nodes anywhere, as long as allowChildren has not been set to false..
38248         var noAppend = tn.allowChildren === false;
38249         if(this.appendOnly || tn.parentNode.allowChildren === false){
38250             return noAppend ? false : "append";
38251         }
38252         var noBelow = false;
38253         if(!this.allowParentInsert){
38254             noBelow = tn.hasChildNodes() && tn.isExpanded();
38255         }
38256         var q = (b - t) / (noAppend ? 2 : 3);
38257         if(y >= t && y < (t + q)){
38258             return "above";
38259         }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
38260             return "below";
38261         }else{
38262             return "append";
38263         }
38264     },
38265     
38266     onNodeEnter : function(n, dd, e, data)
38267     {
38268         this.cancelExpand();
38269     },
38270     
38271     onNodeOver : function(n, dd, e, data)
38272     {
38273        
38274         var pt = this.getDropPoint(e, n, dd);
38275         var node = n.node;
38276         
38277         // auto node expand check
38278         if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
38279             this.queueExpand(node);
38280         }else if(pt != "append"){
38281             this.cancelExpand();
38282         }
38283         
38284         // set the insert point style on the target node
38285         var returnCls = this.dropNotAllowed;
38286         if(this.isValidDropPoint(n, pt, dd, e, data)){
38287            if(pt){
38288                var el = n.ddel;
38289                var cls;
38290                if(pt == "above"){
38291                    returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
38292                    cls = "x-tree-drag-insert-above";
38293                }else if(pt == "below"){
38294                    returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
38295                    cls = "x-tree-drag-insert-below";
38296                }else{
38297                    returnCls = "x-tree-drop-ok-append";
38298                    cls = "x-tree-drag-append";
38299                }
38300                if(this.lastInsertClass != cls){
38301                    Roo.fly(el).replaceClass(this.lastInsertClass, cls);
38302                    this.lastInsertClass = cls;
38303                }
38304            }
38305        }
38306        return returnCls;
38307     },
38308     
38309     onNodeOut : function(n, dd, e, data){
38310         
38311         this.cancelExpand();
38312         this.removeDropIndicators(n);
38313     },
38314     
38315     onNodeDrop : function(n, dd, e, data){
38316         var point = this.getDropPoint(e, n, dd);
38317         var targetNode = n.node;
38318         targetNode.ui.startDrop();
38319         if(!this.isValidDropPoint(n, point, dd, e, data)){
38320             targetNode.ui.endDrop();
38321             return false;
38322         }
38323         // first try to find the drop node
38324         var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
38325         var dropEvent = {
38326             tree : this.tree,
38327             target: targetNode,
38328             data: data,
38329             point: point,
38330             source: dd,
38331             rawEvent: e,
38332             dropNode: dropNode,
38333             cancel: !dropNode   
38334         };
38335         var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
38336         if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
38337             targetNode.ui.endDrop();
38338             return false;
38339         }
38340         // allow target changing
38341         targetNode = dropEvent.target;
38342         if(point == "append" && !targetNode.isExpanded()){
38343             targetNode.expand(false, null, function(){
38344                 this.completeDrop(dropEvent);
38345             }.createDelegate(this));
38346         }else{
38347             this.completeDrop(dropEvent);
38348         }
38349         return true;
38350     },
38351     
38352     completeDrop : function(de){
38353         var ns = de.dropNode, p = de.point, t = de.target;
38354         if(!(ns instanceof Array)){
38355             ns = [ns];
38356         }
38357         var n;
38358         for(var i = 0, len = ns.length; i < len; i++){
38359             n = ns[i];
38360             if(p == "above"){
38361                 t.parentNode.insertBefore(n, t);
38362             }else if(p == "below"){
38363                 t.parentNode.insertBefore(n, t.nextSibling);
38364             }else{
38365                 t.appendChild(n);
38366             }
38367         }
38368         n.ui.focus();
38369         if(this.tree.hlDrop){
38370             n.ui.highlight();
38371         }
38372         t.ui.endDrop();
38373         this.tree.fireEvent("nodedrop", de);
38374     },
38375     
38376     afterNodeMoved : function(dd, data, e, targetNode, dropNode){
38377         if(this.tree.hlDrop){
38378             dropNode.ui.focus();
38379             dropNode.ui.highlight();
38380         }
38381         this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
38382     },
38383     
38384     getTree : function(){
38385         return this.tree;
38386     },
38387     
38388     removeDropIndicators : function(n){
38389         if(n && n.ddel){
38390             var el = n.ddel;
38391             Roo.fly(el).removeClass([
38392                     "x-tree-drag-insert-above",
38393                     "x-tree-drag-insert-below",
38394                     "x-tree-drag-append"]);
38395             this.lastInsertClass = "_noclass";
38396         }
38397     },
38398     
38399     beforeDragDrop : function(target, e, id){
38400         this.cancelExpand();
38401         return true;
38402     },
38403     
38404     afterRepair : function(data){
38405         if(data && Roo.enableFx){
38406             data.node.ui.highlight();
38407         }
38408         this.hideProxy();
38409     } 
38410     
38411 });
38412
38413 }
38414 /*
38415  * Based on:
38416  * Ext JS Library 1.1.1
38417  * Copyright(c) 2006-2007, Ext JS, LLC.
38418  *
38419  * Originally Released Under LGPL - original licence link has changed is not relivant.
38420  *
38421  * Fork - LGPL
38422  * <script type="text/javascript">
38423  */
38424  
38425
38426 if(Roo.dd.DragZone){
38427 Roo.tree.TreeDragZone = function(tree, config){
38428     Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
38429     this.tree = tree;
38430 };
38431
38432 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
38433     ddGroup : "TreeDD",
38434    
38435     onBeforeDrag : function(data, e){
38436         var n = data.node;
38437         return n && n.draggable && !n.disabled;
38438     },
38439      
38440     
38441     onInitDrag : function(e){
38442         var data = this.dragData;
38443         this.tree.getSelectionModel().select(data.node);
38444         this.proxy.update("");
38445         data.node.ui.appendDDGhost(this.proxy.ghost.dom);
38446         this.tree.fireEvent("startdrag", this.tree, data.node, e);
38447     },
38448     
38449     getRepairXY : function(e, data){
38450         return data.node.ui.getDDRepairXY();
38451     },
38452     
38453     onEndDrag : function(data, e){
38454         this.tree.fireEvent("enddrag", this.tree, data.node, e);
38455         
38456         
38457     },
38458     
38459     onValidDrop : function(dd, e, id){
38460         this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
38461         this.hideProxy();
38462     },
38463     
38464     beforeInvalidDrop : function(e, id){
38465         // this scrolls the original position back into view
38466         var sm = this.tree.getSelectionModel();
38467         sm.clearSelections();
38468         sm.select(this.dragData.node);
38469     }
38470 });
38471 }/*
38472  * Based on:
38473  * Ext JS Library 1.1.1
38474  * Copyright(c) 2006-2007, Ext JS, LLC.
38475  *
38476  * Originally Released Under LGPL - original licence link has changed is not relivant.
38477  *
38478  * Fork - LGPL
38479  * <script type="text/javascript">
38480  */
38481 /**
38482  * @class Roo.tree.TreeEditor
38483  * @extends Roo.Editor
38484  * Provides editor functionality for inline tree node editing.  Any valid {@link Roo.form.Field} can be used
38485  * as the editor field.
38486  * @constructor
38487  * @param {Object} config (used to be the tree panel.)
38488  * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
38489  * 
38490  * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
38491  * @cfg {Roo.form.TextField} field [required] The field configuration
38492  *
38493  * 
38494  */
38495 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
38496     var tree = config;
38497     var field;
38498     if (oldconfig) { // old style..
38499         field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
38500     } else {
38501         // new style..
38502         tree = config.tree;
38503         config.field = config.field  || {};
38504         config.field.xtype = 'TextField';
38505         field = Roo.factory(config.field, Roo.form);
38506     }
38507     config = config || {};
38508     
38509     
38510     this.addEvents({
38511         /**
38512          * @event beforenodeedit
38513          * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
38514          * false from the handler of this event.
38515          * @param {Editor} this
38516          * @param {Roo.tree.Node} node 
38517          */
38518         "beforenodeedit" : true
38519     });
38520     
38521     //Roo.log(config);
38522     Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
38523
38524     this.tree = tree;
38525
38526     tree.on('beforeclick', this.beforeNodeClick, this);
38527     tree.getTreeEl().on('mousedown', this.hide, this);
38528     this.on('complete', this.updateNode, this);
38529     this.on('beforestartedit', this.fitToTree, this);
38530     this.on('startedit', this.bindScroll, this, {delay:10});
38531     this.on('specialkey', this.onSpecialKey, this);
38532 };
38533
38534 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
38535     /**
38536      * @cfg {String} alignment
38537      * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
38538      */
38539     alignment: "l-l",
38540     // inherit
38541     autoSize: false,
38542     /**
38543      * @cfg {Boolean} hideEl
38544      * True to hide the bound element while the editor is displayed (defaults to false)
38545      */
38546     hideEl : false,
38547     /**
38548      * @cfg {String} cls
38549      * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
38550      */
38551     cls: "x-small-editor x-tree-editor",
38552     /**
38553      * @cfg {Boolean} shim
38554      * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
38555      */
38556     shim:false,
38557     // inherit
38558     shadow:"frame",
38559     /**
38560      * @cfg {Number} maxWidth
38561      * The maximum width in pixels of the editor field (defaults to 250).  Note that if the maxWidth would exceed
38562      * the containing tree element's size, it will be automatically limited for you to the container width, taking
38563      * scroll and client offsets into account prior to each edit.
38564      */
38565     maxWidth: 250,
38566
38567     editDelay : 350,
38568
38569     // private
38570     fitToTree : function(ed, el){
38571         var td = this.tree.getTreeEl().dom, nd = el.dom;
38572         if(td.scrollLeft >  nd.offsetLeft){ // ensure the node left point is visible
38573             td.scrollLeft = nd.offsetLeft;
38574         }
38575         var w = Math.min(
38576                 this.maxWidth,
38577                 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
38578         this.setSize(w, '');
38579         
38580         return this.fireEvent('beforenodeedit', this, this.editNode);
38581         
38582     },
38583
38584     // private
38585     triggerEdit : function(node){
38586         this.completeEdit();
38587         this.editNode = node;
38588         this.startEdit(node.ui.textNode, node.text);
38589     },
38590
38591     // private
38592     bindScroll : function(){
38593         this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
38594     },
38595
38596     // private
38597     beforeNodeClick : function(node, e){
38598         var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
38599         this.lastClick = new Date();
38600         if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
38601             e.stopEvent();
38602             this.triggerEdit(node);
38603             return false;
38604         }
38605         return true;
38606     },
38607
38608     // private
38609     updateNode : function(ed, value){
38610         this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
38611         this.editNode.setText(value);
38612     },
38613
38614     // private
38615     onHide : function(){
38616         Roo.tree.TreeEditor.superclass.onHide.call(this);
38617         if(this.editNode){
38618             this.editNode.ui.focus();
38619         }
38620     },
38621
38622     // private
38623     onSpecialKey : function(field, e){
38624         var k = e.getKey();
38625         if(k == e.ESC){
38626             e.stopEvent();
38627             this.cancelEdit();
38628         }else if(k == e.ENTER && !e.hasModifier()){
38629             e.stopEvent();
38630             this.completeEdit();
38631         }
38632     }
38633 });//<Script type="text/javascript">
38634 /*
38635  * Based on:
38636  * Ext JS Library 1.1.1
38637  * Copyright(c) 2006-2007, Ext JS, LLC.
38638  *
38639  * Originally Released Under LGPL - original licence link has changed is not relivant.
38640  *
38641  * Fork - LGPL
38642  * <script type="text/javascript">
38643  */
38644  
38645 /**
38646  * Not documented??? - probably should be...
38647  */
38648
38649 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
38650     //focus: Roo.emptyFn, // prevent odd scrolling behavior
38651     
38652     renderElements : function(n, a, targetNode, bulkRender){
38653         //consel.log("renderElements?");
38654         this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
38655
38656         var t = n.getOwnerTree();
38657         var tid = Pman.Tab.Document_TypesTree.tree.el.id;
38658         
38659         var cols = t.columns;
38660         var bw = t.borderWidth;
38661         var c = cols[0];
38662         var href = a.href ? a.href : Roo.isGecko ? "" : "#";
38663          var cb = typeof a.checked == "boolean";
38664         var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
38665         var colcls = 'x-t-' + tid + '-c0';
38666         var buf = [
38667             '<li class="x-tree-node">',
38668             
38669                 
38670                 '<div class="x-tree-node-el ', a.cls,'">',
38671                     // extran...
38672                     '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
38673                 
38674                 
38675                         '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
38676                         '<img src="', this.emptyIcon, '" class="x-tree-ec-icon  " />',
38677                         '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
38678                            (a.icon ? ' x-tree-node-inline-icon' : ''),
38679                            (a.iconCls ? ' '+a.iconCls : ''),
38680                            '" unselectable="on" />',
38681                         (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + 
38682                              (a.checked ? 'checked="checked" />' : ' />')) : ''),
38683                              
38684                         '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
38685                             (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
38686                             '<span unselectable="on" qtip="' + tx + '">',
38687                              tx,
38688                              '</span></a>' ,
38689                     '</div>',
38690                      '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
38691                             (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
38692                  ];
38693         for(var i = 1, len = cols.length; i < len; i++){
38694             c = cols[i];
38695             colcls = 'x-t-' + tid + '-c' +i;
38696             tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
38697             buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
38698                         '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
38699                       "</div>");
38700          }
38701          
38702          buf.push(
38703             '</a>',
38704             '<div class="x-clear"></div></div>',
38705             '<ul class="x-tree-node-ct" style="display:none;"></ul>',
38706             "</li>");
38707         
38708         if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
38709             this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
38710                                 n.nextSibling.ui.getEl(), buf.join(""));
38711         }else{
38712             this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
38713         }
38714         var el = this.wrap.firstChild;
38715         this.elRow = el;
38716         this.elNode = el.firstChild;
38717         this.ranchor = el.childNodes[1];
38718         this.ctNode = this.wrap.childNodes[1];
38719         var cs = el.firstChild.childNodes;
38720         this.indentNode = cs[0];
38721         this.ecNode = cs[1];
38722         this.iconNode = cs[2];
38723         var index = 3;
38724         if(cb){
38725             this.checkbox = cs[3];
38726             index++;
38727         }
38728         this.anchor = cs[index];
38729         
38730         this.textNode = cs[index].firstChild;
38731         
38732         //el.on("click", this.onClick, this);
38733         //el.on("dblclick", this.onDblClick, this);
38734         
38735         
38736        // console.log(this);
38737     },
38738     initEvents : function(){
38739         Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
38740         
38741             
38742         var a = this.ranchor;
38743
38744         var el = Roo.get(a);
38745
38746         if(Roo.isOpera){ // opera render bug ignores the CSS
38747             el.setStyle("text-decoration", "none");
38748         }
38749
38750         el.on("click", this.onClick, this);
38751         el.on("dblclick", this.onDblClick, this);
38752         el.on("contextmenu", this.onContextMenu, this);
38753         
38754     },
38755     
38756     /*onSelectedChange : function(state){
38757         if(state){
38758             this.focus();
38759             this.addClass("x-tree-selected");
38760         }else{
38761             //this.blur();
38762             this.removeClass("x-tree-selected");
38763         }
38764     },*/
38765     addClass : function(cls){
38766         if(this.elRow){
38767             Roo.fly(this.elRow).addClass(cls);
38768         }
38769         
38770     },
38771     
38772     
38773     removeClass : function(cls){
38774         if(this.elRow){
38775             Roo.fly(this.elRow).removeClass(cls);
38776         }
38777     }
38778
38779     
38780     
38781 });//<Script type="text/javascript">
38782
38783 /*
38784  * Based on:
38785  * Ext JS Library 1.1.1
38786  * Copyright(c) 2006-2007, Ext JS, LLC.
38787  *
38788  * Originally Released Under LGPL - original licence link has changed is not relivant.
38789  *
38790  * Fork - LGPL
38791  * <script type="text/javascript">
38792  */
38793  
38794
38795 /**
38796  * @class Roo.tree.ColumnTree
38797  * @extends Roo.tree.TreePanel
38798  * @cfg {Object} columns  Including width, header, renderer, cls, dataIndex 
38799  * @cfg {int} borderWidth  compined right/left border allowance
38800  * @constructor
38801  * @param {String/HTMLElement/Element} el The container element
38802  * @param {Object} config
38803  */
38804 Roo.tree.ColumnTree =  function(el, config)
38805 {
38806    Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
38807    this.addEvents({
38808         /**
38809         * @event resize
38810         * Fire this event on a container when it resizes
38811         * @param {int} w Width
38812         * @param {int} h Height
38813         */
38814        "resize" : true
38815     });
38816     this.on('resize', this.onResize, this);
38817 };
38818
38819 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
38820     //lines:false,
38821     
38822     
38823     borderWidth: Roo.isBorderBox ? 0 : 2, 
38824     headEls : false,
38825     
38826     render : function(){
38827         // add the header.....
38828        
38829         Roo.tree.ColumnTree.superclass.render.apply(this);
38830         
38831         this.el.addClass('x-column-tree');
38832         
38833         this.headers = this.el.createChild(
38834             {cls:'x-tree-headers'},this.innerCt.dom);
38835    
38836         var cols = this.columns, c;
38837         var totalWidth = 0;
38838         this.headEls = [];
38839         var  len = cols.length;
38840         for(var i = 0; i < len; i++){
38841              c = cols[i];
38842              totalWidth += c.width;
38843             this.headEls.push(this.headers.createChild({
38844                  cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
38845                  cn: {
38846                      cls:'x-tree-hd-text',
38847                      html: c.header
38848                  },
38849                  style:'width:'+(c.width-this.borderWidth)+'px;'
38850              }));
38851         }
38852         this.headers.createChild({cls:'x-clear'});
38853         // prevent floats from wrapping when clipped
38854         this.headers.setWidth(totalWidth);
38855         //this.innerCt.setWidth(totalWidth);
38856         this.innerCt.setStyle({ overflow: 'auto' });
38857         this.onResize(this.width, this.height);
38858              
38859         
38860     },
38861     onResize : function(w,h)
38862     {
38863         this.height = h;
38864         this.width = w;
38865         // resize cols..
38866         this.innerCt.setWidth(this.width);
38867         this.innerCt.setHeight(this.height-20);
38868         
38869         // headers...
38870         var cols = this.columns, c;
38871         var totalWidth = 0;
38872         var expEl = false;
38873         var len = cols.length;
38874         for(var i = 0; i < len; i++){
38875             c = cols[i];
38876             if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
38877                 // it's the expander..
38878                 expEl  = this.headEls[i];
38879                 continue;
38880             }
38881             totalWidth += c.width;
38882             
38883         }
38884         if (expEl) {
38885             expEl.setWidth(  ((w - totalWidth)-this.borderWidth - 20));
38886         }
38887         this.headers.setWidth(w-20);
38888
38889         
38890         
38891         
38892     }
38893 });
38894 /*
38895  * Based on:
38896  * Ext JS Library 1.1.1
38897  * Copyright(c) 2006-2007, Ext JS, LLC.
38898  *
38899  * Originally Released Under LGPL - original licence link has changed is not relivant.
38900  *
38901  * Fork - LGPL
38902  * <script type="text/javascript">
38903  */
38904  
38905 /**
38906  * @class Roo.menu.Menu
38907  * @extends Roo.util.Observable
38908  * @children Roo.menu.Item Roo.menu.Separator Roo.menu.TextItem
38909  * A menu object.  This is the container to which you add all other menu items.  Menu can also serve a as a base class
38910  * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
38911  * @constructor
38912  * Creates a new Menu
38913  * @param {Object} config Configuration options
38914  */
38915 Roo.menu.Menu = function(config){
38916     
38917     Roo.menu.Menu.superclass.constructor.call(this, config);
38918     
38919     this.id = this.id || Roo.id();
38920     this.addEvents({
38921         /**
38922          * @event beforeshow
38923          * Fires before this menu is displayed
38924          * @param {Roo.menu.Menu} this
38925          */
38926         beforeshow : true,
38927         /**
38928          * @event beforehide
38929          * Fires before this menu is hidden
38930          * @param {Roo.menu.Menu} this
38931          */
38932         beforehide : true,
38933         /**
38934          * @event show
38935          * Fires after this menu is displayed
38936          * @param {Roo.menu.Menu} this
38937          */
38938         show : true,
38939         /**
38940          * @event hide
38941          * Fires after this menu is hidden
38942          * @param {Roo.menu.Menu} this
38943          */
38944         hide : true,
38945         /**
38946          * @event click
38947          * Fires when this menu is clicked (or when the enter key is pressed while it is active)
38948          * @param {Roo.menu.Menu} this
38949          * @param {Roo.menu.Item} menuItem The menu item that was clicked
38950          * @param {Roo.EventObject} e
38951          */
38952         click : true,
38953         /**
38954          * @event mouseover
38955          * Fires when the mouse is hovering over this menu
38956          * @param {Roo.menu.Menu} this
38957          * @param {Roo.EventObject} e
38958          * @param {Roo.menu.Item} menuItem The menu item that was clicked
38959          */
38960         mouseover : true,
38961         /**
38962          * @event mouseout
38963          * Fires when the mouse exits this menu
38964          * @param {Roo.menu.Menu} this
38965          * @param {Roo.EventObject} e
38966          * @param {Roo.menu.Item} menuItem The menu item that was clicked
38967          */
38968         mouseout : true,
38969         /**
38970          * @event itemclick
38971          * Fires when a menu item contained in this menu is clicked
38972          * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
38973          * @param {Roo.EventObject} e
38974          */
38975         itemclick: true
38976     });
38977     if (this.registerMenu) {
38978         Roo.menu.MenuMgr.register(this);
38979     }
38980     
38981     var mis = this.items;
38982     this.items = new Roo.util.MixedCollection();
38983     if(mis){
38984         this.add.apply(this, mis);
38985     }
38986 };
38987
38988 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
38989     /**
38990      * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
38991      */
38992     minWidth : 120,
38993     /**
38994      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
38995      * for bottom-right shadow (defaults to "sides")
38996      */
38997     shadow : "sides",
38998     /**
38999      * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
39000      * this menu (defaults to "tl-tr?")
39001      */
39002     subMenuAlign : "tl-tr?",
39003     /**
39004      * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
39005      * relative to its element of origin (defaults to "tl-bl?")
39006      */
39007     defaultAlign : "tl-bl?",
39008     /**
39009      * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
39010      */
39011     allowOtherMenus : false,
39012     /**
39013      * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
39014      */
39015     registerMenu : true,
39016
39017     hidden:true,
39018
39019     // private
39020     render : function(){
39021         if(this.el){
39022             return;
39023         }
39024         var el = this.el = new Roo.Layer({
39025             cls: "x-menu",
39026             shadow:this.shadow,
39027             constrain: false,
39028             parentEl: this.parentEl || document.body,
39029             zindex:15000
39030         });
39031
39032         this.keyNav = new Roo.menu.MenuNav(this);
39033
39034         if(this.plain){
39035             el.addClass("x-menu-plain");
39036         }
39037         if(this.cls){
39038             el.addClass(this.cls);
39039         }
39040         // generic focus element
39041         this.focusEl = el.createChild({
39042             tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
39043         });
39044         var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
39045         //disabling touch- as it's causing issues ..
39046         //ul.on(Roo.isTouch ? 'touchstart' : 'click'   , this.onClick, this);
39047         ul.on('click'   , this.onClick, this);
39048         
39049         
39050         ul.on("mouseover", this.onMouseOver, this);
39051         ul.on("mouseout", this.onMouseOut, this);
39052         this.items.each(function(item){
39053             if (item.hidden) {
39054                 return;
39055             }
39056             
39057             var li = document.createElement("li");
39058             li.className = "x-menu-list-item";
39059             ul.dom.appendChild(li);
39060             item.render(li, this);
39061         }, this);
39062         this.ul = ul;
39063         this.autoWidth();
39064     },
39065
39066     // private
39067     autoWidth : function(){
39068         var el = this.el, ul = this.ul;
39069         if(!el){
39070             return;
39071         }
39072         var w = this.width;
39073         if(w){
39074             el.setWidth(w);
39075         }else if(Roo.isIE){
39076             el.setWidth(this.minWidth);
39077             var t = el.dom.offsetWidth; // force recalc
39078             el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
39079         }
39080     },
39081
39082     // private
39083     delayAutoWidth : function(){
39084         if(this.rendered){
39085             if(!this.awTask){
39086                 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
39087             }
39088             this.awTask.delay(20);
39089         }
39090     },
39091
39092     // private
39093     findTargetItem : function(e){
39094         var t = e.getTarget(".x-menu-list-item", this.ul,  true);
39095         if(t && t.menuItemId){
39096             return this.items.get(t.menuItemId);
39097         }
39098     },
39099
39100     // private
39101     onClick : function(e){
39102         Roo.log("menu.onClick");
39103         var t = this.findTargetItem(e);
39104         if(!t){
39105             return;
39106         }
39107         Roo.log(e);
39108         if (Roo.isTouch && e.type == 'touchstart' && t.menu  && !t.disabled) {
39109             if(t == this.activeItem && t.shouldDeactivate(e)){
39110                 this.activeItem.deactivate();
39111                 delete this.activeItem;
39112                 return;
39113             }
39114             if(t.canActivate){
39115                 this.setActiveItem(t, true);
39116             }
39117             return;
39118             
39119             
39120         }
39121         
39122         t.onClick(e);
39123         this.fireEvent("click", this, t, e);
39124     },
39125
39126     // private
39127     setActiveItem : function(item, autoExpand){
39128         if(item != this.activeItem){
39129             if(this.activeItem){
39130                 this.activeItem.deactivate();
39131             }
39132             this.activeItem = item;
39133             item.activate(autoExpand);
39134         }else if(autoExpand){
39135             item.expandMenu();
39136         }
39137     },
39138
39139     // private
39140     tryActivate : function(start, step){
39141         var items = this.items;
39142         for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
39143             var item = items.get(i);
39144             if(!item.disabled && item.canActivate){
39145                 this.setActiveItem(item, false);
39146                 return item;
39147             }
39148         }
39149         return false;
39150     },
39151
39152     // private
39153     onMouseOver : function(e){
39154         var t;
39155         if(t = this.findTargetItem(e)){
39156             if(t.canActivate && !t.disabled){
39157                 this.setActiveItem(t, true);
39158             }
39159         }
39160         this.fireEvent("mouseover", this, e, t);
39161     },
39162
39163     // private
39164     onMouseOut : function(e){
39165         var t;
39166         if(t = this.findTargetItem(e)){
39167             if(t == this.activeItem && t.shouldDeactivate(e)){
39168                 this.activeItem.deactivate();
39169                 delete this.activeItem;
39170             }
39171         }
39172         this.fireEvent("mouseout", this, e, t);
39173     },
39174
39175     /**
39176      * Read-only.  Returns true if the menu is currently displayed, else false.
39177      * @type Boolean
39178      */
39179     isVisible : function(){
39180         return this.el && !this.hidden;
39181     },
39182
39183     /**
39184      * Displays this menu relative to another element
39185      * @param {String/HTMLElement/Roo.Element} element The element to align to
39186      * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
39187      * the element (defaults to this.defaultAlign)
39188      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
39189      */
39190     show : function(el, pos, parentMenu){
39191         this.parentMenu = parentMenu;
39192         if(!this.el){
39193             this.render();
39194         }
39195         this.fireEvent("beforeshow", this);
39196         this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
39197     },
39198
39199     /**
39200      * Displays this menu at a specific xy position
39201      * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
39202      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
39203      */
39204     showAt : function(xy, parentMenu, /* private: */_e){
39205         this.parentMenu = parentMenu;
39206         if(!this.el){
39207             this.render();
39208         }
39209         if(_e !== false){
39210             this.fireEvent("beforeshow", this);
39211             xy = this.el.adjustForConstraints(xy);
39212         }
39213         this.el.setXY(xy);
39214         this.el.show();
39215         this.hidden = false;
39216         this.focus();
39217         this.fireEvent("show", this);
39218     },
39219
39220     focus : function(){
39221         if(!this.hidden){
39222             this.doFocus.defer(50, this);
39223         }
39224     },
39225
39226     doFocus : function(){
39227         if(!this.hidden){
39228             this.focusEl.focus();
39229         }
39230     },
39231
39232     /**
39233      * Hides this menu and optionally all parent menus
39234      * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
39235      */
39236     hide : function(deep){
39237         if(this.el && this.isVisible()){
39238             this.fireEvent("beforehide", this);
39239             if(this.activeItem){
39240                 this.activeItem.deactivate();
39241                 this.activeItem = null;
39242             }
39243             this.el.hide();
39244             this.hidden = true;
39245             this.fireEvent("hide", this);
39246         }
39247         if(deep === true && this.parentMenu){
39248             this.parentMenu.hide(true);
39249         }
39250     },
39251
39252     /**
39253      * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
39254      * Any of the following are valid:
39255      * <ul>
39256      * <li>Any menu item object based on {@link Roo.menu.Item}</li>
39257      * <li>An HTMLElement object which will be converted to a menu item</li>
39258      * <li>A menu item config object that will be created as a new menu item</li>
39259      * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
39260      * it will be converted into a {@link Roo.menu.TextItem} and added</li>
39261      * </ul>
39262      * Usage:
39263      * <pre><code>
39264 // Create the menu
39265 var menu = new Roo.menu.Menu();
39266
39267 // Create a menu item to add by reference
39268 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
39269
39270 // Add a bunch of items at once using different methods.
39271 // Only the last item added will be returned.
39272 var item = menu.add(
39273     menuItem,                // add existing item by ref
39274     'Dynamic Item',          // new TextItem
39275     '-',                     // new separator
39276     { text: 'Config Item' }  // new item by config
39277 );
39278 </code></pre>
39279      * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
39280      * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
39281      */
39282     add : function(){
39283         var a = arguments, l = a.length, item;
39284         for(var i = 0; i < l; i++){
39285             var el = a[i];
39286             if ((typeof(el) == "object") && el.xtype && el.xns) {
39287                 el = Roo.factory(el, Roo.menu);
39288             }
39289             
39290             if(el.render){ // some kind of Item
39291                 item = this.addItem(el);
39292             }else if(typeof el == "string"){ // string
39293                 if(el == "separator" || el == "-"){
39294                     item = this.addSeparator();
39295                 }else{
39296                     item = this.addText(el);
39297                 }
39298             }else if(el.tagName || el.el){ // element
39299                 item = this.addElement(el);
39300             }else if(typeof el == "object"){ // must be menu item config?
39301                 item = this.addMenuItem(el);
39302             }
39303         }
39304         return item;
39305     },
39306
39307     /**
39308      * Returns this menu's underlying {@link Roo.Element} object
39309      * @return {Roo.Element} The element
39310      */
39311     getEl : function(){
39312         if(!this.el){
39313             this.render();
39314         }
39315         return this.el;
39316     },
39317
39318     /**
39319      * Adds a separator bar to the menu
39320      * @return {Roo.menu.Item} The menu item that was added
39321      */
39322     addSeparator : function(){
39323         return this.addItem(new Roo.menu.Separator());
39324     },
39325
39326     /**
39327      * Adds an {@link Roo.Element} object to the menu
39328      * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
39329      * @return {Roo.menu.Item} The menu item that was added
39330      */
39331     addElement : function(el){
39332         return this.addItem(new Roo.menu.BaseItem(el));
39333     },
39334
39335     /**
39336      * Adds an existing object based on {@link Roo.menu.Item} to the menu
39337      * @param {Roo.menu.Item} item The menu item to add
39338      * @return {Roo.menu.Item} The menu item that was added
39339      */
39340     addItem : function(item){
39341         this.items.add(item);
39342         if(this.ul){
39343             var li = document.createElement("li");
39344             li.className = "x-menu-list-item";
39345             this.ul.dom.appendChild(li);
39346             item.render(li, this);
39347             this.delayAutoWidth();
39348         }
39349         return item;
39350     },
39351
39352     /**
39353      * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
39354      * @param {Object} config A MenuItem config object
39355      * @return {Roo.menu.Item} The menu item that was added
39356      */
39357     addMenuItem : function(config){
39358         if(!(config instanceof Roo.menu.Item)){
39359             if(typeof config.checked == "boolean"){ // must be check menu item config?
39360                 config = new Roo.menu.CheckItem(config);
39361             }else{
39362                 config = new Roo.menu.Item(config);
39363             }
39364         }
39365         return this.addItem(config);
39366     },
39367
39368     /**
39369      * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
39370      * @param {String} text The text to display in the menu item
39371      * @return {Roo.menu.Item} The menu item that was added
39372      */
39373     addText : function(text){
39374         return this.addItem(new Roo.menu.TextItem({ text : text }));
39375     },
39376
39377     /**
39378      * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
39379      * @param {Number} index The index in the menu's list of current items where the new item should be inserted
39380      * @param {Roo.menu.Item} item The menu item to add
39381      * @return {Roo.menu.Item} The menu item that was added
39382      */
39383     insert : function(index, item){
39384         this.items.insert(index, item);
39385         if(this.ul){
39386             var li = document.createElement("li");
39387             li.className = "x-menu-list-item";
39388             this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
39389             item.render(li, this);
39390             this.delayAutoWidth();
39391         }
39392         return item;
39393     },
39394
39395     /**
39396      * Removes an {@link Roo.menu.Item} from the menu and destroys the object
39397      * @param {Roo.menu.Item} item The menu item to remove
39398      */
39399     remove : function(item){
39400         this.items.removeKey(item.id);
39401         item.destroy();
39402     },
39403
39404     /**
39405      * Removes and destroys all items in the menu
39406      */
39407     removeAll : function(){
39408         var f;
39409         while(f = this.items.first()){
39410             this.remove(f);
39411         }
39412     }
39413 });
39414
39415 // MenuNav is a private utility class used internally by the Menu
39416 Roo.menu.MenuNav = function(menu){
39417     Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
39418     this.scope = this.menu = menu;
39419 };
39420
39421 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
39422     doRelay : function(e, h){
39423         var k = e.getKey();
39424         if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
39425             this.menu.tryActivate(0, 1);
39426             return false;
39427         }
39428         return h.call(this.scope || this, e, this.menu);
39429     },
39430
39431     up : function(e, m){
39432         if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
39433             m.tryActivate(m.items.length-1, -1);
39434         }
39435     },
39436
39437     down : function(e, m){
39438         if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
39439             m.tryActivate(0, 1);
39440         }
39441     },
39442
39443     right : function(e, m){
39444         if(m.activeItem){
39445             m.activeItem.expandMenu(true);
39446         }
39447     },
39448
39449     left : function(e, m){
39450         m.hide();
39451         if(m.parentMenu && m.parentMenu.activeItem){
39452             m.parentMenu.activeItem.activate();
39453         }
39454     },
39455
39456     enter : function(e, m){
39457         if(m.activeItem){
39458             e.stopPropagation();
39459             m.activeItem.onClick(e);
39460             m.fireEvent("click", this, m.activeItem);
39461             return true;
39462         }
39463     }
39464 });/*
39465  * Based on:
39466  * Ext JS Library 1.1.1
39467  * Copyright(c) 2006-2007, Ext JS, LLC.
39468  *
39469  * Originally Released Under LGPL - original licence link has changed is not relivant.
39470  *
39471  * Fork - LGPL
39472  * <script type="text/javascript">
39473  */
39474  
39475 /**
39476  * @class Roo.menu.MenuMgr
39477  * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
39478  * @static
39479  */
39480 Roo.menu.MenuMgr = function(){
39481    var menus, active, groups = {}, attached = false, lastShow = new Date();
39482
39483    // private - called when first menu is created
39484    function init(){
39485        menus = {};
39486        active = new Roo.util.MixedCollection();
39487        Roo.get(document).addKeyListener(27, function(){
39488            if(active.length > 0){
39489                hideAll();
39490            }
39491        });
39492    }
39493
39494    // private
39495    function hideAll(){
39496        if(active && active.length > 0){
39497            var c = active.clone();
39498            c.each(function(m){
39499                m.hide();
39500            });
39501        }
39502    }
39503
39504    // private
39505    function onHide(m){
39506        active.remove(m);
39507        if(active.length < 1){
39508            Roo.get(document).un("mousedown", onMouseDown);
39509            attached = false;
39510        }
39511    }
39512
39513    // private
39514    function onShow(m){
39515        var last = active.last();
39516        lastShow = new Date();
39517        active.add(m);
39518        if(!attached){
39519            Roo.get(document).on("mousedown", onMouseDown);
39520            attached = true;
39521        }
39522        if(m.parentMenu){
39523           m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
39524           m.parentMenu.activeChild = m;
39525        }else if(last && last.isVisible()){
39526           m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
39527        }
39528    }
39529
39530    // private
39531    function onBeforeHide(m){
39532        if(m.activeChild){
39533            m.activeChild.hide();
39534        }
39535        if(m.autoHideTimer){
39536            clearTimeout(m.autoHideTimer);
39537            delete m.autoHideTimer;
39538        }
39539    }
39540
39541    // private
39542    function onBeforeShow(m){
39543        var pm = m.parentMenu;
39544        if(!pm && !m.allowOtherMenus){
39545            hideAll();
39546        }else if(pm && pm.activeChild && active != m){
39547            pm.activeChild.hide();
39548        }
39549    }
39550
39551    // private
39552    function onMouseDown(e){
39553        if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
39554            hideAll();
39555        }
39556    }
39557
39558    // private
39559    function onBeforeCheck(mi, state){
39560        if(state){
39561            var g = groups[mi.group];
39562            for(var i = 0, l = g.length; i < l; i++){
39563                if(g[i] != mi){
39564                    g[i].setChecked(false);
39565                }
39566            }
39567        }
39568    }
39569
39570    return {
39571
39572        /**
39573         * Hides all menus that are currently visible
39574         */
39575        hideAll : function(){
39576             hideAll();  
39577        },
39578
39579        // private
39580        register : function(menu){
39581            if(!menus){
39582                init();
39583            }
39584            menus[menu.id] = menu;
39585            menu.on("beforehide", onBeforeHide);
39586            menu.on("hide", onHide);
39587            menu.on("beforeshow", onBeforeShow);
39588            menu.on("show", onShow);
39589            var g = menu.group;
39590            if(g && menu.events["checkchange"]){
39591                if(!groups[g]){
39592                    groups[g] = [];
39593                }
39594                groups[g].push(menu);
39595                menu.on("checkchange", onCheck);
39596            }
39597        },
39598
39599         /**
39600          * Returns a {@link Roo.menu.Menu} object
39601          * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
39602          * be used to generate and return a new Menu instance.
39603          */
39604        get : function(menu){
39605            if(typeof menu == "string"){ // menu id
39606                return menus[menu];
39607            }else if(menu.events){  // menu instance
39608                return menu;
39609            }else if(typeof menu.length == 'number'){ // array of menu items?
39610                return new Roo.menu.Menu({items:menu});
39611            }else{ // otherwise, must be a config
39612                return new Roo.menu.Menu(menu);
39613            }
39614        },
39615
39616        // private
39617        unregister : function(menu){
39618            delete menus[menu.id];
39619            menu.un("beforehide", onBeforeHide);
39620            menu.un("hide", onHide);
39621            menu.un("beforeshow", onBeforeShow);
39622            menu.un("show", onShow);
39623            var g = menu.group;
39624            if(g && menu.events["checkchange"]){
39625                groups[g].remove(menu);
39626                menu.un("checkchange", onCheck);
39627            }
39628        },
39629
39630        // private
39631        registerCheckable : function(menuItem){
39632            var g = menuItem.group;
39633            if(g){
39634                if(!groups[g]){
39635                    groups[g] = [];
39636                }
39637                groups[g].push(menuItem);
39638                menuItem.on("beforecheckchange", onBeforeCheck);
39639            }
39640        },
39641
39642        // private
39643        unregisterCheckable : function(menuItem){
39644            var g = menuItem.group;
39645            if(g){
39646                groups[g].remove(menuItem);
39647                menuItem.un("beforecheckchange", onBeforeCheck);
39648            }
39649        }
39650    };
39651 }();/*
39652  * Based on:
39653  * Ext JS Library 1.1.1
39654  * Copyright(c) 2006-2007, Ext JS, LLC.
39655  *
39656  * Originally Released Under LGPL - original licence link has changed is not relivant.
39657  *
39658  * Fork - LGPL
39659  * <script type="text/javascript">
39660  */
39661  
39662
39663 /**
39664  * @class Roo.menu.BaseItem
39665  * @extends Roo.Component
39666  * @abstract
39667  * The base class for all items that render into menus.  BaseItem provides default rendering, activated state
39668  * management and base configuration options shared by all menu components.
39669  * @constructor
39670  * Creates a new BaseItem
39671  * @param {Object} config Configuration options
39672  */
39673 Roo.menu.BaseItem = function(config){
39674     Roo.menu.BaseItem.superclass.constructor.call(this, config);
39675
39676     this.addEvents({
39677         /**
39678          * @event click
39679          * Fires when this item is clicked
39680          * @param {Roo.menu.BaseItem} this
39681          * @param {Roo.EventObject} e
39682          */
39683         click: true,
39684         /**
39685          * @event activate
39686          * Fires when this item is activated
39687          * @param {Roo.menu.BaseItem} this
39688          */
39689         activate : true,
39690         /**
39691          * @event deactivate
39692          * Fires when this item is deactivated
39693          * @param {Roo.menu.BaseItem} this
39694          */
39695         deactivate : true
39696     });
39697
39698     if(this.handler){
39699         this.on("click", this.handler, this.scope, true);
39700     }
39701 };
39702
39703 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
39704     /**
39705      * @cfg {Function} handler
39706      * A function that will handle the click event of this menu item (defaults to undefined)
39707      */
39708     /**
39709      * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
39710      */
39711     canActivate : false,
39712     
39713      /**
39714      * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
39715      */
39716     hidden: false,
39717     
39718     /**
39719      * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
39720      */
39721     activeClass : "x-menu-item-active",
39722     /**
39723      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
39724      */
39725     hideOnClick : true,
39726     /**
39727      * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
39728      */
39729     hideDelay : 100,
39730
39731     // private
39732     ctype: "Roo.menu.BaseItem",
39733
39734     // private
39735     actionMode : "container",
39736
39737     // private
39738     render : function(container, parentMenu){
39739         this.parentMenu = parentMenu;
39740         Roo.menu.BaseItem.superclass.render.call(this, container);
39741         this.container.menuItemId = this.id;
39742     },
39743
39744     // private
39745     onRender : function(container, position){
39746         this.el = Roo.get(this.el);
39747         container.dom.appendChild(this.el.dom);
39748     },
39749
39750     // private
39751     onClick : function(e){
39752         if(!this.disabled && this.fireEvent("click", this, e) !== false
39753                 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
39754             this.handleClick(e);
39755         }else{
39756             e.stopEvent();
39757         }
39758     },
39759
39760     // private
39761     activate : function(){
39762         if(this.disabled){
39763             return false;
39764         }
39765         var li = this.container;
39766         li.addClass(this.activeClass);
39767         this.region = li.getRegion().adjust(2, 2, -2, -2);
39768         this.fireEvent("activate", this);
39769         return true;
39770     },
39771
39772     // private
39773     deactivate : function(){
39774         this.container.removeClass(this.activeClass);
39775         this.fireEvent("deactivate", this);
39776     },
39777
39778     // private
39779     shouldDeactivate : function(e){
39780         return !this.region || !this.region.contains(e.getPoint());
39781     },
39782
39783     // private
39784     handleClick : function(e){
39785         if(this.hideOnClick){
39786             this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
39787         }
39788     },
39789
39790     // private
39791     expandMenu : function(autoActivate){
39792         // do nothing
39793     },
39794
39795     // private
39796     hideMenu : function(){
39797         // do nothing
39798     }
39799 });/*
39800  * Based on:
39801  * Ext JS Library 1.1.1
39802  * Copyright(c) 2006-2007, Ext JS, LLC.
39803  *
39804  * Originally Released Under LGPL - original licence link has changed is not relivant.
39805  *
39806  * Fork - LGPL
39807  * <script type="text/javascript">
39808  */
39809  
39810 /**
39811  * @class Roo.menu.Adapter
39812  * @extends Roo.menu.BaseItem
39813  * @abstract
39814  * A base utility class that adapts a non-menu component so that it can be wrapped by a menu item and added to a menu.
39815  * It provides basic rendering, activation management and enable/disable logic required to work in menus.
39816  * @constructor
39817  * Creates a new Adapter
39818  * @param {Object} config Configuration options
39819  */
39820 Roo.menu.Adapter = function(component, config){
39821     Roo.menu.Adapter.superclass.constructor.call(this, config);
39822     this.component = component;
39823 };
39824 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
39825     // private
39826     canActivate : true,
39827
39828     // private
39829     onRender : function(container, position){
39830         this.component.render(container);
39831         this.el = this.component.getEl();
39832     },
39833
39834     // private
39835     activate : function(){
39836         if(this.disabled){
39837             return false;
39838         }
39839         this.component.focus();
39840         this.fireEvent("activate", this);
39841         return true;
39842     },
39843
39844     // private
39845     deactivate : function(){
39846         this.fireEvent("deactivate", this);
39847     },
39848
39849     // private
39850     disable : function(){
39851         this.component.disable();
39852         Roo.menu.Adapter.superclass.disable.call(this);
39853     },
39854
39855     // private
39856     enable : function(){
39857         this.component.enable();
39858         Roo.menu.Adapter.superclass.enable.call(this);
39859     }
39860 });/*
39861  * Based on:
39862  * Ext JS Library 1.1.1
39863  * Copyright(c) 2006-2007, Ext JS, LLC.
39864  *
39865  * Originally Released Under LGPL - original licence link has changed is not relivant.
39866  *
39867  * Fork - LGPL
39868  * <script type="text/javascript">
39869  */
39870
39871 /**
39872  * @class Roo.menu.TextItem
39873  * @extends Roo.menu.BaseItem
39874  * Adds a static text string to a menu, usually used as either a heading or group separator.
39875  * Note: old style constructor with text is still supported.
39876  * 
39877  * @constructor
39878  * Creates a new TextItem
39879  * @param {Object} cfg Configuration
39880  */
39881 Roo.menu.TextItem = function(cfg){
39882     if (typeof(cfg) == 'string') {
39883         this.text = cfg;
39884     } else {
39885         Roo.apply(this,cfg);
39886     }
39887     
39888     Roo.menu.TextItem.superclass.constructor.call(this);
39889 };
39890
39891 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
39892     /**
39893      * @cfg {String} text Text to show on item.
39894      */
39895     text : '',
39896     
39897     /**
39898      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
39899      */
39900     hideOnClick : false,
39901     /**
39902      * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
39903      */
39904     itemCls : "x-menu-text",
39905
39906     // private
39907     onRender : function(){
39908         var s = document.createElement("span");
39909         s.className = this.itemCls;
39910         s.innerHTML = this.text;
39911         this.el = s;
39912         Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
39913     }
39914 });/*
39915  * Based on:
39916  * Ext JS Library 1.1.1
39917  * Copyright(c) 2006-2007, Ext JS, LLC.
39918  *
39919  * Originally Released Under LGPL - original licence link has changed is not relivant.
39920  *
39921  * Fork - LGPL
39922  * <script type="text/javascript">
39923  */
39924
39925 /**
39926  * @class Roo.menu.Separator
39927  * @extends Roo.menu.BaseItem
39928  * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
39929  * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
39930  * @constructor
39931  * @param {Object} config Configuration options
39932  */
39933 Roo.menu.Separator = function(config){
39934     Roo.menu.Separator.superclass.constructor.call(this, config);
39935 };
39936
39937 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
39938     /**
39939      * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
39940      */
39941     itemCls : "x-menu-sep",
39942     /**
39943      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
39944      */
39945     hideOnClick : false,
39946
39947     // private
39948     onRender : function(li){
39949         var s = document.createElement("span");
39950         s.className = this.itemCls;
39951         s.innerHTML = "&#160;";
39952         this.el = s;
39953         li.addClass("x-menu-sep-li");
39954         Roo.menu.Separator.superclass.onRender.apply(this, arguments);
39955     }
39956 });/*
39957  * Based on:
39958  * Ext JS Library 1.1.1
39959  * Copyright(c) 2006-2007, Ext JS, LLC.
39960  *
39961  * Originally Released Under LGPL - original licence link has changed is not relivant.
39962  *
39963  * Fork - LGPL
39964  * <script type="text/javascript">
39965  */
39966 /**
39967  * @class Roo.menu.Item
39968  * @extends Roo.menu.BaseItem
39969  * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
39970  * display items.  Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
39971  * activation and click handling.
39972  * @constructor
39973  * Creates a new Item
39974  * @param {Object} config Configuration options
39975  */
39976 Roo.menu.Item = function(config){
39977     Roo.menu.Item.superclass.constructor.call(this, config);
39978     if(this.menu){
39979         this.menu = Roo.menu.MenuMgr.get(this.menu);
39980     }
39981 };
39982 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
39983     /**
39984      * @cfg {Roo.menu.Menu} menu
39985      * A Sub menu
39986      */
39987     /**
39988      * @cfg {String} text
39989      * The text to show on the menu item.
39990      */
39991     text: '',
39992      /**
39993      * @cfg {String} html to render in menu
39994      * The text to show on the menu item (HTML version).
39995      */
39996     html: '',
39997     /**
39998      * @cfg {String} icon
39999      * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
40000      */
40001     icon: undefined,
40002     /**
40003      * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
40004      */
40005     itemCls : "x-menu-item",
40006     /**
40007      * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
40008      */
40009     canActivate : true,
40010     /**
40011      * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
40012      */
40013     showDelay: 200,
40014     // doc'd in BaseItem
40015     hideDelay: 200,
40016
40017     // private
40018     ctype: "Roo.menu.Item",
40019     
40020     // private
40021     onRender : function(container, position){
40022         var el = document.createElement("a");
40023         el.hideFocus = true;
40024         el.unselectable = "on";
40025         el.href = this.href || "#";
40026         if(this.hrefTarget){
40027             el.target = this.hrefTarget;
40028         }
40029         el.className = this.itemCls + (this.menu ?  " x-menu-item-arrow" : "") + (this.cls ?  " " + this.cls : "");
40030         
40031         var html = this.html.length ? this.html  : String.format('{0}',this.text);
40032         
40033         el.innerHTML = String.format(
40034                 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
40035                 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
40036         this.el = el;
40037         Roo.menu.Item.superclass.onRender.call(this, container, position);
40038     },
40039
40040     /**
40041      * Sets the text to display in this menu item
40042      * @param {String} text The text to display
40043      * @param {Boolean} isHTML true to indicate text is pure html.
40044      */
40045     setText : function(text, isHTML){
40046         if (isHTML) {
40047             this.html = text;
40048         } else {
40049             this.text = text;
40050             this.html = '';
40051         }
40052         if(this.rendered){
40053             var html = this.html.length ? this.html  : String.format('{0}',this.text);
40054      
40055             this.el.update(String.format(
40056                 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
40057                 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
40058             this.parentMenu.autoWidth();
40059         }
40060     },
40061
40062     // private
40063     handleClick : function(e){
40064         if(!this.href){ // if no link defined, stop the event automatically
40065             e.stopEvent();
40066         }
40067         Roo.menu.Item.superclass.handleClick.apply(this, arguments);
40068     },
40069
40070     // private
40071     activate : function(autoExpand){
40072         if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
40073             this.focus();
40074             if(autoExpand){
40075                 this.expandMenu();
40076             }
40077         }
40078         return true;
40079     },
40080
40081     // private
40082     shouldDeactivate : function(e){
40083         if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
40084             if(this.menu && this.menu.isVisible()){
40085                 return !this.menu.getEl().getRegion().contains(e.getPoint());
40086             }
40087             return true;
40088         }
40089         return false;
40090     },
40091
40092     // private
40093     deactivate : function(){
40094         Roo.menu.Item.superclass.deactivate.apply(this, arguments);
40095         this.hideMenu();
40096     },
40097
40098     // private
40099     expandMenu : function(autoActivate){
40100         if(!this.disabled && this.menu){
40101             clearTimeout(this.hideTimer);
40102             delete this.hideTimer;
40103             if(!this.menu.isVisible() && !this.showTimer){
40104                 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
40105             }else if (this.menu.isVisible() && autoActivate){
40106                 this.menu.tryActivate(0, 1);
40107             }
40108         }
40109     },
40110
40111     // private
40112     deferExpand : function(autoActivate){
40113         delete this.showTimer;
40114         this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
40115         if(autoActivate){
40116             this.menu.tryActivate(0, 1);
40117         }
40118     },
40119
40120     // private
40121     hideMenu : function(){
40122         clearTimeout(this.showTimer);
40123         delete this.showTimer;
40124         if(!this.hideTimer && this.menu && this.menu.isVisible()){
40125             this.hideTimer = this.deferHide.defer(this.hideDelay, this);
40126         }
40127     },
40128
40129     // private
40130     deferHide : function(){
40131         delete this.hideTimer;
40132         this.menu.hide();
40133     }
40134 });/*
40135  * Based on:
40136  * Ext JS Library 1.1.1
40137  * Copyright(c) 2006-2007, Ext JS, LLC.
40138  *
40139  * Originally Released Under LGPL - original licence link has changed is not relivant.
40140  *
40141  * Fork - LGPL
40142  * <script type="text/javascript">
40143  */
40144  
40145 /**
40146  * @class Roo.menu.CheckItem
40147  * @extends Roo.menu.Item
40148  * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
40149  * @constructor
40150  * Creates a new CheckItem
40151  * @param {Object} config Configuration options
40152  */
40153 Roo.menu.CheckItem = function(config){
40154     Roo.menu.CheckItem.superclass.constructor.call(this, config);
40155     this.addEvents({
40156         /**
40157          * @event beforecheckchange
40158          * Fires before the checked value is set, providing an opportunity to cancel if needed
40159          * @param {Roo.menu.CheckItem} this
40160          * @param {Boolean} checked The new checked value that will be set
40161          */
40162         "beforecheckchange" : true,
40163         /**
40164          * @event checkchange
40165          * Fires after the checked value has been set
40166          * @param {Roo.menu.CheckItem} this
40167          * @param {Boolean} checked The checked value that was set
40168          */
40169         "checkchange" : true
40170     });
40171     if(this.checkHandler){
40172         this.on('checkchange', this.checkHandler, this.scope);
40173     }
40174 };
40175 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
40176     /**
40177      * @cfg {String} group
40178      * All check items with the same group name will automatically be grouped into a single-select
40179      * radio button group (defaults to '')
40180      */
40181     /**
40182      * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
40183      */
40184     itemCls : "x-menu-item x-menu-check-item",
40185     /**
40186      * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
40187      */
40188     groupClass : "x-menu-group-item",
40189
40190     /**
40191      * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false).  Note that
40192      * if this checkbox is part of a radio group (group = true) only the last item in the group that is
40193      * initialized with checked = true will be rendered as checked.
40194      */
40195     checked: false,
40196
40197     // private
40198     ctype: "Roo.menu.CheckItem",
40199
40200     // private
40201     onRender : function(c){
40202         Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
40203         if(this.group){
40204             this.el.addClass(this.groupClass);
40205         }
40206         Roo.menu.MenuMgr.registerCheckable(this);
40207         if(this.checked){
40208             this.checked = false;
40209             this.setChecked(true, true);
40210         }
40211     },
40212
40213     // private
40214     destroy : function(){
40215         if(this.rendered){
40216             Roo.menu.MenuMgr.unregisterCheckable(this);
40217         }
40218         Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
40219     },
40220
40221     /**
40222      * Set the checked state of this item
40223      * @param {Boolean} checked The new checked value
40224      * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
40225      */
40226     setChecked : function(state, suppressEvent){
40227         if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
40228             if(this.container){
40229                 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
40230             }
40231             this.checked = state;
40232             if(suppressEvent !== true){
40233                 this.fireEvent("checkchange", this, state);
40234             }
40235         }
40236     },
40237
40238     // private
40239     handleClick : function(e){
40240        if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
40241            this.setChecked(!this.checked);
40242        }
40243        Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
40244     }
40245 });/*
40246  * Based on:
40247  * Ext JS Library 1.1.1
40248  * Copyright(c) 2006-2007, Ext JS, LLC.
40249  *
40250  * Originally Released Under LGPL - original licence link has changed is not relivant.
40251  *
40252  * Fork - LGPL
40253  * <script type="text/javascript">
40254  */
40255  
40256 /**
40257  * @class Roo.menu.DateItem
40258  * @extends Roo.menu.Adapter
40259  * A menu item that wraps the {@link Roo.DatPicker} component.
40260  * @constructor
40261  * Creates a new DateItem
40262  * @param {Object} config Configuration options
40263  */
40264 Roo.menu.DateItem = function(config){
40265     Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
40266     /** The Roo.DatePicker object @type Roo.DatePicker */
40267     this.picker = this.component;
40268     this.addEvents({select: true});
40269     
40270     this.picker.on("render", function(picker){
40271         picker.getEl().swallowEvent("click");
40272         picker.container.addClass("x-menu-date-item");
40273     });
40274
40275     this.picker.on("select", this.onSelect, this);
40276 };
40277
40278 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
40279     // private
40280     onSelect : function(picker, date){
40281         this.fireEvent("select", this, date, picker);
40282         Roo.menu.DateItem.superclass.handleClick.call(this);
40283     }
40284 });/*
40285  * Based on:
40286  * Ext JS Library 1.1.1
40287  * Copyright(c) 2006-2007, Ext JS, LLC.
40288  *
40289  * Originally Released Under LGPL - original licence link has changed is not relivant.
40290  *
40291  * Fork - LGPL
40292  * <script type="text/javascript">
40293  */
40294  
40295 /**
40296  * @class Roo.menu.ColorItem
40297  * @extends Roo.menu.Adapter
40298  * A menu item that wraps the {@link Roo.ColorPalette} component.
40299  * @constructor
40300  * Creates a new ColorItem
40301  * @param {Object} config Configuration options
40302  */
40303 Roo.menu.ColorItem = function(config){
40304     Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
40305     /** The Roo.ColorPalette object @type Roo.ColorPalette */
40306     this.palette = this.component;
40307     this.relayEvents(this.palette, ["select"]);
40308     if(this.selectHandler){
40309         this.on('select', this.selectHandler, this.scope);
40310     }
40311 };
40312 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
40313  * Based on:
40314  * Ext JS Library 1.1.1
40315  * Copyright(c) 2006-2007, Ext JS, LLC.
40316  *
40317  * Originally Released Under LGPL - original licence link has changed is not relivant.
40318  *
40319  * Fork - LGPL
40320  * <script type="text/javascript">
40321  */
40322  
40323
40324 /**
40325  * @class Roo.menu.DateMenu
40326  * @extends Roo.menu.Menu
40327  * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
40328  * @constructor
40329  * Creates a new DateMenu
40330  * @param {Object} config Configuration options
40331  */
40332 Roo.menu.DateMenu = function(config){
40333     Roo.menu.DateMenu.superclass.constructor.call(this, config);
40334     this.plain = true;
40335     var di = new Roo.menu.DateItem(config);
40336     this.add(di);
40337     /**
40338      * The {@link Roo.DatePicker} instance for this DateMenu
40339      * @type DatePicker
40340      */
40341     this.picker = di.picker;
40342     /**
40343      * @event select
40344      * @param {DatePicker} picker
40345      * @param {Date} date
40346      */
40347     this.relayEvents(di, ["select"]);
40348     this.on('beforeshow', function(){
40349         if(this.picker){
40350             this.picker.hideMonthPicker(false);
40351         }
40352     }, this);
40353 };
40354 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
40355     cls:'x-date-menu'
40356 });/*
40357  * Based on:
40358  * Ext JS Library 1.1.1
40359  * Copyright(c) 2006-2007, Ext JS, LLC.
40360  *
40361  * Originally Released Under LGPL - original licence link has changed is not relivant.
40362  *
40363  * Fork - LGPL
40364  * <script type="text/javascript">
40365  */
40366  
40367
40368 /**
40369  * @class Roo.menu.ColorMenu
40370  * @extends Roo.menu.Menu
40371  * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
40372  * @constructor
40373  * Creates a new ColorMenu
40374  * @param {Object} config Configuration options
40375  */
40376 Roo.menu.ColorMenu = function(config){
40377     Roo.menu.ColorMenu.superclass.constructor.call(this, config);
40378     this.plain = true;
40379     var ci = new Roo.menu.ColorItem(config);
40380     this.add(ci);
40381     /**
40382      * The {@link Roo.ColorPalette} instance for this ColorMenu
40383      * @type ColorPalette
40384      */
40385     this.palette = ci.palette;
40386     /**
40387      * @event select
40388      * @param {ColorPalette} palette
40389      * @param {String} color
40390      */
40391     this.relayEvents(ci, ["select"]);
40392 };
40393 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
40394  * Based on:
40395  * Ext JS Library 1.1.1
40396  * Copyright(c) 2006-2007, Ext JS, LLC.
40397  *
40398  * Originally Released Under LGPL - original licence link has changed is not relivant.
40399  *
40400  * Fork - LGPL
40401  * <script type="text/javascript">
40402  */
40403  
40404 /**
40405  * @class Roo.form.TextItem
40406  * @extends Roo.BoxComponent
40407  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
40408  * @constructor
40409  * Creates a new TextItem
40410  * @param {Object} config Configuration options
40411  */
40412 Roo.form.TextItem = function(config){
40413     Roo.form.TextItem.superclass.constructor.call(this, config);
40414 };
40415
40416 Roo.extend(Roo.form.TextItem, Roo.BoxComponent,  {
40417     
40418     /**
40419      * @cfg {String} tag the tag for this item (default div)
40420      */
40421     tag : 'div',
40422     /**
40423      * @cfg {String} html the content for this item
40424      */
40425     html : '',
40426     
40427     getAutoCreate : function()
40428     {
40429         var cfg = {
40430             id: this.id,
40431             tag: this.tag,
40432             html: this.html,
40433             cls: 'x-form-item'
40434         };
40435         
40436         return cfg;
40437         
40438     },
40439     
40440     onRender : function(ct, position)
40441     {
40442         Roo.form.TextItem.superclass.onRender.call(this, ct, position);
40443         
40444         if(!this.el){
40445             var cfg = this.getAutoCreate();
40446             if(!cfg.name){
40447                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
40448             }
40449             if (!cfg.name.length) {
40450                 delete cfg.name;
40451             }
40452             this.el = ct.createChild(cfg, position);
40453         }
40454     },
40455     /*
40456      * setHTML
40457      * @param {String} html update the Contents of the element.
40458      */
40459     setHTML : function(html)
40460     {
40461         this.fieldEl.dom.innerHTML = html;
40462     }
40463     
40464 });/*
40465  * Based on:
40466  * Ext JS Library 1.1.1
40467  * Copyright(c) 2006-2007, Ext JS, LLC.
40468  *
40469  * Originally Released Under LGPL - original licence link has changed is not relivant.
40470  *
40471  * Fork - LGPL
40472  * <script type="text/javascript">
40473  */
40474  
40475 /**
40476  * @class Roo.form.Field
40477  * @extends Roo.BoxComponent
40478  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
40479  * @constructor
40480  * Creates a new Field
40481  * @param {Object} config Configuration options
40482  */
40483 Roo.form.Field = function(config){
40484     Roo.form.Field.superclass.constructor.call(this, config);
40485 };
40486
40487 Roo.extend(Roo.form.Field, Roo.BoxComponent,  {
40488     /**
40489      * @cfg {String} fieldLabel Label to use when rendering a form.
40490      */
40491        /**
40492      * @cfg {String} qtip Mouse over tip
40493      */
40494      
40495     /**
40496      * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
40497      */
40498     invalidClass : "x-form-invalid",
40499     /**
40500      * @cfg {String} invalidText The error text to use when marking a field invalid and no message is provided (defaults to "The value in this field is invalid")
40501      */
40502     invalidText : "The value in this field is invalid",
40503     /**
40504      * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
40505      */
40506     focusClass : "x-form-focus",
40507     /**
40508      * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
40509       automatic validation (defaults to "keyup").
40510      */
40511     validationEvent : "keyup",
40512     /**
40513      * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
40514      */
40515     validateOnBlur : true,
40516     /**
40517      * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
40518      */
40519     validationDelay : 250,
40520     /**
40521      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
40522      * {tag: "input", type: "text", size: "20", autocomplete: "off"})
40523      */
40524     defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "new-password"},
40525     /**
40526      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
40527      */
40528     fieldClass : "x-form-field",
40529     /**
40530      * @cfg {String} msgTarget The location where error text should display.  Should be one of the following values (defaults to 'qtip'):
40531      *<pre>
40532 Value         Description
40533 -----------   ----------------------------------------------------------------------
40534 qtip          Display a quick tip when the user hovers over the field
40535 title         Display a default browser title attribute popup
40536 under         Add a block div beneath the field containing the error text
40537 side          Add an error icon to the right of the field with a popup on hover
40538 [element id]  Add the error text directly to the innerHTML of the specified element
40539 </pre>
40540      */
40541     msgTarget : 'qtip',
40542     /**
40543      * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
40544      */
40545     msgFx : 'normal',
40546
40547     /**
40548      * @cfg {Boolean} readOnly True to mark the field as readOnly in HTML (defaults to false) -- Note: this only sets the element's readOnly DOM attribute.
40549      */
40550     readOnly : false,
40551
40552     /**
40553      * @cfg {Boolean} disabled True to disable the field (defaults to false).
40554      */
40555     disabled : false,
40556
40557     /**
40558      * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
40559      */
40560     inputType : undefined,
40561     
40562     /**
40563      * @cfg {Number} tabIndex The tabIndex for this field. Note this only applies to fields that are rendered, not those which are built via applyTo (defaults to undefined).
40564          */
40565         tabIndex : undefined,
40566         
40567     // private
40568     isFormField : true,
40569
40570     // private
40571     hasFocus : false,
40572     /**
40573      * @property {Roo.Element} fieldEl
40574      * Element Containing the rendered Field (with label etc.)
40575      */
40576     /**
40577      * @cfg {Mixed} value A value to initialize this field with.
40578      */
40579     value : undefined,
40580
40581     /**
40582      * @cfg {String} name The field's HTML name attribute.
40583      */
40584     /**
40585      * @cfg {String} cls A CSS class to apply to the field's underlying element.
40586      */
40587     // private
40588     loadedValue : false,
40589      
40590      
40591         // private ??
40592         initComponent : function(){
40593         Roo.form.Field.superclass.initComponent.call(this);
40594         this.addEvents({
40595             /**
40596              * @event focus
40597              * Fires when this field receives input focus.
40598              * @param {Roo.form.Field} this
40599              */
40600             focus : true,
40601             /**
40602              * @event blur
40603              * Fires when this field loses input focus.
40604              * @param {Roo.form.Field} this
40605              */
40606             blur : true,
40607             /**
40608              * @event specialkey
40609              * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
40610              * {@link Roo.EventObject#getKey} to determine which key was pressed.
40611              * @param {Roo.form.Field} this
40612              * @param {Roo.EventObject} e The event object
40613              */
40614             specialkey : true,
40615             /**
40616              * @event change
40617              * Fires just before the field blurs if the field value has changed.
40618              * @param {Roo.form.Field} this
40619              * @param {Mixed} newValue The new value
40620              * @param {Mixed} oldValue The original value
40621              */
40622             change : true,
40623             /**
40624              * @event invalid
40625              * Fires after the field has been marked as invalid.
40626              * @param {Roo.form.Field} this
40627              * @param {String} msg The validation message
40628              */
40629             invalid : true,
40630             /**
40631              * @event valid
40632              * Fires after the field has been validated with no errors.
40633              * @param {Roo.form.Field} this
40634              */
40635             valid : true,
40636              /**
40637              * @event keyup
40638              * Fires after the key up
40639              * @param {Roo.form.Field} this
40640              * @param {Roo.EventObject}  e The event Object
40641              */
40642             keyup : true
40643         });
40644     },
40645
40646     /**
40647      * Returns the name attribute of the field if available
40648      * @return {String} name The field name
40649      */
40650     getName: function(){
40651          return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
40652     },
40653
40654     // private
40655     onRender : function(ct, position){
40656         Roo.form.Field.superclass.onRender.call(this, ct, position);
40657         if(!this.el){
40658             var cfg = this.getAutoCreate();
40659             if(!cfg.name){
40660                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
40661             }
40662             if (!cfg.name.length) {
40663                 delete cfg.name;
40664             }
40665             if(this.inputType){
40666                 cfg.type = this.inputType;
40667             }
40668             this.el = ct.createChild(cfg, position);
40669         }
40670         var type = this.el.dom.type;
40671         if(type){
40672             if(type == 'password'){
40673                 type = 'text';
40674             }
40675             this.el.addClass('x-form-'+type);
40676         }
40677         if(this.readOnly){
40678             this.el.dom.readOnly = true;
40679         }
40680         if(this.tabIndex !== undefined){
40681             this.el.dom.setAttribute('tabIndex', this.tabIndex);
40682         }
40683
40684         this.el.addClass([this.fieldClass, this.cls]);
40685         this.initValue();
40686     },
40687
40688     /**
40689      * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
40690      * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
40691      * @return {Roo.form.Field} this
40692      */
40693     applyTo : function(target){
40694         this.allowDomMove = false;
40695         this.el = Roo.get(target);
40696         this.render(this.el.dom.parentNode);
40697         return this;
40698     },
40699
40700     // private
40701     initValue : function(){
40702         if(this.value !== undefined){
40703             this.setValue(this.value);
40704         }else if(this.el.dom.value.length > 0){
40705             this.setValue(this.el.dom.value);
40706         }
40707     },
40708
40709     /**
40710      * Returns true if this field has been changed since it was originally loaded and is not disabled.
40711      * DEPRICATED  - it never worked well - use hasChanged/resetHasChanged.
40712      */
40713     isDirty : function() {
40714         if(this.disabled) {
40715             return false;
40716         }
40717         return String(this.getValue()) !== String(this.originalValue);
40718     },
40719
40720     /**
40721      * stores the current value in loadedValue
40722      */
40723     resetHasChanged : function()
40724     {
40725         this.loadedValue = String(this.getValue());
40726     },
40727     /**
40728      * checks the current value against the 'loaded' value.
40729      * Note - will return false if 'resetHasChanged' has not been called first.
40730      */
40731     hasChanged : function()
40732     {
40733         if(this.disabled || this.readOnly) {
40734             return false;
40735         }
40736         return this.loadedValue !== false && String(this.getValue()) !== this.loadedValue;
40737     },
40738     
40739     
40740     
40741     // private
40742     afterRender : function(){
40743         Roo.form.Field.superclass.afterRender.call(this);
40744         this.initEvents();
40745     },
40746
40747     // private
40748     fireKey : function(e){
40749         //Roo.log('field ' + e.getKey());
40750         if(e.isNavKeyPress()){
40751             this.fireEvent("specialkey", this, e);
40752         }
40753     },
40754
40755     /**
40756      * Resets the current field value to the originally loaded value and clears any validation messages
40757      */
40758     reset : function(){
40759         this.setValue(this.resetValue);
40760         this.originalValue = this.getValue();
40761         this.clearInvalid();
40762     },
40763
40764     // private
40765     initEvents : function(){
40766         // safari killled keypress - so keydown is now used..
40767         this.el.on("keydown" , this.fireKey,  this);
40768         this.el.on("focus", this.onFocus,  this);
40769         this.el.on("blur", this.onBlur,  this);
40770         this.el.relayEvent('keyup', this);
40771
40772         // reference to original value for reset
40773         this.originalValue = this.getValue();
40774         this.resetValue =  this.getValue();
40775     },
40776
40777     // private
40778     onFocus : function(){
40779         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
40780             this.el.addClass(this.focusClass);
40781         }
40782         if(!this.hasFocus){
40783             this.hasFocus = true;
40784             this.startValue = this.getValue();
40785             this.fireEvent("focus", this);
40786         }
40787     },
40788
40789     beforeBlur : Roo.emptyFn,
40790
40791     // private
40792     onBlur : function(){
40793         this.beforeBlur();
40794         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
40795             this.el.removeClass(this.focusClass);
40796         }
40797         this.hasFocus = false;
40798         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
40799             this.validate();
40800         }
40801         var v = this.getValue();
40802         if(String(v) !== String(this.startValue)){
40803             this.fireEvent('change', this, v, this.startValue);
40804         }
40805         this.fireEvent("blur", this);
40806     },
40807
40808     /**
40809      * Returns whether or not the field value is currently valid
40810      * @param {Boolean} preventMark True to disable marking the field invalid
40811      * @return {Boolean} True if the value is valid, else false
40812      */
40813     isValid : function(preventMark){
40814         if(this.disabled){
40815             return true;
40816         }
40817         var restore = this.preventMark;
40818         this.preventMark = preventMark === true;
40819         var v = this.validateValue(this.processValue(this.getRawValue()));
40820         this.preventMark = restore;
40821         return v;
40822     },
40823
40824     /**
40825      * Validates the field value
40826      * @return {Boolean} True if the value is valid, else false
40827      */
40828     validate : function(){
40829         if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
40830             this.clearInvalid();
40831             return true;
40832         }
40833         return false;
40834     },
40835
40836     processValue : function(value){
40837         return value;
40838     },
40839
40840     // private
40841     // Subclasses should provide the validation implementation by overriding this
40842     validateValue : function(value){
40843         return true;
40844     },
40845
40846     /**
40847      * Mark this field as invalid
40848      * @param {String} msg The validation message
40849      */
40850     markInvalid : function(msg){
40851         if(!this.rendered || this.preventMark){ // not rendered
40852             return;
40853         }
40854         
40855         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
40856         
40857         obj.el.addClass(this.invalidClass);
40858         msg = msg || this.invalidText;
40859         switch(this.msgTarget){
40860             case 'qtip':
40861                 obj.el.dom.qtip = msg;
40862                 obj.el.dom.qclass = 'x-form-invalid-tip';
40863                 if(Roo.QuickTips){ // fix for floating editors interacting with DND
40864                     Roo.QuickTips.enable();
40865                 }
40866                 break;
40867             case 'title':
40868                 this.el.dom.title = msg;
40869                 break;
40870             case 'under':
40871                 if(!this.errorEl){
40872                     var elp = this.el.findParent('.x-form-element', 5, true);
40873                     this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
40874                     this.errorEl.setWidth(elp.getWidth(true)-20);
40875                 }
40876                 this.errorEl.update(msg);
40877                 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
40878                 break;
40879             case 'side':
40880                 if(!this.errorIcon){
40881                     var elp = this.el.findParent('.x-form-element', 5, true);
40882                     this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
40883                 }
40884                 this.alignErrorIcon();
40885                 this.errorIcon.dom.qtip = msg;
40886                 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
40887                 this.errorIcon.show();
40888                 this.on('resize', this.alignErrorIcon, this);
40889                 break;
40890             default:
40891                 var t = Roo.getDom(this.msgTarget);
40892                 t.innerHTML = msg;
40893                 t.style.display = this.msgDisplay;
40894                 break;
40895         }
40896         this.fireEvent('invalid', this, msg);
40897     },
40898
40899     // private
40900     alignErrorIcon : function(){
40901         this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
40902     },
40903
40904     /**
40905      * Clear any invalid styles/messages for this field
40906      */
40907     clearInvalid : function(){
40908         if(!this.rendered || this.preventMark){ // not rendered
40909             return;
40910         }
40911         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
40912         
40913         obj.el.removeClass(this.invalidClass);
40914         switch(this.msgTarget){
40915             case 'qtip':
40916                 obj.el.dom.qtip = '';
40917                 break;
40918             case 'title':
40919                 this.el.dom.title = '';
40920                 break;
40921             case 'under':
40922                 if(this.errorEl){
40923                     Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
40924                 }
40925                 break;
40926             case 'side':
40927                 if(this.errorIcon){
40928                     this.errorIcon.dom.qtip = '';
40929                     this.errorIcon.hide();
40930                     this.un('resize', this.alignErrorIcon, this);
40931                 }
40932                 break;
40933             default:
40934                 var t = Roo.getDom(this.msgTarget);
40935                 t.innerHTML = '';
40936                 t.style.display = 'none';
40937                 break;
40938         }
40939         this.fireEvent('valid', this);
40940     },
40941
40942     /**
40943      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
40944      * @return {Mixed} value The field value
40945      */
40946     getRawValue : function(){
40947         var v = this.el.getValue();
40948         
40949         return v;
40950     },
40951
40952     /**
40953      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
40954      * @return {Mixed} value The field value
40955      */
40956     getValue : function(){
40957         var v = this.el.getValue();
40958          
40959         return v;
40960     },
40961
40962     /**
40963      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
40964      * @param {Mixed} value The value to set
40965      */
40966     setRawValue : function(v){
40967         return this.el.dom.value = (v === null || v === undefined ? '' : v);
40968     },
40969
40970     /**
40971      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
40972      * @param {Mixed} value The value to set
40973      */
40974     setValue : function(v){
40975         this.value = v;
40976         if(this.rendered){
40977             this.el.dom.value = (v === null || v === undefined ? '' : v);
40978              this.validate();
40979         }
40980     },
40981
40982     adjustSize : function(w, h){
40983         var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
40984         s.width = this.adjustWidth(this.el.dom.tagName, s.width);
40985         return s;
40986     },
40987
40988     adjustWidth : function(tag, w){
40989         tag = tag.toLowerCase();
40990         if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
40991             if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
40992                 if(tag == 'input'){
40993                     return w + 2;
40994                 }
40995                 if(tag == 'textarea'){
40996                     return w-2;
40997                 }
40998             }else if(Roo.isOpera){
40999                 if(tag == 'input'){
41000                     return w + 2;
41001                 }
41002                 if(tag == 'textarea'){
41003                     return w-2;
41004                 }
41005             }
41006         }
41007         return w;
41008     }
41009 });
41010
41011
41012 // anything other than normal should be considered experimental
41013 Roo.form.Field.msgFx = {
41014     normal : {
41015         show: function(msgEl, f){
41016             msgEl.setDisplayed('block');
41017         },
41018
41019         hide : function(msgEl, f){
41020             msgEl.setDisplayed(false).update('');
41021         }
41022     },
41023
41024     slide : {
41025         show: function(msgEl, f){
41026             msgEl.slideIn('t', {stopFx:true});
41027         },
41028
41029         hide : function(msgEl, f){
41030             msgEl.slideOut('t', {stopFx:true,useDisplay:true});
41031         }
41032     },
41033
41034     slideRight : {
41035         show: function(msgEl, f){
41036             msgEl.fixDisplay();
41037             msgEl.alignTo(f.el, 'tl-tr');
41038             msgEl.slideIn('l', {stopFx:true});
41039         },
41040
41041         hide : function(msgEl, f){
41042             msgEl.slideOut('l', {stopFx:true,useDisplay:true});
41043         }
41044     }
41045 };/*
41046  * Based on:
41047  * Ext JS Library 1.1.1
41048  * Copyright(c) 2006-2007, Ext JS, LLC.
41049  *
41050  * Originally Released Under LGPL - original licence link has changed is not relivant.
41051  *
41052  * Fork - LGPL
41053  * <script type="text/javascript">
41054  */
41055  
41056
41057 /**
41058  * @class Roo.form.TextField
41059  * @extends Roo.form.Field
41060  * Basic text field.  Can be used as a direct replacement for traditional text inputs, or as the base
41061  * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
41062  * @constructor
41063  * Creates a new TextField
41064  * @param {Object} config Configuration options
41065  */
41066 Roo.form.TextField = function(config){
41067     Roo.form.TextField.superclass.constructor.call(this, config);
41068     this.addEvents({
41069         /**
41070          * @event autosize
41071          * Fires when the autosize function is triggered.  The field may or may not have actually changed size
41072          * according to the default logic, but this event provides a hook for the developer to apply additional
41073          * logic at runtime to resize the field if needed.
41074              * @param {Roo.form.Field} this This text field
41075              * @param {Number} width The new field width
41076              */
41077         autosize : true
41078     });
41079 };
41080
41081 Roo.extend(Roo.form.TextField, Roo.form.Field,  {
41082     /**
41083      * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
41084      */
41085     grow : false,
41086     /**
41087      * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
41088      */
41089     growMin : 30,
41090     /**
41091      * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
41092      */
41093     growMax : 800,
41094     /**
41095      * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
41096      */
41097     vtype : null,
41098     /**
41099      * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
41100      */
41101     maskRe : null,
41102     /**
41103      * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
41104      */
41105     disableKeyFilter : false,
41106     /**
41107      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
41108      */
41109     allowBlank : true,
41110     /**
41111      * @cfg {Number} minLength Minimum input field length required (defaults to 0)
41112      */
41113     minLength : 0,
41114     /**
41115      * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
41116      */
41117     maxLength : Number.MAX_VALUE,
41118     /**
41119      * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
41120      */
41121     minLengthText : "The minimum length for this field is {0}",
41122     /**
41123      * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
41124      */
41125     maxLengthText : "The maximum length for this field is {0}",
41126     /**
41127      * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
41128      */
41129     selectOnFocus : false,
41130     /**
41131      * @cfg {Boolean} allowLeadingSpace True to prevent the stripping of leading white space 
41132      */    
41133     allowLeadingSpace : false,
41134     /**
41135      * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
41136      */
41137     blankText : "This field is required",
41138     /**
41139      * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
41140      * If available, this function will be called only after the basic validators all return true, and will be passed the
41141      * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
41142      */
41143     validator : null,
41144     /**
41145      * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
41146      * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
41147      * current field value.  If the test fails, the field will be marked invalid using {@link #regexText}.
41148      */
41149     regex : null,
41150     /**
41151      * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
41152      */
41153     regexText : "",
41154     /**
41155      * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
41156      */
41157     emptyText : null,
41158    
41159
41160     // private
41161     initEvents : function()
41162     {
41163         if (this.emptyText) {
41164             this.el.attr('placeholder', this.emptyText);
41165         }
41166         
41167         Roo.form.TextField.superclass.initEvents.call(this);
41168         if(this.validationEvent == 'keyup'){
41169             this.validationTask = new Roo.util.DelayedTask(this.validate, this);
41170             this.el.on('keyup', this.filterValidation, this);
41171         }
41172         else if(this.validationEvent !== false){
41173             this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
41174         }
41175         
41176         if(this.selectOnFocus){
41177             this.on("focus", this.preFocus, this);
41178         }
41179         if (!this.allowLeadingSpace) {
41180             this.on('blur', this.cleanLeadingSpace, this);
41181         }
41182         
41183         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
41184             this.el.on("keypress", this.filterKeys, this);
41185         }
41186         if(this.grow){
41187             this.el.on("keyup", this.onKeyUp,  this, {buffer:50});
41188             this.el.on("click", this.autoSize,  this);
41189         }
41190         if(this.el.is('input[type=password]') && Roo.isSafari){
41191             this.el.on('keydown', this.SafariOnKeyDown, this);
41192         }
41193     },
41194
41195     processValue : function(value){
41196         if(this.stripCharsRe){
41197             var newValue = value.replace(this.stripCharsRe, '');
41198             if(newValue !== value){
41199                 this.setRawValue(newValue);
41200                 return newValue;
41201             }
41202         }
41203         return value;
41204     },
41205
41206     filterValidation : function(e){
41207         if(!e.isNavKeyPress()){
41208             this.validationTask.delay(this.validationDelay);
41209         }
41210     },
41211
41212     // private
41213     onKeyUp : function(e){
41214         if(!e.isNavKeyPress()){
41215             this.autoSize();
41216         }
41217     },
41218     // private - clean the leading white space
41219     cleanLeadingSpace : function(e)
41220     {
41221         if ( this.inputType == 'file') {
41222             return;
41223         }
41224         
41225         this.setValue((this.getValue() + '').replace(/^\s+/,''));
41226     },
41227     /**
41228      * Resets the current field value to the originally-loaded value and clears any validation messages.
41229      *  
41230      */
41231     reset : function(){
41232         Roo.form.TextField.superclass.reset.call(this);
41233        
41234     }, 
41235     // private
41236     preFocus : function(){
41237         
41238         if(this.selectOnFocus){
41239             this.el.dom.select();
41240         }
41241     },
41242
41243     
41244     // private
41245     filterKeys : function(e){
41246         var k = e.getKey();
41247         if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
41248             return;
41249         }
41250         var c = e.getCharCode(), cc = String.fromCharCode(c);
41251         if(Roo.isIE && (e.isSpecialKey() || !cc)){
41252             return;
41253         }
41254         if(!this.maskRe.test(cc)){
41255             e.stopEvent();
41256         }
41257     },
41258
41259     setValue : function(v){
41260         
41261         Roo.form.TextField.superclass.setValue.apply(this, arguments);
41262         
41263         this.autoSize();
41264     },
41265
41266     /**
41267      * Validates a value according to the field's validation rules and marks the field as invalid
41268      * if the validation fails
41269      * @param {Mixed} value The value to validate
41270      * @return {Boolean} True if the value is valid, else false
41271      */
41272     validateValue : function(value){
41273         if(value.length < 1)  { // if it's blank
41274              if(this.allowBlank){
41275                 this.clearInvalid();
41276                 return true;
41277              }else{
41278                 this.markInvalid(this.blankText);
41279                 return false;
41280              }
41281         }
41282         if(value.length < this.minLength){
41283             this.markInvalid(String.format(this.minLengthText, this.minLength));
41284             return false;
41285         }
41286         if(value.length > this.maxLength){
41287             this.markInvalid(String.format(this.maxLengthText, this.maxLength));
41288             return false;
41289         }
41290         if(this.vtype){
41291             var vt = Roo.form.VTypes;
41292             if(!vt[this.vtype](value, this)){
41293                 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
41294                 return false;
41295             }
41296         }
41297         if(typeof this.validator == "function"){
41298             var msg = this.validator(value);
41299             if(msg !== true){
41300                 this.markInvalid(msg);
41301                 return false;
41302             }
41303         }
41304         if(this.regex && !this.regex.test(value)){
41305             this.markInvalid(this.regexText);
41306             return false;
41307         }
41308         return true;
41309     },
41310
41311     /**
41312      * Selects text in this field
41313      * @param {Number} start (optional) The index where the selection should start (defaults to 0)
41314      * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
41315      */
41316     selectText : function(start, end){
41317         var v = this.getRawValue();
41318         if(v.length > 0){
41319             start = start === undefined ? 0 : start;
41320             end = end === undefined ? v.length : end;
41321             var d = this.el.dom;
41322             if(d.setSelectionRange){
41323                 d.setSelectionRange(start, end);
41324             }else if(d.createTextRange){
41325                 var range = d.createTextRange();
41326                 range.moveStart("character", start);
41327                 range.moveEnd("character", v.length-end);
41328                 range.select();
41329             }
41330         }
41331     },
41332
41333     /**
41334      * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
41335      * This only takes effect if grow = true, and fires the autosize event.
41336      */
41337     autoSize : function(){
41338         if(!this.grow || !this.rendered){
41339             return;
41340         }
41341         if(!this.metrics){
41342             this.metrics = Roo.util.TextMetrics.createInstance(this.el);
41343         }
41344         var el = this.el;
41345         var v = el.dom.value;
41346         var d = document.createElement('div');
41347         d.appendChild(document.createTextNode(v));
41348         v = d.innerHTML;
41349         d = null;
41350         v += "&#160;";
41351         var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
41352         this.el.setWidth(w);
41353         this.fireEvent("autosize", this, w);
41354     },
41355     
41356     // private
41357     SafariOnKeyDown : function(event)
41358     {
41359         // this is a workaround for a password hang bug on chrome/ webkit.
41360         
41361         var isSelectAll = false;
41362         
41363         if(this.el.dom.selectionEnd > 0){
41364             isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
41365         }
41366         if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
41367             event.preventDefault();
41368             this.setValue('');
41369             return;
41370         }
41371         
41372         if(isSelectAll && event.getCharCode() > 31){ // backspace and delete key
41373             
41374             event.preventDefault();
41375             // this is very hacky as keydown always get's upper case.
41376             
41377             var cc = String.fromCharCode(event.getCharCode());
41378             
41379             
41380             this.setValue( event.shiftKey ?  cc : cc.toLowerCase());
41381             
41382         }
41383         
41384         
41385     }
41386 });/*
41387  * Based on:
41388  * Ext JS Library 1.1.1
41389  * Copyright(c) 2006-2007, Ext JS, LLC.
41390  *
41391  * Originally Released Under LGPL - original licence link has changed is not relivant.
41392  *
41393  * Fork - LGPL
41394  * <script type="text/javascript">
41395  */
41396  
41397 /**
41398  * @class Roo.form.Hidden
41399  * @extends Roo.form.TextField
41400  * Simple Hidden element used on forms 
41401  * 
41402  * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
41403  * 
41404  * @constructor
41405  * Creates a new Hidden form element.
41406  * @param {Object} config Configuration options
41407  */
41408
41409
41410
41411 // easy hidden field...
41412 Roo.form.Hidden = function(config){
41413     Roo.form.Hidden.superclass.constructor.call(this, config);
41414 };
41415   
41416 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
41417     fieldLabel:      '',
41418     inputType:      'hidden',
41419     width:          50,
41420     allowBlank:     true,
41421     labelSeparator: '',
41422     hidden:         true,
41423     itemCls :       'x-form-item-display-none'
41424
41425
41426 });
41427
41428
41429 /*
41430  * Based on:
41431  * Ext JS Library 1.1.1
41432  * Copyright(c) 2006-2007, Ext JS, LLC.
41433  *
41434  * Originally Released Under LGPL - original licence link has changed is not relivant.
41435  *
41436  * Fork - LGPL
41437  * <script type="text/javascript">
41438  */
41439  
41440 /**
41441  * @class Roo.form.TriggerField
41442  * @extends Roo.form.TextField
41443  * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
41444  * The trigger has no default action, so you must assign a function to implement the trigger click handler by
41445  * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
41446  * for which you can provide a custom implementation.  For example:
41447  * <pre><code>
41448 var trigger = new Roo.form.TriggerField();
41449 trigger.onTriggerClick = myTriggerFn;
41450 trigger.applyTo('my-field');
41451 </code></pre>
41452  *
41453  * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
41454  * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
41455  * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
41456  * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
41457  * @constructor
41458  * Create a new TriggerField.
41459  * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
41460  * to the base TextField)
41461  */
41462 Roo.form.TriggerField = function(config){
41463     this.mimicing = false;
41464     Roo.form.TriggerField.superclass.constructor.call(this, config);
41465 };
41466
41467 Roo.extend(Roo.form.TriggerField, Roo.form.TextField,  {
41468     /**
41469      * @cfg {String} triggerClass A CSS class to apply to the trigger
41470      */
41471     /**
41472      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
41473      * {tag: "input", type: "text", size: "16", autocomplete: "off"})
41474      */
41475     defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "new-password"},
41476     /**
41477      * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
41478      */
41479     hideTrigger:false,
41480
41481     /** @cfg {Boolean} grow @hide */
41482     /** @cfg {Number} growMin @hide */
41483     /** @cfg {Number} growMax @hide */
41484
41485     /**
41486      * @hide 
41487      * @method
41488      */
41489     autoSize: Roo.emptyFn,
41490     // private
41491     monitorTab : true,
41492     // private
41493     deferHeight : true,
41494
41495     
41496     actionMode : 'wrap',
41497     // private
41498     onResize : function(w, h){
41499         Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
41500         if(typeof w == 'number'){
41501             var x = w - this.trigger.getWidth();
41502             this.el.setWidth(this.adjustWidth('input', x));
41503             this.trigger.setStyle('left', x+'px');
41504         }
41505     },
41506
41507     // private
41508     adjustSize : Roo.BoxComponent.prototype.adjustSize,
41509
41510     // private
41511     getResizeEl : function(){
41512         return this.wrap;
41513     },
41514
41515     // private
41516     getPositionEl : function(){
41517         return this.wrap;
41518     },
41519
41520     // private
41521     alignErrorIcon : function(){
41522         this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
41523     },
41524
41525     // private
41526     onRender : function(ct, position){
41527         Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
41528         this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
41529         this.trigger = this.wrap.createChild(this.triggerConfig ||
41530                 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
41531         if(this.hideTrigger){
41532             this.trigger.setDisplayed(false);
41533         }
41534         this.initTrigger();
41535         if(!this.width){
41536             this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
41537         }
41538     },
41539
41540     // private
41541     initTrigger : function(){
41542         this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
41543         this.trigger.addClassOnOver('x-form-trigger-over');
41544         this.trigger.addClassOnClick('x-form-trigger-click');
41545     },
41546
41547     // private
41548     onDestroy : function(){
41549         if(this.trigger){
41550             this.trigger.removeAllListeners();
41551             this.trigger.remove();
41552         }
41553         if(this.wrap){
41554             this.wrap.remove();
41555         }
41556         Roo.form.TriggerField.superclass.onDestroy.call(this);
41557     },
41558
41559     // private
41560     onFocus : function(){
41561         Roo.form.TriggerField.superclass.onFocus.call(this);
41562         if(!this.mimicing){
41563             this.wrap.addClass('x-trigger-wrap-focus');
41564             this.mimicing = true;
41565             Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
41566             if(this.monitorTab){
41567                 this.el.on("keydown", this.checkTab, this);
41568             }
41569         }
41570     },
41571
41572     // private
41573     checkTab : function(e){
41574         if(e.getKey() == e.TAB){
41575             this.triggerBlur();
41576         }
41577     },
41578
41579     // private
41580     onBlur : function(){
41581         // do nothing
41582     },
41583
41584     // private
41585     mimicBlur : function(e, t){
41586         if(!this.wrap.contains(t) && this.validateBlur()){
41587             this.triggerBlur();
41588         }
41589     },
41590
41591     // private
41592     triggerBlur : function(){
41593         this.mimicing = false;
41594         Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
41595         if(this.monitorTab){
41596             this.el.un("keydown", this.checkTab, this);
41597         }
41598         this.wrap.removeClass('x-trigger-wrap-focus');
41599         Roo.form.TriggerField.superclass.onBlur.call(this);
41600     },
41601
41602     // private
41603     // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
41604     validateBlur : function(e, t){
41605         return true;
41606     },
41607
41608     // private
41609     onDisable : function(){
41610         Roo.form.TriggerField.superclass.onDisable.call(this);
41611         if(this.wrap){
41612             this.wrap.addClass('x-item-disabled');
41613         }
41614     },
41615
41616     // private
41617     onEnable : function(){
41618         Roo.form.TriggerField.superclass.onEnable.call(this);
41619         if(this.wrap){
41620             this.wrap.removeClass('x-item-disabled');
41621         }
41622     },
41623
41624     // private
41625     onShow : function(){
41626         var ae = this.getActionEl();
41627         
41628         if(ae){
41629             ae.dom.style.display = '';
41630             ae.dom.style.visibility = 'visible';
41631         }
41632     },
41633
41634     // private
41635     
41636     onHide : function(){
41637         var ae = this.getActionEl();
41638         ae.dom.style.display = 'none';
41639     },
41640
41641     /**
41642      * The function that should handle the trigger's click event.  This method does nothing by default until overridden
41643      * by an implementing function.
41644      * @method
41645      * @param {EventObject} e
41646      */
41647     onTriggerClick : Roo.emptyFn
41648 });
41649
41650 // TwinTriggerField is not a public class to be used directly.  It is meant as an abstract base class
41651 // to be extended by an implementing class.  For an example of implementing this class, see the custom
41652 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
41653 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
41654     initComponent : function(){
41655         Roo.form.TwinTriggerField.superclass.initComponent.call(this);
41656
41657         this.triggerConfig = {
41658             tag:'span', cls:'x-form-twin-triggers', cn:[
41659             {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
41660             {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
41661         ]};
41662     },
41663
41664     getTrigger : function(index){
41665         return this.triggers[index];
41666     },
41667
41668     initTrigger : function(){
41669         var ts = this.trigger.select('.x-form-trigger', true);
41670         this.wrap.setStyle('overflow', 'hidden');
41671         var triggerField = this;
41672         ts.each(function(t, all, index){
41673             t.hide = function(){
41674                 var w = triggerField.wrap.getWidth();
41675                 this.dom.style.display = 'none';
41676                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
41677             };
41678             t.show = function(){
41679                 var w = triggerField.wrap.getWidth();
41680                 this.dom.style.display = '';
41681                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
41682             };
41683             var triggerIndex = 'Trigger'+(index+1);
41684
41685             if(this['hide'+triggerIndex]){
41686                 t.dom.style.display = 'none';
41687             }
41688             t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
41689             t.addClassOnOver('x-form-trigger-over');
41690             t.addClassOnClick('x-form-trigger-click');
41691         }, this);
41692         this.triggers = ts.elements;
41693     },
41694
41695     onTrigger1Click : Roo.emptyFn,
41696     onTrigger2Click : Roo.emptyFn
41697 });/*
41698  * Based on:
41699  * Ext JS Library 1.1.1
41700  * Copyright(c) 2006-2007, Ext JS, LLC.
41701  *
41702  * Originally Released Under LGPL - original licence link has changed is not relivant.
41703  *
41704  * Fork - LGPL
41705  * <script type="text/javascript">
41706  */
41707  
41708 /**
41709  * @class Roo.form.TextArea
41710  * @extends Roo.form.TextField
41711  * Multiline text field.  Can be used as a direct replacement for traditional textarea fields, plus adds
41712  * support for auto-sizing.
41713  * @constructor
41714  * Creates a new TextArea
41715  * @param {Object} config Configuration options
41716  */
41717 Roo.form.TextArea = function(config){
41718     Roo.form.TextArea.superclass.constructor.call(this, config);
41719     // these are provided exchanges for backwards compat
41720     // minHeight/maxHeight were replaced by growMin/growMax to be
41721     // compatible with TextField growing config values
41722     if(this.minHeight !== undefined){
41723         this.growMin = this.minHeight;
41724     }
41725     if(this.maxHeight !== undefined){
41726         this.growMax = this.maxHeight;
41727     }
41728 };
41729
41730 Roo.extend(Roo.form.TextArea, Roo.form.TextField,  {
41731     /**
41732      * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
41733      */
41734     growMin : 60,
41735     /**
41736      * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
41737      */
41738     growMax: 1000,
41739     /**
41740      * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
41741      * in the field (equivalent to setting overflow: hidden, defaults to false)
41742      */
41743     preventScrollbars: false,
41744     /**
41745      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
41746      * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
41747      */
41748
41749     // private
41750     onRender : function(ct, position){
41751         if(!this.el){
41752             this.defaultAutoCreate = {
41753                 tag: "textarea",
41754                 style:"width:300px;height:60px;",
41755                 autocomplete: "new-password"
41756             };
41757         }
41758         Roo.form.TextArea.superclass.onRender.call(this, ct, position);
41759         if(this.grow){
41760             this.textSizeEl = Roo.DomHelper.append(document.body, {
41761                 tag: "pre", cls: "x-form-grow-sizer"
41762             });
41763             if(this.preventScrollbars){
41764                 this.el.setStyle("overflow", "hidden");
41765             }
41766             this.el.setHeight(this.growMin);
41767         }
41768     },
41769
41770     onDestroy : function(){
41771         if(this.textSizeEl){
41772             this.textSizeEl.parentNode.removeChild(this.textSizeEl);
41773         }
41774         Roo.form.TextArea.superclass.onDestroy.call(this);
41775     },
41776
41777     // private
41778     onKeyUp : function(e){
41779         if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
41780             this.autoSize();
41781         }
41782     },
41783
41784     /**
41785      * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
41786      * This only takes effect if grow = true, and fires the autosize event if the height changes.
41787      */
41788     autoSize : function(){
41789         if(!this.grow || !this.textSizeEl){
41790             return;
41791         }
41792         var el = this.el;
41793         var v = el.dom.value;
41794         var ts = this.textSizeEl;
41795
41796         ts.innerHTML = '';
41797         ts.appendChild(document.createTextNode(v));
41798         v = ts.innerHTML;
41799
41800         Roo.fly(ts).setWidth(this.el.getWidth());
41801         if(v.length < 1){
41802             v = "&#160;&#160;";
41803         }else{
41804             if(Roo.isIE){
41805                 v = v.replace(/\n/g, '<p>&#160;</p>');
41806             }
41807             v += "&#160;\n&#160;";
41808         }
41809         ts.innerHTML = v;
41810         var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
41811         if(h != this.lastHeight){
41812             this.lastHeight = h;
41813             this.el.setHeight(h);
41814             this.fireEvent("autosize", this, h);
41815         }
41816     }
41817 });/*
41818  * Based on:
41819  * Ext JS Library 1.1.1
41820  * Copyright(c) 2006-2007, Ext JS, LLC.
41821  *
41822  * Originally Released Under LGPL - original licence link has changed is not relivant.
41823  *
41824  * Fork - LGPL
41825  * <script type="text/javascript">
41826  */
41827  
41828
41829 /**
41830  * @class Roo.form.NumberField
41831  * @extends Roo.form.TextField
41832  * Numeric text field that provides automatic keystroke filtering and numeric validation.
41833  * @constructor
41834  * Creates a new NumberField
41835  * @param {Object} config Configuration options
41836  */
41837 Roo.form.NumberField = function(config){
41838     Roo.form.NumberField.superclass.constructor.call(this, config);
41839 };
41840
41841 Roo.extend(Roo.form.NumberField, Roo.form.TextField,  {
41842     /**
41843      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
41844      */
41845     fieldClass: "x-form-field x-form-num-field",
41846     /**
41847      * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
41848      */
41849     allowDecimals : true,
41850     /**
41851      * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
41852      */
41853     decimalSeparator : ".",
41854     /**
41855      * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
41856      */
41857     decimalPrecision : 2,
41858     /**
41859      * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
41860      */
41861     allowNegative : true,
41862     /**
41863      * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
41864      */
41865     minValue : Number.NEGATIVE_INFINITY,
41866     /**
41867      * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
41868      */
41869     maxValue : Number.MAX_VALUE,
41870     /**
41871      * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
41872      */
41873     minText : "The minimum value for this field is {0}",
41874     /**
41875      * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
41876      */
41877     maxText : "The maximum value for this field is {0}",
41878     /**
41879      * @cfg {String} nanText Error text to display if the value is not a valid number.  For example, this can happen
41880      * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
41881      */
41882     nanText : "{0} is not a valid number",
41883
41884     // private
41885     initEvents : function(){
41886         Roo.form.NumberField.superclass.initEvents.call(this);
41887         var allowed = "0123456789";
41888         if(this.allowDecimals){
41889             allowed += this.decimalSeparator;
41890         }
41891         if(this.allowNegative){
41892             allowed += "-";
41893         }
41894         this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
41895         var keyPress = function(e){
41896             var k = e.getKey();
41897             if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
41898                 return;
41899             }
41900             var c = e.getCharCode();
41901             if(allowed.indexOf(String.fromCharCode(c)) === -1){
41902                 e.stopEvent();
41903             }
41904         };
41905         this.el.on("keypress", keyPress, this);
41906     },
41907
41908     // private
41909     validateValue : function(value){
41910         if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
41911             return false;
41912         }
41913         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
41914              return true;
41915         }
41916         var num = this.parseValue(value);
41917         if(isNaN(num)){
41918             this.markInvalid(String.format(this.nanText, value));
41919             return false;
41920         }
41921         if(num < this.minValue){
41922             this.markInvalid(String.format(this.minText, this.minValue));
41923             return false;
41924         }
41925         if(num > this.maxValue){
41926             this.markInvalid(String.format(this.maxText, this.maxValue));
41927             return false;
41928         }
41929         return true;
41930     },
41931
41932     getValue : function(){
41933         return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
41934     },
41935
41936     // private
41937     parseValue : function(value){
41938         value = parseFloat(String(value).replace(this.decimalSeparator, "."));
41939         return isNaN(value) ? '' : value;
41940     },
41941
41942     // private
41943     fixPrecision : function(value){
41944         var nan = isNaN(value);
41945         if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
41946             return nan ? '' : value;
41947         }
41948         return parseFloat(value).toFixed(this.decimalPrecision);
41949     },
41950
41951     setValue : function(v){
41952         v = this.fixPrecision(v);
41953         Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
41954     },
41955
41956     // private
41957     decimalPrecisionFcn : function(v){
41958         return Math.floor(v);
41959     },
41960
41961     beforeBlur : function(){
41962         var v = this.parseValue(this.getRawValue());
41963         if(v){
41964             this.setValue(v);
41965         }
41966     }
41967 });/*
41968  * Based on:
41969  * Ext JS Library 1.1.1
41970  * Copyright(c) 2006-2007, Ext JS, LLC.
41971  *
41972  * Originally Released Under LGPL - original licence link has changed is not relivant.
41973  *
41974  * Fork - LGPL
41975  * <script type="text/javascript">
41976  */
41977  
41978 /**
41979  * @class Roo.form.DateField
41980  * @extends Roo.form.TriggerField
41981  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
41982 * @constructor
41983 * Create a new DateField
41984 * @param {Object} config
41985  */
41986 Roo.form.DateField = function(config)
41987 {
41988     Roo.form.DateField.superclass.constructor.call(this, config);
41989     
41990       this.addEvents({
41991          
41992         /**
41993          * @event select
41994          * Fires when a date is selected
41995              * @param {Roo.form.DateField} combo This combo box
41996              * @param {Date} date The date selected
41997              */
41998         'select' : true
41999          
42000     });
42001     
42002     
42003     if(typeof this.minValue == "string") {
42004         this.minValue = this.parseDate(this.minValue);
42005     }
42006     if(typeof this.maxValue == "string") {
42007         this.maxValue = this.parseDate(this.maxValue);
42008     }
42009     this.ddMatch = null;
42010     if(this.disabledDates){
42011         var dd = this.disabledDates;
42012         var re = "(?:";
42013         for(var i = 0; i < dd.length; i++){
42014             re += dd[i];
42015             if(i != dd.length-1) {
42016                 re += "|";
42017             }
42018         }
42019         this.ddMatch = new RegExp(re + ")");
42020     }
42021 };
42022
42023 Roo.extend(Roo.form.DateField, Roo.form.TriggerField,  {
42024     /**
42025      * @cfg {String} format
42026      * The default date format string which can be overriden for localization support.  The format must be
42027      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
42028      */
42029     format : "m/d/y",
42030     /**
42031      * @cfg {String} altFormats
42032      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
42033      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
42034      */
42035     altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
42036     /**
42037      * @cfg {Array} disabledDays
42038      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
42039      */
42040     disabledDays : null,
42041     /**
42042      * @cfg {String} disabledDaysText
42043      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
42044      */
42045     disabledDaysText : "Disabled",
42046     /**
42047      * @cfg {Array} disabledDates
42048      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
42049      * expression so they are very powerful. Some examples:
42050      * <ul>
42051      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
42052      * <li>["03/08", "09/16"] would disable those days for every year</li>
42053      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
42054      * <li>["03/../2006"] would disable every day in March 2006</li>
42055      * <li>["^03"] would disable every day in every March</li>
42056      * </ul>
42057      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
42058      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
42059      */
42060     disabledDates : null,
42061     /**
42062      * @cfg {String} disabledDatesText
42063      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
42064      */
42065     disabledDatesText : "Disabled",
42066         
42067         
42068         /**
42069      * @cfg {Date/String} zeroValue
42070      * if the date is less that this number, then the field is rendered as empty
42071      * default is 1800
42072      */
42073         zeroValue : '1800-01-01',
42074         
42075         
42076     /**
42077      * @cfg {Date/String} minValue
42078      * The minimum allowed date. Can be either a Javascript date object or a string date in a
42079      * valid format (defaults to null).
42080      */
42081     minValue : null,
42082     /**
42083      * @cfg {Date/String} maxValue
42084      * The maximum allowed date. Can be either a Javascript date object or a string date in a
42085      * valid format (defaults to null).
42086      */
42087     maxValue : null,
42088     /**
42089      * @cfg {String} minText
42090      * The error text to display when the date in the cell is before minValue (defaults to
42091      * 'The date in this field must be after {minValue}').
42092      */
42093     minText : "The date in this field must be equal to or after {0}",
42094     /**
42095      * @cfg {String} maxText
42096      * The error text to display when the date in the cell is after maxValue (defaults to
42097      * 'The date in this field must be before {maxValue}').
42098      */
42099     maxText : "The date in this field must be equal to or before {0}",
42100     /**
42101      * @cfg {String} invalidText
42102      * The error text to display when the date in the field is invalid (defaults to
42103      * '{value} is not a valid date - it must be in the format {format}').
42104      */
42105     invalidText : "{0} is not a valid date - it must be in the format {1}",
42106     /**
42107      * @cfg {String} triggerClass
42108      * An additional CSS class used to style the trigger button.  The trigger will always get the
42109      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
42110      * which displays a calendar icon).
42111      */
42112     triggerClass : 'x-form-date-trigger',
42113     
42114
42115     /**
42116      * @cfg {Boolean} useIso
42117      * if enabled, then the date field will use a hidden field to store the 
42118      * real value as iso formated date. default (false)
42119      */ 
42120     useIso : false,
42121     /**
42122      * @cfg {String/Object} autoCreate
42123      * A DomHelper element spec, or true for a default element spec (defaults to
42124      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
42125      */ 
42126     // private
42127     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
42128     
42129     // private
42130     hiddenField: false,
42131     
42132     onRender : function(ct, position)
42133     {
42134         Roo.form.DateField.superclass.onRender.call(this, ct, position);
42135         if (this.useIso) {
42136             //this.el.dom.removeAttribute('name'); 
42137             Roo.log("Changing name?");
42138             this.el.dom.setAttribute('name', this.name + '____hidden___' ); 
42139             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
42140                     'before', true);
42141             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
42142             // prevent input submission
42143             this.hiddenName = this.name;
42144         }
42145             
42146             
42147     },
42148     
42149     // private
42150     validateValue : function(value)
42151     {
42152         value = this.formatDate(value);
42153         if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
42154             Roo.log('super failed');
42155             return false;
42156         }
42157         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
42158              return true;
42159         }
42160         var svalue = value;
42161         value = this.parseDate(value);
42162         if(!value){
42163             Roo.log('parse date failed' + svalue);
42164             this.markInvalid(String.format(this.invalidText, svalue, this.format));
42165             return false;
42166         }
42167         var time = value.getTime();
42168         if(this.minValue && time < this.minValue.getTime()){
42169             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
42170             return false;
42171         }
42172         if(this.maxValue && time > this.maxValue.getTime()){
42173             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
42174             return false;
42175         }
42176         if(this.disabledDays){
42177             var day = value.getDay();
42178             for(var i = 0; i < this.disabledDays.length; i++) {
42179                 if(day === this.disabledDays[i]){
42180                     this.markInvalid(this.disabledDaysText);
42181                     return false;
42182                 }
42183             }
42184         }
42185         var fvalue = this.formatDate(value);
42186         if(this.ddMatch && this.ddMatch.test(fvalue)){
42187             this.markInvalid(String.format(this.disabledDatesText, fvalue));
42188             return false;
42189         }
42190         return true;
42191     },
42192
42193     // private
42194     // Provides logic to override the default TriggerField.validateBlur which just returns true
42195     validateBlur : function(){
42196         return !this.menu || !this.menu.isVisible();
42197     },
42198     
42199     getName: function()
42200     {
42201         // returns hidden if it's set..
42202         if (!this.rendered) {return ''};
42203         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
42204         
42205     },
42206
42207     /**
42208      * Returns the current date value of the date field.
42209      * @return {Date} The date value
42210      */
42211     getValue : function(){
42212         
42213         return  this.hiddenField ?
42214                 this.hiddenField.value :
42215                 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
42216     },
42217
42218     /**
42219      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
42220      * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
42221      * (the default format used is "m/d/y").
42222      * <br />Usage:
42223      * <pre><code>
42224 //All of these calls set the same date value (May 4, 2006)
42225
42226 //Pass a date object:
42227 var dt = new Date('5/4/06');
42228 dateField.setValue(dt);
42229
42230 //Pass a date string (default format):
42231 dateField.setValue('5/4/06');
42232
42233 //Pass a date string (custom format):
42234 dateField.format = 'Y-m-d';
42235 dateField.setValue('2006-5-4');
42236 </code></pre>
42237      * @param {String/Date} date The date or valid date string
42238      */
42239     setValue : function(date){
42240         if (this.hiddenField) {
42241             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
42242         }
42243         Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
42244         // make sure the value field is always stored as a date..
42245         this.value = this.parseDate(date);
42246         
42247         
42248     },
42249
42250     // private
42251     parseDate : function(value){
42252                 
42253                 if (value instanceof Date) {
42254                         if (value < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
42255                                 return  '';
42256                         }
42257                         return value;
42258                 }
42259                 
42260                 
42261         if(!value || value instanceof Date){
42262             return value;
42263         }
42264         var v = Date.parseDate(value, this.format);
42265          if (!v && this.useIso) {
42266             v = Date.parseDate(value, 'Y-m-d');
42267         }
42268         if(!v && this.altFormats){
42269             if(!this.altFormatsArray){
42270                 this.altFormatsArray = this.altFormats.split("|");
42271             }
42272             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
42273                 v = Date.parseDate(value, this.altFormatsArray[i]);
42274             }
42275         }
42276                 if (v < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
42277                         v = '';
42278                 }
42279         return v;
42280     },
42281
42282     // private
42283     formatDate : function(date, fmt){
42284         return (!date || !(date instanceof Date)) ?
42285                date : date.dateFormat(fmt || this.format);
42286     },
42287
42288     // private
42289     menuListeners : {
42290         select: function(m, d){
42291             
42292             this.setValue(d);
42293             this.fireEvent('select', this, d);
42294         },
42295         show : function(){ // retain focus styling
42296             this.onFocus();
42297         },
42298         hide : function(){
42299             this.focus.defer(10, this);
42300             var ml = this.menuListeners;
42301             this.menu.un("select", ml.select,  this);
42302             this.menu.un("show", ml.show,  this);
42303             this.menu.un("hide", ml.hide,  this);
42304         }
42305     },
42306
42307     // private
42308     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
42309     onTriggerClick : function(){
42310         if(this.disabled){
42311             return;
42312         }
42313         if(this.menu == null){
42314             this.menu = new Roo.menu.DateMenu();
42315         }
42316         Roo.apply(this.menu.picker,  {
42317             showClear: this.allowBlank,
42318             minDate : this.minValue,
42319             maxDate : this.maxValue,
42320             disabledDatesRE : this.ddMatch,
42321             disabledDatesText : this.disabledDatesText,
42322             disabledDays : this.disabledDays,
42323             disabledDaysText : this.disabledDaysText,
42324             format : this.useIso ? 'Y-m-d' : this.format,
42325             minText : String.format(this.minText, this.formatDate(this.minValue)),
42326             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
42327         });
42328         this.menu.on(Roo.apply({}, this.menuListeners, {
42329             scope:this
42330         }));
42331         this.menu.picker.setValue(this.getValue() || new Date());
42332         this.menu.show(this.el, "tl-bl?");
42333     },
42334
42335     beforeBlur : function(){
42336         var v = this.parseDate(this.getRawValue());
42337         if(v){
42338             this.setValue(v);
42339         }
42340     },
42341
42342     /*@
42343      * overide
42344      * 
42345      */
42346     isDirty : function() {
42347         if(this.disabled) {
42348             return false;
42349         }
42350         
42351         if(typeof(this.startValue) === 'undefined'){
42352             return false;
42353         }
42354         
42355         return String(this.getValue()) !== String(this.startValue);
42356         
42357     },
42358     // @overide
42359     cleanLeadingSpace : function(e)
42360     {
42361        return;
42362     }
42363     
42364 });/*
42365  * Based on:
42366  * Ext JS Library 1.1.1
42367  * Copyright(c) 2006-2007, Ext JS, LLC.
42368  *
42369  * Originally Released Under LGPL - original licence link has changed is not relivant.
42370  *
42371  * Fork - LGPL
42372  * <script type="text/javascript">
42373  */
42374  
42375 /**
42376  * @class Roo.form.MonthField
42377  * @extends Roo.form.TriggerField
42378  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
42379 * @constructor
42380 * Create a new MonthField
42381 * @param {Object} config
42382  */
42383 Roo.form.MonthField = function(config){
42384     
42385     Roo.form.MonthField.superclass.constructor.call(this, config);
42386     
42387       this.addEvents({
42388          
42389         /**
42390          * @event select
42391          * Fires when a date is selected
42392              * @param {Roo.form.MonthFieeld} combo This combo box
42393              * @param {Date} date The date selected
42394              */
42395         'select' : true
42396          
42397     });
42398     
42399     
42400     if(typeof this.minValue == "string") {
42401         this.minValue = this.parseDate(this.minValue);
42402     }
42403     if(typeof this.maxValue == "string") {
42404         this.maxValue = this.parseDate(this.maxValue);
42405     }
42406     this.ddMatch = null;
42407     if(this.disabledDates){
42408         var dd = this.disabledDates;
42409         var re = "(?:";
42410         for(var i = 0; i < dd.length; i++){
42411             re += dd[i];
42412             if(i != dd.length-1) {
42413                 re += "|";
42414             }
42415         }
42416         this.ddMatch = new RegExp(re + ")");
42417     }
42418 };
42419
42420 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField,  {
42421     /**
42422      * @cfg {String} format
42423      * The default date format string which can be overriden for localization support.  The format must be
42424      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
42425      */
42426     format : "M Y",
42427     /**
42428      * @cfg {String} altFormats
42429      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
42430      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
42431      */
42432     altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
42433     /**
42434      * @cfg {Array} disabledDays
42435      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
42436      */
42437     disabledDays : [0,1,2,3,4,5,6],
42438     /**
42439      * @cfg {String} disabledDaysText
42440      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
42441      */
42442     disabledDaysText : "Disabled",
42443     /**
42444      * @cfg {Array} disabledDates
42445      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
42446      * expression so they are very powerful. Some examples:
42447      * <ul>
42448      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
42449      * <li>["03/08", "09/16"] would disable those days for every year</li>
42450      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
42451      * <li>["03/../2006"] would disable every day in March 2006</li>
42452      * <li>["^03"] would disable every day in every March</li>
42453      * </ul>
42454      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
42455      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
42456      */
42457     disabledDates : null,
42458     /**
42459      * @cfg {String} disabledDatesText
42460      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
42461      */
42462     disabledDatesText : "Disabled",
42463     /**
42464      * @cfg {Date/String} minValue
42465      * The minimum allowed date. Can be either a Javascript date object or a string date in a
42466      * valid format (defaults to null).
42467      */
42468     minValue : null,
42469     /**
42470      * @cfg {Date/String} maxValue
42471      * The maximum allowed date. Can be either a Javascript date object or a string date in a
42472      * valid format (defaults to null).
42473      */
42474     maxValue : null,
42475     /**
42476      * @cfg {String} minText
42477      * The error text to display when the date in the cell is before minValue (defaults to
42478      * 'The date in this field must be after {minValue}').
42479      */
42480     minText : "The date in this field must be equal to or after {0}",
42481     /**
42482      * @cfg {String} maxTextf
42483      * The error text to display when the date in the cell is after maxValue (defaults to
42484      * 'The date in this field must be before {maxValue}').
42485      */
42486     maxText : "The date in this field must be equal to or before {0}",
42487     /**
42488      * @cfg {String} invalidText
42489      * The error text to display when the date in the field is invalid (defaults to
42490      * '{value} is not a valid date - it must be in the format {format}').
42491      */
42492     invalidText : "{0} is not a valid date - it must be in the format {1}",
42493     /**
42494      * @cfg {String} triggerClass
42495      * An additional CSS class used to style the trigger button.  The trigger will always get the
42496      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
42497      * which displays a calendar icon).
42498      */
42499     triggerClass : 'x-form-date-trigger',
42500     
42501
42502     /**
42503      * @cfg {Boolean} useIso
42504      * if enabled, then the date field will use a hidden field to store the 
42505      * real value as iso formated date. default (true)
42506      */ 
42507     useIso : true,
42508     /**
42509      * @cfg {String/Object} autoCreate
42510      * A DomHelper element spec, or true for a default element spec (defaults to
42511      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
42512      */ 
42513     // private
42514     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
42515     
42516     // private
42517     hiddenField: false,
42518     
42519     hideMonthPicker : false,
42520     
42521     onRender : function(ct, position)
42522     {
42523         Roo.form.MonthField.superclass.onRender.call(this, ct, position);
42524         if (this.useIso) {
42525             this.el.dom.removeAttribute('name'); 
42526             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
42527                     'before', true);
42528             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
42529             // prevent input submission
42530             this.hiddenName = this.name;
42531         }
42532             
42533             
42534     },
42535     
42536     // private
42537     validateValue : function(value)
42538     {
42539         value = this.formatDate(value);
42540         if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
42541             return false;
42542         }
42543         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
42544              return true;
42545         }
42546         var svalue = value;
42547         value = this.parseDate(value);
42548         if(!value){
42549             this.markInvalid(String.format(this.invalidText, svalue, this.format));
42550             return false;
42551         }
42552         var time = value.getTime();
42553         if(this.minValue && time < this.minValue.getTime()){
42554             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
42555             return false;
42556         }
42557         if(this.maxValue && time > this.maxValue.getTime()){
42558             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
42559             return false;
42560         }
42561         /*if(this.disabledDays){
42562             var day = value.getDay();
42563             for(var i = 0; i < this.disabledDays.length; i++) {
42564                 if(day === this.disabledDays[i]){
42565                     this.markInvalid(this.disabledDaysText);
42566                     return false;
42567                 }
42568             }
42569         }
42570         */
42571         var fvalue = this.formatDate(value);
42572         /*if(this.ddMatch && this.ddMatch.test(fvalue)){
42573             this.markInvalid(String.format(this.disabledDatesText, fvalue));
42574             return false;
42575         }
42576         */
42577         return true;
42578     },
42579
42580     // private
42581     // Provides logic to override the default TriggerField.validateBlur which just returns true
42582     validateBlur : function(){
42583         return !this.menu || !this.menu.isVisible();
42584     },
42585
42586     /**
42587      * Returns the current date value of the date field.
42588      * @return {Date} The date value
42589      */
42590     getValue : function(){
42591         
42592         
42593         
42594         return  this.hiddenField ?
42595                 this.hiddenField.value :
42596                 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
42597     },
42598
42599     /**
42600      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
42601      * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
42602      * (the default format used is "m/d/y").
42603      * <br />Usage:
42604      * <pre><code>
42605 //All of these calls set the same date value (May 4, 2006)
42606
42607 //Pass a date object:
42608 var dt = new Date('5/4/06');
42609 monthField.setValue(dt);
42610
42611 //Pass a date string (default format):
42612 monthField.setValue('5/4/06');
42613
42614 //Pass a date string (custom format):
42615 monthField.format = 'Y-m-d';
42616 monthField.setValue('2006-5-4');
42617 </code></pre>
42618      * @param {String/Date} date The date or valid date string
42619      */
42620     setValue : function(date){
42621         Roo.log('month setValue' + date);
42622         // can only be first of month..
42623         
42624         var val = this.parseDate(date);
42625         
42626         if (this.hiddenField) {
42627             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
42628         }
42629         Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
42630         this.value = this.parseDate(date);
42631     },
42632
42633     // private
42634     parseDate : function(value){
42635         if(!value || value instanceof Date){
42636             value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
42637             return value;
42638         }
42639         var v = Date.parseDate(value, this.format);
42640         if (!v && this.useIso) {
42641             v = Date.parseDate(value, 'Y-m-d');
42642         }
42643         if (v) {
42644             // 
42645             v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
42646         }
42647         
42648         
42649         if(!v && this.altFormats){
42650             if(!this.altFormatsArray){
42651                 this.altFormatsArray = this.altFormats.split("|");
42652             }
42653             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
42654                 v = Date.parseDate(value, this.altFormatsArray[i]);
42655             }
42656         }
42657         return v;
42658     },
42659
42660     // private
42661     formatDate : function(date, fmt){
42662         return (!date || !(date instanceof Date)) ?
42663                date : date.dateFormat(fmt || this.format);
42664     },
42665
42666     // private
42667     menuListeners : {
42668         select: function(m, d){
42669             this.setValue(d);
42670             this.fireEvent('select', this, d);
42671         },
42672         show : function(){ // retain focus styling
42673             this.onFocus();
42674         },
42675         hide : function(){
42676             this.focus.defer(10, this);
42677             var ml = this.menuListeners;
42678             this.menu.un("select", ml.select,  this);
42679             this.menu.un("show", ml.show,  this);
42680             this.menu.un("hide", ml.hide,  this);
42681         }
42682     },
42683     // private
42684     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
42685     onTriggerClick : function(){
42686         if(this.disabled){
42687             return;
42688         }
42689         if(this.menu == null){
42690             this.menu = new Roo.menu.DateMenu();
42691            
42692         }
42693         
42694         Roo.apply(this.menu.picker,  {
42695             
42696             showClear: this.allowBlank,
42697             minDate : this.minValue,
42698             maxDate : this.maxValue,
42699             disabledDatesRE : this.ddMatch,
42700             disabledDatesText : this.disabledDatesText,
42701             
42702             format : this.useIso ? 'Y-m-d' : this.format,
42703             minText : String.format(this.minText, this.formatDate(this.minValue)),
42704             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
42705             
42706         });
42707          this.menu.on(Roo.apply({}, this.menuListeners, {
42708             scope:this
42709         }));
42710        
42711         
42712         var m = this.menu;
42713         var p = m.picker;
42714         
42715         // hide month picker get's called when we called by 'before hide';
42716         
42717         var ignorehide = true;
42718         p.hideMonthPicker  = function(disableAnim){
42719             if (ignorehide) {
42720                 return;
42721             }
42722              if(this.monthPicker){
42723                 Roo.log("hideMonthPicker called");
42724                 if(disableAnim === true){
42725                     this.monthPicker.hide();
42726                 }else{
42727                     this.monthPicker.slideOut('t', {duration:.2});
42728                     p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
42729                     p.fireEvent("select", this, this.value);
42730                     m.hide();
42731                 }
42732             }
42733         }
42734         
42735         Roo.log('picker set value');
42736         Roo.log(this.getValue());
42737         p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
42738         m.show(this.el, 'tl-bl?');
42739         ignorehide  = false;
42740         // this will trigger hideMonthPicker..
42741         
42742         
42743         // hidden the day picker
42744         Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
42745         
42746         
42747         
42748       
42749         
42750         p.showMonthPicker.defer(100, p);
42751     
42752         
42753        
42754     },
42755
42756     beforeBlur : function(){
42757         var v = this.parseDate(this.getRawValue());
42758         if(v){
42759             this.setValue(v);
42760         }
42761     }
42762
42763     /** @cfg {Boolean} grow @hide */
42764     /** @cfg {Number} growMin @hide */
42765     /** @cfg {Number} growMax @hide */
42766     /**
42767      * @hide
42768      * @method autoSize
42769      */
42770 });/*
42771  * Based on:
42772  * Ext JS Library 1.1.1
42773  * Copyright(c) 2006-2007, Ext JS, LLC.
42774  *
42775  * Originally Released Under LGPL - original licence link has changed is not relivant.
42776  *
42777  * Fork - LGPL
42778  * <script type="text/javascript">
42779  */
42780  
42781
42782 /**
42783  * @class Roo.form.ComboBox
42784  * @extends Roo.form.TriggerField
42785  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
42786  * @constructor
42787  * Create a new ComboBox.
42788  * @param {Object} config Configuration options
42789  */
42790 Roo.form.ComboBox = function(config){
42791     Roo.form.ComboBox.superclass.constructor.call(this, config);
42792     this.addEvents({
42793         /**
42794          * @event expand
42795          * Fires when the dropdown list is expanded
42796              * @param {Roo.form.ComboBox} combo This combo box
42797              */
42798         'expand' : true,
42799         /**
42800          * @event collapse
42801          * Fires when the dropdown list is collapsed
42802              * @param {Roo.form.ComboBox} combo This combo box
42803              */
42804         'collapse' : true,
42805         /**
42806          * @event beforeselect
42807          * Fires before a list item is selected. Return false to cancel the selection.
42808              * @param {Roo.form.ComboBox} combo This combo box
42809              * @param {Roo.data.Record} record The data record returned from the underlying store
42810              * @param {Number} index The index of the selected item in the dropdown list
42811              */
42812         'beforeselect' : true,
42813         /**
42814          * @event select
42815          * Fires when a list item is selected
42816              * @param {Roo.form.ComboBox} combo This combo box
42817              * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
42818              * @param {Number} index The index of the selected item in the dropdown list
42819              */
42820         'select' : true,
42821         /**
42822          * @event beforequery
42823          * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
42824          * The event object passed has these properties:
42825              * @param {Roo.form.ComboBox} combo This combo box
42826              * @param {String} query The query
42827              * @param {Boolean} forceAll true to force "all" query
42828              * @param {Boolean} cancel true to cancel the query
42829              * @param {Object} e The query event object
42830              */
42831         'beforequery': true,
42832          /**
42833          * @event add
42834          * Fires when the 'add' icon is pressed (add a listener to enable add button)
42835              * @param {Roo.form.ComboBox} combo This combo box
42836              */
42837         'add' : true,
42838         /**
42839          * @event edit
42840          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
42841              * @param {Roo.form.ComboBox} combo This combo box
42842              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
42843              */
42844         'edit' : true
42845         
42846         
42847     });
42848     if(this.transform){
42849         this.allowDomMove = false;
42850         var s = Roo.getDom(this.transform);
42851         if(!this.hiddenName){
42852             this.hiddenName = s.name;
42853         }
42854         if(!this.store){
42855             this.mode = 'local';
42856             var d = [], opts = s.options;
42857             for(var i = 0, len = opts.length;i < len; i++){
42858                 var o = opts[i];
42859                 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
42860                 if(o.selected) {
42861                     this.value = value;
42862                 }
42863                 d.push([value, o.text]);
42864             }
42865             this.store = new Roo.data.SimpleStore({
42866                 'id': 0,
42867                 fields: ['value', 'text'],
42868                 data : d
42869             });
42870             this.valueField = 'value';
42871             this.displayField = 'text';
42872         }
42873         s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
42874         if(!this.lazyRender){
42875             this.target = true;
42876             this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
42877             s.parentNode.removeChild(s); // remove it
42878             this.render(this.el.parentNode);
42879         }else{
42880             s.parentNode.removeChild(s); // remove it
42881         }
42882
42883     }
42884     if (this.store) {
42885         this.store = Roo.factory(this.store, Roo.data);
42886     }
42887     
42888     this.selectedIndex = -1;
42889     if(this.mode == 'local'){
42890         if(config.queryDelay === undefined){
42891             this.queryDelay = 10;
42892         }
42893         if(config.minChars === undefined){
42894             this.minChars = 0;
42895         }
42896     }
42897 };
42898
42899 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
42900     /**
42901      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
42902      */
42903     /**
42904      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
42905      * rendering into an Roo.Editor, defaults to false)
42906      */
42907     /**
42908      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
42909      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
42910      */
42911     /**
42912      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
42913      */
42914     /**
42915      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
42916      * the dropdown list (defaults to undefined, with no header element)
42917      */
42918
42919      /**
42920      * @cfg {String/Roo.Template} tpl The template to use to render the output
42921      */
42922      
42923     // private
42924     defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
42925     /**
42926      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
42927      */
42928     listWidth: undefined,
42929     /**
42930      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
42931      * mode = 'remote' or 'text' if mode = 'local')
42932      */
42933     displayField: undefined,
42934     /**
42935      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
42936      * mode = 'remote' or 'value' if mode = 'local'). 
42937      * Note: use of a valueField requires the user make a selection
42938      * in order for a value to be mapped.
42939      */
42940     valueField: undefined,
42941     
42942     
42943     /**
42944      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
42945      * field's data value (defaults to the underlying DOM element's name)
42946      */
42947     hiddenName: undefined,
42948     /**
42949      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
42950      */
42951     listClass: '',
42952     /**
42953      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
42954      */
42955     selectedClass: 'x-combo-selected',
42956     /**
42957      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
42958      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
42959      * which displays a downward arrow icon).
42960      */
42961     triggerClass : 'x-form-arrow-trigger',
42962     /**
42963      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
42964      */
42965     shadow:'sides',
42966     /**
42967      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
42968      * anchor positions (defaults to 'tl-bl')
42969      */
42970     listAlign: 'tl-bl?',
42971     /**
42972      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
42973      */
42974     maxHeight: 300,
42975     /**
42976      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
42977      * query specified by the allQuery config option (defaults to 'query')
42978      */
42979     triggerAction: 'query',
42980     /**
42981      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
42982      * (defaults to 4, does not apply if editable = false)
42983      */
42984     minChars : 4,
42985     /**
42986      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
42987      * delay (typeAheadDelay) if it matches a known value (defaults to false)
42988      */
42989     typeAhead: false,
42990     /**
42991      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
42992      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
42993      */
42994     queryDelay: 500,
42995     /**
42996      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
42997      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
42998      */
42999     pageSize: 0,
43000     /**
43001      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
43002      * when editable = true (defaults to false)
43003      */
43004     selectOnFocus:false,
43005     /**
43006      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
43007      */
43008     queryParam: 'query',
43009     /**
43010      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
43011      * when mode = 'remote' (defaults to 'Loading...')
43012      */
43013     loadingText: 'Loading...',
43014     /**
43015      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
43016      */
43017     resizable: false,
43018     /**
43019      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
43020      */
43021     handleHeight : 8,
43022     /**
43023      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
43024      * traditional select (defaults to true)
43025      */
43026     editable: true,
43027     /**
43028      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
43029      */
43030     allQuery: '',
43031     /**
43032      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
43033      */
43034     mode: 'remote',
43035     /**
43036      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
43037      * listWidth has a higher value)
43038      */
43039     minListWidth : 70,
43040     /**
43041      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
43042      * allow the user to set arbitrary text into the field (defaults to false)
43043      */
43044     forceSelection:false,
43045     /**
43046      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
43047      * if typeAhead = true (defaults to 250)
43048      */
43049     typeAheadDelay : 250,
43050     /**
43051      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
43052      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
43053      */
43054     valueNotFoundText : undefined,
43055     /**
43056      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
43057      */
43058     blockFocus : false,
43059     
43060     /**
43061      * @cfg {Boolean} disableClear Disable showing of clear button.
43062      */
43063     disableClear : false,
43064     /**
43065      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
43066      */
43067     alwaysQuery : false,
43068     
43069     //private
43070     addicon : false,
43071     editicon: false,
43072     
43073     // element that contains real text value.. (when hidden is used..)
43074      
43075     // private
43076     onRender : function(ct, position)
43077     {
43078         Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
43079         
43080         if(this.hiddenName){
43081             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id:  (this.hiddenId||this.hiddenName)},
43082                     'before', true);
43083             this.hiddenField.value =
43084                 this.hiddenValue !== undefined ? this.hiddenValue :
43085                 this.value !== undefined ? this.value : '';
43086
43087             // prevent input submission
43088             this.el.dom.removeAttribute('name');
43089              
43090              
43091         }
43092         
43093         if(Roo.isGecko){
43094             this.el.dom.setAttribute('autocomplete', 'off');
43095         }
43096
43097         var cls = 'x-combo-list';
43098
43099         this.list = new Roo.Layer({
43100             shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
43101         });
43102
43103         var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
43104         this.list.setWidth(lw);
43105         this.list.swallowEvent('mousewheel');
43106         this.assetHeight = 0;
43107
43108         if(this.title){
43109             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
43110             this.assetHeight += this.header.getHeight();
43111         }
43112
43113         this.innerList = this.list.createChild({cls:cls+'-inner'});
43114         this.innerList.on('mouseover', this.onViewOver, this);
43115         this.innerList.on('mousemove', this.onViewMove, this);
43116         this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
43117         
43118         if(this.allowBlank && !this.pageSize && !this.disableClear){
43119             this.footer = this.list.createChild({cls:cls+'-ft'});
43120             this.pageTb = new Roo.Toolbar(this.footer);
43121            
43122         }
43123         if(this.pageSize){
43124             this.footer = this.list.createChild({cls:cls+'-ft'});
43125             this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
43126                     {pageSize: this.pageSize});
43127             
43128         }
43129         
43130         if (this.pageTb && this.allowBlank && !this.disableClear) {
43131             var _this = this;
43132             this.pageTb.add(new Roo.Toolbar.Fill(), {
43133                 cls: 'x-btn-icon x-btn-clear',
43134                 text: '&#160;',
43135                 handler: function()
43136                 {
43137                     _this.collapse();
43138                     _this.clearValue();
43139                     _this.onSelect(false, -1);
43140                 }
43141             });
43142         }
43143         if (this.footer) {
43144             this.assetHeight += this.footer.getHeight();
43145         }
43146         
43147
43148         if(!this.tpl){
43149             this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
43150         }
43151
43152         this.view = new Roo.View(this.innerList, this.tpl, {
43153             singleSelect:true,
43154             store: this.store,
43155             selectedClass: this.selectedClass
43156         });
43157
43158         this.view.on('click', this.onViewClick, this);
43159
43160         this.store.on('beforeload', this.onBeforeLoad, this);
43161         this.store.on('load', this.onLoad, this);
43162         this.store.on('loadexception', this.onLoadException, this);
43163
43164         if(this.resizable){
43165             this.resizer = new Roo.Resizable(this.list,  {
43166                pinned:true, handles:'se'
43167             });
43168             this.resizer.on('resize', function(r, w, h){
43169                 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
43170                 this.listWidth = w;
43171                 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
43172                 this.restrictHeight();
43173             }, this);
43174             this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
43175         }
43176         if(!this.editable){
43177             this.editable = true;
43178             this.setEditable(false);
43179         }  
43180         
43181         
43182         if (typeof(this.events.add.listeners) != 'undefined') {
43183             
43184             this.addicon = this.wrap.createChild(
43185                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });  
43186        
43187             this.addicon.on('click', function(e) {
43188                 this.fireEvent('add', this);
43189             }, this);
43190         }
43191         if (typeof(this.events.edit.listeners) != 'undefined') {
43192             
43193             this.editicon = this.wrap.createChild(
43194                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });  
43195             if (this.addicon) {
43196                 this.editicon.setStyle('margin-left', '40px');
43197             }
43198             this.editicon.on('click', function(e) {
43199                 
43200                 // we fire even  if inothing is selected..
43201                 this.fireEvent('edit', this, this.lastData );
43202                 
43203             }, this);
43204         }
43205         
43206         
43207         
43208     },
43209
43210     // private
43211     initEvents : function(){
43212         Roo.form.ComboBox.superclass.initEvents.call(this);
43213
43214         this.keyNav = new Roo.KeyNav(this.el, {
43215             "up" : function(e){
43216                 this.inKeyMode = true;
43217                 this.selectPrev();
43218             },
43219
43220             "down" : function(e){
43221                 if(!this.isExpanded()){
43222                     this.onTriggerClick();
43223                 }else{
43224                     this.inKeyMode = true;
43225                     this.selectNext();
43226                 }
43227             },
43228
43229             "enter" : function(e){
43230                 this.onViewClick();
43231                 //return true;
43232             },
43233
43234             "esc" : function(e){
43235                 this.collapse();
43236             },
43237
43238             "tab" : function(e){
43239                 this.onViewClick(false);
43240                 this.fireEvent("specialkey", this, e);
43241                 return true;
43242             },
43243
43244             scope : this,
43245
43246             doRelay : function(foo, bar, hname){
43247                 if(hname == 'down' || this.scope.isExpanded()){
43248                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
43249                 }
43250                 return true;
43251             },
43252
43253             forceKeyDown: true
43254         });
43255         this.queryDelay = Math.max(this.queryDelay || 10,
43256                 this.mode == 'local' ? 10 : 250);
43257         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
43258         if(this.typeAhead){
43259             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
43260         }
43261         if(this.editable !== false){
43262             this.el.on("keyup", this.onKeyUp, this);
43263         }
43264         if(this.forceSelection){
43265             this.on('blur', this.doForce, this);
43266         }
43267     },
43268
43269     onDestroy : function(){
43270         if(this.view){
43271             this.view.setStore(null);
43272             this.view.el.removeAllListeners();
43273             this.view.el.remove();
43274             this.view.purgeListeners();
43275         }
43276         if(this.list){
43277             this.list.destroy();
43278         }
43279         if(this.store){
43280             this.store.un('beforeload', this.onBeforeLoad, this);
43281             this.store.un('load', this.onLoad, this);
43282             this.store.un('loadexception', this.onLoadException, this);
43283         }
43284         Roo.form.ComboBox.superclass.onDestroy.call(this);
43285     },
43286
43287     // private
43288     fireKey : function(e){
43289         if(e.isNavKeyPress() && !this.list.isVisible()){
43290             this.fireEvent("specialkey", this, e);
43291         }
43292     },
43293
43294     // private
43295     onResize: function(w, h){
43296         Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
43297         
43298         if(typeof w != 'number'){
43299             // we do not handle it!?!?
43300             return;
43301         }
43302         var tw = this.trigger.getWidth();
43303         tw += this.addicon ? this.addicon.getWidth() : 0;
43304         tw += this.editicon ? this.editicon.getWidth() : 0;
43305         var x = w - tw;
43306         this.el.setWidth( this.adjustWidth('input', x));
43307             
43308         this.trigger.setStyle('left', x+'px');
43309         
43310         if(this.list && this.listWidth === undefined){
43311             var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
43312             this.list.setWidth(lw);
43313             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
43314         }
43315         
43316     
43317         
43318     },
43319
43320     /**
43321      * Allow or prevent the user from directly editing the field text.  If false is passed,
43322      * the user will only be able to select from the items defined in the dropdown list.  This method
43323      * is the runtime equivalent of setting the 'editable' config option at config time.
43324      * @param {Boolean} value True to allow the user to directly edit the field text
43325      */
43326     setEditable : function(value){
43327         if(value == this.editable){
43328             return;
43329         }
43330         this.editable = value;
43331         if(!value){
43332             this.el.dom.setAttribute('readOnly', true);
43333             this.el.on('mousedown', this.onTriggerClick,  this);
43334             this.el.addClass('x-combo-noedit');
43335         }else{
43336             this.el.dom.setAttribute('readOnly', false);
43337             this.el.un('mousedown', this.onTriggerClick,  this);
43338             this.el.removeClass('x-combo-noedit');
43339         }
43340     },
43341
43342     // private
43343     onBeforeLoad : function(){
43344         if(!this.hasFocus){
43345             return;
43346         }
43347         this.innerList.update(this.loadingText ?
43348                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
43349         this.restrictHeight();
43350         this.selectedIndex = -1;
43351     },
43352
43353     // private
43354     onLoad : function(){
43355         if(!this.hasFocus){
43356             return;
43357         }
43358         if(this.store.getCount() > 0){
43359             this.expand();
43360             this.restrictHeight();
43361             if(this.lastQuery == this.allQuery){
43362                 if(this.editable){
43363                     this.el.dom.select();
43364                 }
43365                 if(!this.selectByValue(this.value, true)){
43366                     this.select(0, true);
43367                 }
43368             }else{
43369                 this.selectNext();
43370                 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
43371                     this.taTask.delay(this.typeAheadDelay);
43372                 }
43373             }
43374         }else{
43375             this.onEmptyResults();
43376         }
43377         //this.el.focus();
43378     },
43379     // private
43380     onLoadException : function()
43381     {
43382         this.collapse();
43383         Roo.log(this.store.reader.jsonData);
43384         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
43385             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
43386         }
43387         
43388         
43389     },
43390     // private
43391     onTypeAhead : function(){
43392         if(this.store.getCount() > 0){
43393             var r = this.store.getAt(0);
43394             var newValue = r.data[this.displayField];
43395             var len = newValue.length;
43396             var selStart = this.getRawValue().length;
43397             if(selStart != len){
43398                 this.setRawValue(newValue);
43399                 this.selectText(selStart, newValue.length);
43400             }
43401         }
43402     },
43403
43404     // private
43405     onSelect : function(record, index){
43406         if(this.fireEvent('beforeselect', this, record, index) !== false){
43407             this.setFromData(index > -1 ? record.data : false);
43408             this.collapse();
43409             this.fireEvent('select', this, record, index);
43410         }
43411     },
43412
43413     /**
43414      * Returns the currently selected field value or empty string if no value is set.
43415      * @return {String} value The selected value
43416      */
43417     getValue : function(){
43418         if(this.valueField){
43419             return typeof this.value != 'undefined' ? this.value : '';
43420         }
43421         return Roo.form.ComboBox.superclass.getValue.call(this);
43422     },
43423
43424     /**
43425      * Clears any text/value currently set in the field
43426      */
43427     clearValue : function(){
43428         if(this.hiddenField){
43429             this.hiddenField.value = '';
43430         }
43431         this.value = '';
43432         this.setRawValue('');
43433         this.lastSelectionText = '';
43434         
43435     },
43436
43437     /**
43438      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
43439      * will be displayed in the field.  If the value does not match the data value of an existing item,
43440      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
43441      * Otherwise the field will be blank (although the value will still be set).
43442      * @param {String} value The value to match
43443      */
43444     setValue : function(v){
43445         var text = v;
43446         if(this.valueField){
43447             var r = this.findRecord(this.valueField, v);
43448             if(r){
43449                 text = r.data[this.displayField];
43450             }else if(this.valueNotFoundText !== undefined){
43451                 text = this.valueNotFoundText;
43452             }
43453         }
43454         this.lastSelectionText = text;
43455         if(this.hiddenField){
43456             this.hiddenField.value = v;
43457         }
43458         Roo.form.ComboBox.superclass.setValue.call(this, text);
43459         this.value = v;
43460     },
43461     /**
43462      * @property {Object} the last set data for the element
43463      */
43464     
43465     lastData : false,
43466     /**
43467      * Sets the value of the field based on a object which is related to the record format for the store.
43468      * @param {Object} value the value to set as. or false on reset?
43469      */
43470     setFromData : function(o){
43471         var dv = ''; // display value
43472         var vv = ''; // value value..
43473         this.lastData = o;
43474         if (this.displayField) {
43475             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
43476         } else {
43477             // this is an error condition!!!
43478             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
43479         }
43480         
43481         if(this.valueField){
43482             vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
43483         }
43484         if(this.hiddenField){
43485             this.hiddenField.value = vv;
43486             
43487             this.lastSelectionText = dv;
43488             Roo.form.ComboBox.superclass.setValue.call(this, dv);
43489             this.value = vv;
43490             return;
43491         }
43492         // no hidden field.. - we store the value in 'value', but still display
43493         // display field!!!!
43494         this.lastSelectionText = dv;
43495         Roo.form.ComboBox.superclass.setValue.call(this, dv);
43496         this.value = vv;
43497         
43498         
43499     },
43500     // private
43501     reset : function(){
43502         // overridden so that last data is reset..
43503         this.setValue(this.resetValue);
43504         this.originalValue = this.getValue();
43505         this.clearInvalid();
43506         this.lastData = false;
43507         if (this.view) {
43508             this.view.clearSelections();
43509         }
43510     },
43511     // private
43512     findRecord : function(prop, value){
43513         var record;
43514         if(this.store.getCount() > 0){
43515             this.store.each(function(r){
43516                 if(r.data[prop] == value){
43517                     record = r;
43518                     return false;
43519                 }
43520                 return true;
43521             });
43522         }
43523         return record;
43524     },
43525     
43526     getName: function()
43527     {
43528         // returns hidden if it's set..
43529         if (!this.rendered) {return ''};
43530         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
43531         
43532     },
43533     // private
43534     onViewMove : function(e, t){
43535         this.inKeyMode = false;
43536     },
43537
43538     // private
43539     onViewOver : function(e, t){
43540         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
43541             return;
43542         }
43543         var item = this.view.findItemFromChild(t);
43544         if(item){
43545             var index = this.view.indexOf(item);
43546             this.select(index, false);
43547         }
43548     },
43549
43550     // private
43551     onViewClick : function(doFocus)
43552     {
43553         var index = this.view.getSelectedIndexes()[0];
43554         var r = this.store.getAt(index);
43555         if(r){
43556             this.onSelect(r, index);
43557         }
43558         if(doFocus !== false && !this.blockFocus){
43559             this.el.focus();
43560         }
43561     },
43562
43563     // private
43564     restrictHeight : function(){
43565         this.innerList.dom.style.height = '';
43566         var inner = this.innerList.dom;
43567         var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
43568         this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
43569         this.list.beginUpdate();
43570         this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
43571         this.list.alignTo(this.el, this.listAlign);
43572         this.list.endUpdate();
43573     },
43574
43575     // private
43576     onEmptyResults : function(){
43577         this.collapse();
43578     },
43579
43580     /**
43581      * Returns true if the dropdown list is expanded, else false.
43582      */
43583     isExpanded : function(){
43584         return this.list.isVisible();
43585     },
43586
43587     /**
43588      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
43589      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
43590      * @param {String} value The data value of the item to select
43591      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
43592      * selected item if it is not currently in view (defaults to true)
43593      * @return {Boolean} True if the value matched an item in the list, else false
43594      */
43595     selectByValue : function(v, scrollIntoView){
43596         if(v !== undefined && v !== null){
43597             var r = this.findRecord(this.valueField || this.displayField, v);
43598             if(r){
43599                 this.select(this.store.indexOf(r), scrollIntoView);
43600                 return true;
43601             }
43602         }
43603         return false;
43604     },
43605
43606     /**
43607      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
43608      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
43609      * @param {Number} index The zero-based index of the list item to select
43610      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
43611      * selected item if it is not currently in view (defaults to true)
43612      */
43613     select : function(index, scrollIntoView){
43614         this.selectedIndex = index;
43615         this.view.select(index);
43616         if(scrollIntoView !== false){
43617             var el = this.view.getNode(index);
43618             if(el){
43619                 this.innerList.scrollChildIntoView(el, false);
43620             }
43621         }
43622     },
43623
43624     // private
43625     selectNext : function(){
43626         var ct = this.store.getCount();
43627         if(ct > 0){
43628             if(this.selectedIndex == -1){
43629                 this.select(0);
43630             }else if(this.selectedIndex < ct-1){
43631                 this.select(this.selectedIndex+1);
43632             }
43633         }
43634     },
43635
43636     // private
43637     selectPrev : function(){
43638         var ct = this.store.getCount();
43639         if(ct > 0){
43640             if(this.selectedIndex == -1){
43641                 this.select(0);
43642             }else if(this.selectedIndex != 0){
43643                 this.select(this.selectedIndex-1);
43644             }
43645         }
43646     },
43647
43648     // private
43649     onKeyUp : function(e){
43650         if(this.editable !== false && !e.isSpecialKey()){
43651             this.lastKey = e.getKey();
43652             this.dqTask.delay(this.queryDelay);
43653         }
43654     },
43655
43656     // private
43657     validateBlur : function(){
43658         return !this.list || !this.list.isVisible();   
43659     },
43660
43661     // private
43662     initQuery : function(){
43663         this.doQuery(this.getRawValue());
43664     },
43665
43666     // private
43667     doForce : function(){
43668         if(this.el.dom.value.length > 0){
43669             this.el.dom.value =
43670                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
43671              
43672         }
43673     },
43674
43675     /**
43676      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
43677      * query allowing the query action to be canceled if needed.
43678      * @param {String} query The SQL query to execute
43679      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
43680      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
43681      * saved in the current store (defaults to false)
43682      */
43683     doQuery : function(q, forceAll){
43684         if(q === undefined || q === null){
43685             q = '';
43686         }
43687         var qe = {
43688             query: q,
43689             forceAll: forceAll,
43690             combo: this,
43691             cancel:false
43692         };
43693         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
43694             return false;
43695         }
43696         q = qe.query;
43697         forceAll = qe.forceAll;
43698         if(forceAll === true || (q.length >= this.minChars)){
43699             if(this.lastQuery != q || this.alwaysQuery){
43700                 this.lastQuery = q;
43701                 if(this.mode == 'local'){
43702                     this.selectedIndex = -1;
43703                     if(forceAll){
43704                         this.store.clearFilter();
43705                     }else{
43706                         this.store.filter(this.displayField, q);
43707                     }
43708                     this.onLoad();
43709                 }else{
43710                     this.store.baseParams[this.queryParam] = q;
43711                     this.store.load({
43712                         params: this.getParams(q)
43713                     });
43714                     this.expand();
43715                 }
43716             }else{
43717                 this.selectedIndex = -1;
43718                 this.onLoad();   
43719             }
43720         }
43721     },
43722
43723     // private
43724     getParams : function(q){
43725         var p = {};
43726         //p[this.queryParam] = q;
43727         if(this.pageSize){
43728             p.start = 0;
43729             p.limit = this.pageSize;
43730         }
43731         return p;
43732     },
43733
43734     /**
43735      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
43736      */
43737     collapse : function(){
43738         if(!this.isExpanded()){
43739             return;
43740         }
43741         this.list.hide();
43742         Roo.get(document).un('mousedown', this.collapseIf, this);
43743         Roo.get(document).un('mousewheel', this.collapseIf, this);
43744         if (!this.editable) {
43745             Roo.get(document).un('keydown', this.listKeyPress, this);
43746         }
43747         this.fireEvent('collapse', this);
43748     },
43749
43750     // private
43751     collapseIf : function(e){
43752         if(!e.within(this.wrap) && !e.within(this.list)){
43753             this.collapse();
43754         }
43755     },
43756
43757     /**
43758      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
43759      */
43760     expand : function(){
43761         if(this.isExpanded() || !this.hasFocus){
43762             return;
43763         }
43764         this.list.alignTo(this.el, this.listAlign);
43765         this.list.show();
43766         Roo.get(document).on('mousedown', this.collapseIf, this);
43767         Roo.get(document).on('mousewheel', this.collapseIf, this);
43768         if (!this.editable) {
43769             Roo.get(document).on('keydown', this.listKeyPress, this);
43770         }
43771         
43772         this.fireEvent('expand', this);
43773     },
43774
43775     // private
43776     // Implements the default empty TriggerField.onTriggerClick function
43777     onTriggerClick : function(){
43778         if(this.disabled){
43779             return;
43780         }
43781         if(this.isExpanded()){
43782             this.collapse();
43783             if (!this.blockFocus) {
43784                 this.el.focus();
43785             }
43786             
43787         }else {
43788             this.hasFocus = true;
43789             if(this.triggerAction == 'all') {
43790                 this.doQuery(this.allQuery, true);
43791             } else {
43792                 this.doQuery(this.getRawValue());
43793             }
43794             if (!this.blockFocus) {
43795                 this.el.focus();
43796             }
43797         }
43798     },
43799     listKeyPress : function(e)
43800     {
43801         //Roo.log('listkeypress');
43802         // scroll to first matching element based on key pres..
43803         if (e.isSpecialKey()) {
43804             return false;
43805         }
43806         var k = String.fromCharCode(e.getKey()).toUpperCase();
43807         //Roo.log(k);
43808         var match  = false;
43809         var csel = this.view.getSelectedNodes();
43810         var cselitem = false;
43811         if (csel.length) {
43812             var ix = this.view.indexOf(csel[0]);
43813             cselitem  = this.store.getAt(ix);
43814             if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
43815                 cselitem = false;
43816             }
43817             
43818         }
43819         
43820         this.store.each(function(v) { 
43821             if (cselitem) {
43822                 // start at existing selection.
43823                 if (cselitem.id == v.id) {
43824                     cselitem = false;
43825                 }
43826                 return;
43827             }
43828                 
43829             if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
43830                 match = this.store.indexOf(v);
43831                 return false;
43832             }
43833         }, this);
43834         
43835         if (match === false) {
43836             return true; // no more action?
43837         }
43838         // scroll to?
43839         this.view.select(match);
43840         var sn = Roo.get(this.view.getSelectedNodes()[0]);
43841         sn.scrollIntoView(sn.dom.parentNode, false);
43842     } 
43843
43844     /** 
43845     * @cfg {Boolean} grow 
43846     * @hide 
43847     */
43848     /** 
43849     * @cfg {Number} growMin 
43850     * @hide 
43851     */
43852     /** 
43853     * @cfg {Number} growMax 
43854     * @hide 
43855     */
43856     /**
43857      * @hide
43858      * @method autoSize
43859      */
43860 });/*
43861  * Copyright(c) 2010-2012, Roo J Solutions Limited
43862  *
43863  * Licence LGPL
43864  *
43865  */
43866
43867 /**
43868  * @class Roo.form.ComboBoxArray
43869  * @extends Roo.form.TextField
43870  * A facebook style adder... for lists of email / people / countries  etc...
43871  * pick multiple items from a combo box, and shows each one.
43872  *
43873  *  Fred [x]  Brian [x]  [Pick another |v]
43874  *
43875  *
43876  *  For this to work: it needs various extra information
43877  *    - normal combo problay has
43878  *      name, hiddenName
43879  *    + displayField, valueField
43880  *
43881  *    For our purpose...
43882  *
43883  *
43884  *   If we change from 'extends' to wrapping...
43885  *   
43886  *  
43887  *
43888  
43889  
43890  * @constructor
43891  * Create a new ComboBoxArray.
43892  * @param {Object} config Configuration options
43893  */
43894  
43895
43896 Roo.form.ComboBoxArray = function(config)
43897 {
43898     this.addEvents({
43899         /**
43900          * @event beforeremove
43901          * Fires before remove the value from the list
43902              * @param {Roo.form.ComboBoxArray} _self This combo box array
43903              * @param {Roo.form.ComboBoxArray.Item} item removed item
43904              */
43905         'beforeremove' : true,
43906         /**
43907          * @event remove
43908          * Fires when remove the value from the list
43909              * @param {Roo.form.ComboBoxArray} _self This combo box array
43910              * @param {Roo.form.ComboBoxArray.Item} item removed item
43911              */
43912         'remove' : true
43913         
43914         
43915     });
43916     
43917     Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
43918     
43919     this.items = new Roo.util.MixedCollection(false);
43920     
43921     // construct the child combo...
43922     
43923     
43924     
43925     
43926    
43927     
43928 }
43929
43930  
43931 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
43932
43933     /**
43934      * @cfg {Roo.form.ComboBox} combo [required] The combo box that is wrapped
43935      */
43936     
43937     lastData : false,
43938     
43939     // behavies liek a hiddne field
43940     inputType:      'hidden',
43941     /**
43942      * @cfg {Number} width The width of the box that displays the selected element
43943      */ 
43944     width:          300,
43945
43946     
43947     
43948     /**
43949      * @cfg {String} name    The name of the visable items on this form (eg. titles not ids)
43950      */
43951     name : false,
43952     /**
43953      * @cfg {String} hiddenName    The hidden name of the field, often contains an comma seperated list of names
43954      */
43955     hiddenName : false,
43956       /**
43957      * @cfg {String} seperator    The value seperator normally ',' 
43958      */
43959     seperator : ',',
43960     
43961     // private the array of items that are displayed..
43962     items  : false,
43963     // private - the hidden field el.
43964     hiddenEl : false,
43965     // private - the filed el..
43966     el : false,
43967     
43968     //validateValue : function() { return true; }, // all values are ok!
43969     //onAddClick: function() { },
43970     
43971     onRender : function(ct, position) 
43972     {
43973         
43974         // create the standard hidden element
43975         //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
43976         
43977         
43978         // give fake names to child combo;
43979         this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
43980         this.combo.name = this.name ? (this.name+'-subcombo') : this.name;
43981         
43982         this.combo = Roo.factory(this.combo, Roo.form);
43983         this.combo.onRender(ct, position);
43984         if (typeof(this.combo.width) != 'undefined') {
43985             this.combo.onResize(this.combo.width,0);
43986         }
43987         
43988         this.combo.initEvents();
43989         
43990         // assigned so form know we need to do this..
43991         this.store          = this.combo.store;
43992         this.valueField     = this.combo.valueField;
43993         this.displayField   = this.combo.displayField ;
43994         
43995         
43996         this.combo.wrap.addClass('x-cbarray-grp');
43997         
43998         var cbwrap = this.combo.wrap.createChild(
43999             {tag: 'div', cls: 'x-cbarray-cb'},
44000             this.combo.el.dom
44001         );
44002         
44003              
44004         this.hiddenEl = this.combo.wrap.createChild({
44005             tag: 'input',  type:'hidden' , name: this.hiddenName, value : ''
44006         });
44007         this.el = this.combo.wrap.createChild({
44008             tag: 'input',  type:'hidden' , name: this.name, value : ''
44009         });
44010          //   this.el.dom.removeAttribute("name");
44011         
44012         
44013         this.outerWrap = this.combo.wrap;
44014         this.wrap = cbwrap;
44015         
44016         this.outerWrap.setWidth(this.width);
44017         this.outerWrap.dom.removeChild(this.el.dom);
44018         
44019         this.wrap.dom.appendChild(this.el.dom);
44020         this.outerWrap.dom.removeChild(this.combo.trigger.dom);
44021         this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
44022         
44023         this.combo.trigger.setStyle('position','relative');
44024         this.combo.trigger.setStyle('left', '0px');
44025         this.combo.trigger.setStyle('top', '2px');
44026         
44027         this.combo.el.setStyle('vertical-align', 'text-bottom');
44028         
44029         //this.trigger.setStyle('vertical-align', 'top');
44030         
44031         // this should use the code from combo really... on('add' ....)
44032         if (this.adder) {
44033             
44034         
44035             this.adder = this.outerWrap.createChild(
44036                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});  
44037             var _t = this;
44038             this.adder.on('click', function(e) {
44039                 _t.fireEvent('adderclick', this, e);
44040             }, _t);
44041         }
44042         //var _t = this;
44043         //this.adder.on('click', this.onAddClick, _t);
44044         
44045         
44046         this.combo.on('select', function(cb, rec, ix) {
44047             this.addItem(rec.data);
44048             
44049             cb.setValue('');
44050             cb.el.dom.value = '';
44051             //cb.lastData = rec.data;
44052             // add to list
44053             
44054         }, this);
44055         
44056         
44057     },
44058     
44059     
44060     getName: function()
44061     {
44062         // returns hidden if it's set..
44063         if (!this.rendered) {return ''};
44064         return  this.hiddenName ? this.hiddenName : this.name;
44065         
44066     },
44067     
44068     
44069     onResize: function(w, h){
44070         
44071         return;
44072         // not sure if this is needed..
44073         //this.combo.onResize(w,h);
44074         
44075         if(typeof w != 'number'){
44076             // we do not handle it!?!?
44077             return;
44078         }
44079         var tw = this.combo.trigger.getWidth();
44080         tw += this.addicon ? this.addicon.getWidth() : 0;
44081         tw += this.editicon ? this.editicon.getWidth() : 0;
44082         var x = w - tw;
44083         this.combo.el.setWidth( this.combo.adjustWidth('input', x));
44084             
44085         this.combo.trigger.setStyle('left', '0px');
44086         
44087         if(this.list && this.listWidth === undefined){
44088             var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
44089             this.list.setWidth(lw);
44090             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
44091         }
44092         
44093     
44094         
44095     },
44096     
44097     addItem: function(rec)
44098     {
44099         var valueField = this.combo.valueField;
44100         var displayField = this.combo.displayField;
44101         
44102         if (this.items.indexOfKey(rec[valueField]) > -1) {
44103             //console.log("GOT " + rec.data.id);
44104             return;
44105         }
44106         
44107         var x = new Roo.form.ComboBoxArray.Item({
44108             //id : rec[this.idField],
44109             data : rec,
44110             displayField : displayField ,
44111             tipField : displayField ,
44112             cb : this
44113         });
44114         // use the 
44115         this.items.add(rec[valueField],x);
44116         // add it before the element..
44117         this.updateHiddenEl();
44118         x.render(this.outerWrap, this.wrap.dom);
44119         // add the image handler..
44120     },
44121     
44122     updateHiddenEl : function()
44123     {
44124         this.validate();
44125         if (!this.hiddenEl) {
44126             return;
44127         }
44128         var ar = [];
44129         var idField = this.combo.valueField;
44130         
44131         this.items.each(function(f) {
44132             ar.push(f.data[idField]);
44133         });
44134         this.hiddenEl.dom.value = ar.join(this.seperator);
44135         this.validate();
44136     },
44137     
44138     reset : function()
44139     {
44140         this.items.clear();
44141         
44142         Roo.each(this.outerWrap.select('.x-cbarray-item', true).elements, function(el){
44143            el.remove();
44144         });
44145         
44146         this.el.dom.value = '';
44147         if (this.hiddenEl) {
44148             this.hiddenEl.dom.value = '';
44149         }
44150         
44151     },
44152     getValue: function()
44153     {
44154         return this.hiddenEl ? this.hiddenEl.dom.value : '';
44155     },
44156     setValue: function(v) // not a valid action - must use addItems..
44157     {
44158         
44159         this.reset();
44160          
44161         if (this.store.isLocal && (typeof(v) == 'string')) {
44162             // then we can use the store to find the values..
44163             // comma seperated at present.. this needs to allow JSON based encoding..
44164             this.hiddenEl.value  = v;
44165             var v_ar = [];
44166             Roo.each(v.split(this.seperator), function(k) {
44167                 Roo.log("CHECK " + this.valueField + ',' + k);
44168                 var li = this.store.query(this.valueField, k);
44169                 if (!li.length) {
44170                     return;
44171                 }
44172                 var add = {};
44173                 add[this.valueField] = k;
44174                 add[this.displayField] = li.item(0).data[this.displayField];
44175                 
44176                 this.addItem(add);
44177             }, this) 
44178              
44179         }
44180         if (typeof(v) == 'object' ) {
44181             // then let's assume it's an array of objects..
44182             Roo.each(v, function(l) {
44183                 var add = l;
44184                 if (typeof(l) == 'string') {
44185                     add = {};
44186                     add[this.valueField] = l;
44187                     add[this.displayField] = l
44188                 }
44189                 this.addItem(add);
44190             }, this);
44191              
44192         }
44193         
44194         
44195     },
44196     setFromData: function(v)
44197     {
44198         // this recieves an object, if setValues is called.
44199         this.reset();
44200         this.el.dom.value = v[this.displayField];
44201         this.hiddenEl.dom.value = v[this.valueField];
44202         if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
44203             return;
44204         }
44205         var kv = v[this.valueField];
44206         var dv = v[this.displayField];
44207         kv = typeof(kv) != 'string' ? '' : kv;
44208         dv = typeof(dv) != 'string' ? '' : dv;
44209         
44210         
44211         var keys = kv.split(this.seperator);
44212         var display = dv.split(this.seperator);
44213         for (var i = 0 ; i < keys.length; i++) {
44214             add = {};
44215             add[this.valueField] = keys[i];
44216             add[this.displayField] = display[i];
44217             this.addItem(add);
44218         }
44219       
44220         
44221     },
44222     
44223     /**
44224      * Validates the combox array value
44225      * @return {Boolean} True if the value is valid, else false
44226      */
44227     validate : function(){
44228         if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
44229             this.clearInvalid();
44230             return true;
44231         }
44232         return false;
44233     },
44234     
44235     validateValue : function(value){
44236         return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
44237         
44238     },
44239     
44240     /*@
44241      * overide
44242      * 
44243      */
44244     isDirty : function() {
44245         if(this.disabled) {
44246             return false;
44247         }
44248         
44249         try {
44250             var d = Roo.decode(String(this.originalValue));
44251         } catch (e) {
44252             return String(this.getValue()) !== String(this.originalValue);
44253         }
44254         
44255         var originalValue = [];
44256         
44257         for (var i = 0; i < d.length; i++){
44258             originalValue.push(d[i][this.valueField]);
44259         }
44260         
44261         return String(this.getValue()) !== String(originalValue.join(this.seperator));
44262         
44263     }
44264     
44265 });
44266
44267
44268
44269 /**
44270  * @class Roo.form.ComboBoxArray.Item
44271  * @extends Roo.BoxComponent
44272  * A selected item in the list
44273  *  Fred [x]  Brian [x]  [Pick another |v]
44274  * 
44275  * @constructor
44276  * Create a new item.
44277  * @param {Object} config Configuration options
44278  */
44279  
44280 Roo.form.ComboBoxArray.Item = function(config) {
44281     config.id = Roo.id();
44282     Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
44283 }
44284
44285 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
44286     data : {},
44287     cb: false,
44288     displayField : false,
44289     tipField : false,
44290     
44291     
44292     defaultAutoCreate : {
44293         tag: 'div',
44294         cls: 'x-cbarray-item',
44295         cn : [ 
44296             { tag: 'div' },
44297             {
44298                 tag: 'img',
44299                 width:16,
44300                 height : 16,
44301                 src : Roo.BLANK_IMAGE_URL ,
44302                 align: 'center'
44303             }
44304         ]
44305         
44306     },
44307     
44308  
44309     onRender : function(ct, position)
44310     {
44311         Roo.form.Field.superclass.onRender.call(this, ct, position);
44312         
44313         if(!this.el){
44314             var cfg = this.getAutoCreate();
44315             this.el = ct.createChild(cfg, position);
44316         }
44317         
44318         this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
44319         
44320         this.el.child('div').dom.innerHTML = this.cb.renderer ? 
44321             this.cb.renderer(this.data) :
44322             String.format('{0}',this.data[this.displayField]);
44323         
44324             
44325         this.el.child('div').dom.setAttribute('qtip',
44326                         String.format('{0}',this.data[this.tipField])
44327         );
44328         
44329         this.el.child('img').on('click', this.remove, this);
44330         
44331     },
44332    
44333     remove : function()
44334     {
44335         if(this.cb.disabled){
44336             return;
44337         }
44338         
44339         if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
44340             this.cb.items.remove(this);
44341             this.el.child('img').un('click', this.remove, this);
44342             this.el.remove();
44343             this.cb.updateHiddenEl();
44344
44345             this.cb.fireEvent('remove', this.cb, this);
44346         }
44347         
44348     }
44349 });/*
44350  * RooJS Library 1.1.1
44351  * Copyright(c) 2008-2011  Alan Knowles
44352  *
44353  * License - LGPL
44354  */
44355  
44356
44357 /**
44358  * @class Roo.form.ComboNested
44359  * @extends Roo.form.ComboBox
44360  * A combobox for that allows selection of nested items in a list,
44361  * eg.
44362  *
44363  *  Book
44364  *    -> red
44365  *    -> green
44366  *  Table
44367  *    -> square
44368  *      ->red
44369  *      ->green
44370  *    -> rectangle
44371  *      ->green
44372  *      
44373  * 
44374  * @constructor
44375  * Create a new ComboNested
44376  * @param {Object} config Configuration options
44377  */
44378 Roo.form.ComboNested = function(config){
44379     Roo.form.ComboCheck.superclass.constructor.call(this, config);
44380     // should verify some data...
44381     // like
44382     // hiddenName = required..
44383     // displayField = required
44384     // valudField == required
44385     var req= [ 'hiddenName', 'displayField', 'valueField' ];
44386     var _t = this;
44387     Roo.each(req, function(e) {
44388         if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
44389             throw "Roo.form.ComboNested : missing value for: " + e;
44390         }
44391     });
44392      
44393     
44394 };
44395
44396 Roo.extend(Roo.form.ComboNested, Roo.form.ComboBox, {
44397    
44398     /*
44399      * @config {Number} max Number of columns to show
44400      */
44401     
44402     maxColumns : 3,
44403    
44404     list : null, // the outermost div..
44405     innerLists : null, // the
44406     views : null,
44407     stores : null,
44408     // private
44409     loadingChildren : false,
44410     
44411     onRender : function(ct, position)
44412     {
44413         Roo.form.ComboBox.superclass.onRender.call(this, ct, position); // skip parent call - got to above..
44414         
44415         if(this.hiddenName){
44416             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id:  (this.hiddenId||this.hiddenName)},
44417                     'before', true);
44418             this.hiddenField.value =
44419                 this.hiddenValue !== undefined ? this.hiddenValue :
44420                 this.value !== undefined ? this.value : '';
44421
44422             // prevent input submission
44423             this.el.dom.removeAttribute('name');
44424              
44425              
44426         }
44427         
44428         if(Roo.isGecko){
44429             this.el.dom.setAttribute('autocomplete', 'off');
44430         }
44431
44432         var cls = 'x-combo-list';
44433
44434         this.list = new Roo.Layer({
44435             shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
44436         });
44437
44438         var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
44439         this.list.setWidth(lw);
44440         this.list.swallowEvent('mousewheel');
44441         this.assetHeight = 0;
44442
44443         if(this.title){
44444             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
44445             this.assetHeight += this.header.getHeight();
44446         }
44447         this.innerLists = [];
44448         this.views = [];
44449         this.stores = [];
44450         for (var i =0 ; i < this.maxColumns; i++) {
44451             this.onRenderList( cls, i);
44452         }
44453         
44454         // always needs footer, as we are going to have an 'OK' button.
44455         this.footer = this.list.createChild({cls:cls+'-ft'});
44456         this.pageTb = new Roo.Toolbar(this.footer);  
44457         var _this = this;
44458         this.pageTb.add(  {
44459             
44460             text: 'Done',
44461             handler: function()
44462             {
44463                 _this.collapse();
44464             }
44465         });
44466         
44467         if ( this.allowBlank && !this.disableClear) {
44468             
44469             this.pageTb.add(new Roo.Toolbar.Fill(), {
44470                 cls: 'x-btn-icon x-btn-clear',
44471                 text: '&#160;',
44472                 handler: function()
44473                 {
44474                     _this.collapse();
44475                     _this.clearValue();
44476                     _this.onSelect(false, -1);
44477                 }
44478             });
44479         }
44480         if (this.footer) {
44481             this.assetHeight += this.footer.getHeight();
44482         }
44483         
44484     },
44485     onRenderList : function (  cls, i)
44486     {
44487         
44488         var lw = Math.floor(
44489                 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
44490         );
44491         
44492         this.list.setWidth(lw); // default to '1'
44493
44494         var il = this.innerLists[i] = this.list.createChild({cls:cls+'-inner'});
44495         //il.on('mouseover', this.onViewOver, this, { list:  i });
44496         //il.on('mousemove', this.onViewMove, this, { list:  i });
44497         il.setWidth(lw);
44498         il.setStyle({ 'overflow-x' : 'hidden'});
44499
44500         if(!this.tpl){
44501             this.tpl = new Roo.Template({
44502                 html :  '<div class="'+cls+'-item '+cls+'-item-{cn:this.isEmpty}">{' + this.displayField + '}</div>',
44503                 isEmpty: function (value, allValues) {
44504                     //Roo.log(value);
44505                     var dl = typeof(value.data) != 'undefined' ? value.data.length : value.length; ///json is a nested response..
44506                     return dl ? 'has-children' : 'no-children'
44507                 }
44508             });
44509         }
44510         
44511         var store  = this.store;
44512         if (i > 0) {
44513             store  = new Roo.data.SimpleStore({
44514                 //fields : this.store.reader.meta.fields,
44515                 reader : this.store.reader,
44516                 data : [ ]
44517             });
44518         }
44519         this.stores[i]  = store;
44520                   
44521         var view = this.views[i] = new Roo.View(
44522             il,
44523             this.tpl,
44524             {
44525                 singleSelect:true,
44526                 store: store,
44527                 selectedClass: this.selectedClass
44528             }
44529         );
44530         view.getEl().setWidth(lw);
44531         view.getEl().setStyle({
44532             position: i < 1 ? 'relative' : 'absolute',
44533             top: 0,
44534             left: (i * lw ) + 'px',
44535             display : i > 0 ? 'none' : 'block'
44536         });
44537         view.on('selectionchange', this.onSelectChange.createDelegate(this, {list : i }, true));
44538         view.on('dblclick', this.onDoubleClick.createDelegate(this, {list : i }, true));
44539         //view.on('click', this.onViewClick, this, { list : i });
44540
44541         store.on('beforeload', this.onBeforeLoad, this);
44542         store.on('load',  this.onLoad, this, { list  : i});
44543         store.on('loadexception', this.onLoadException, this);
44544
44545         // hide the other vies..
44546         
44547         
44548         
44549     },
44550       
44551     restrictHeight : function()
44552     {
44553         var mh = 0;
44554         Roo.each(this.innerLists, function(il,i) {
44555             var el = this.views[i].getEl();
44556             el.dom.style.height = '';
44557             var inner = el.dom;
44558             var h = Math.max(il.clientHeight, il.offsetHeight, il.scrollHeight);
44559             // only adjust heights on other ones..
44560             mh = Math.max(h, mh);
44561             if (i < 1) {
44562                 
44563                 el.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
44564                 il.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
44565                
44566             }
44567             
44568             
44569         }, this);
44570         
44571         this.list.beginUpdate();
44572         this.list.setHeight(mh+this.list.getFrameWidth('tb')+this.assetHeight);
44573         this.list.alignTo(this.el, this.listAlign);
44574         this.list.endUpdate();
44575         
44576     },
44577      
44578     
44579     // -- store handlers..
44580     // private
44581     onBeforeLoad : function()
44582     {
44583         if(!this.hasFocus){
44584             return;
44585         }
44586         this.innerLists[0].update(this.loadingText ?
44587                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
44588         this.restrictHeight();
44589         this.selectedIndex = -1;
44590     },
44591     // private
44592     onLoad : function(a,b,c,d)
44593     {
44594         if (!this.loadingChildren) {
44595             // then we are loading the top level. - hide the children
44596             for (var i = 1;i < this.views.length; i++) {
44597                 this.views[i].getEl().setStyle({ display : 'none' });
44598             }
44599             var lw = Math.floor(
44600                 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
44601             );
44602         
44603              this.list.setWidth(lw); // default to '1'
44604
44605             
44606         }
44607         if(!this.hasFocus){
44608             return;
44609         }
44610         
44611         if(this.store.getCount() > 0) {
44612             this.expand();
44613             this.restrictHeight();   
44614         } else {
44615             this.onEmptyResults();
44616         }
44617         
44618         if (!this.loadingChildren) {
44619             this.selectActive();
44620         }
44621         /*
44622         this.stores[1].loadData([]);
44623         this.stores[2].loadData([]);
44624         this.views
44625         */    
44626     
44627         //this.el.focus();
44628     },
44629     
44630     
44631     // private
44632     onLoadException : function()
44633     {
44634         this.collapse();
44635         Roo.log(this.store.reader.jsonData);
44636         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
44637             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
44638         }
44639         
44640         
44641     },
44642     // no cleaning of leading spaces on blur here.
44643     cleanLeadingSpace : function(e) { },
44644     
44645
44646     onSelectChange : function (view, sels, opts )
44647     {
44648         var ix = view.getSelectedIndexes();
44649          
44650         if (opts.list > this.maxColumns - 2) {
44651             if (view.store.getCount()<  1) {
44652                 this.views[opts.list ].getEl().setStyle({ display :   'none' });
44653
44654             } else  {
44655                 if (ix.length) {
44656                     // used to clear ?? but if we are loading unselected 
44657                     this.setFromData(view.store.getAt(ix[0]).data);
44658                 }
44659                 
44660             }
44661             
44662             return;
44663         }
44664         
44665         if (!ix.length) {
44666             // this get's fired when trigger opens..
44667            // this.setFromData({});
44668             var str = this.stores[opts.list+1];
44669             str.data.clear(); // removeall wihtout the fire events..
44670             return;
44671         }
44672         
44673         var rec = view.store.getAt(ix[0]);
44674          
44675         this.setFromData(rec.data);
44676         this.fireEvent('select', this, rec, ix[0]);
44677         
44678         var lw = Math.floor(
44679              (
44680                 (this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')
44681              ) / this.maxColumns
44682         );
44683         this.loadingChildren = true;
44684         this.stores[opts.list+1].loadDataFromChildren( rec );
44685         this.loadingChildren = false;
44686         var dl = this.stores[opts.list+1]. getTotalCount();
44687         
44688         this.views[opts.list+1].getEl().setHeight( this.innerLists[0].getHeight());
44689         
44690         this.views[opts.list+1].getEl().setStyle({ display : dl ? 'block' : 'none' });
44691         for (var i = opts.list+2; i < this.views.length;i++) {
44692             this.views[i].getEl().setStyle({ display : 'none' });
44693         }
44694         
44695         this.innerLists[opts.list+1].setHeight( this.innerLists[0].getHeight());
44696         this.list.setWidth(lw * (opts.list + (dl ? 2 : 1)));
44697         
44698         if (this.isLoading) {
44699            // this.selectActive(opts.list);
44700         }
44701          
44702     },
44703     
44704     
44705     
44706     
44707     onDoubleClick : function()
44708     {
44709         this.collapse(); //??
44710     },
44711     
44712      
44713     
44714     
44715     
44716     // private
44717     recordToStack : function(store, prop, value, stack)
44718     {
44719         var cstore = new Roo.data.SimpleStore({
44720             //fields : this.store.reader.meta.fields, // we need array reader.. for
44721             reader : this.store.reader,
44722             data : [ ]
44723         });
44724         var _this = this;
44725         var record  = false;
44726         var srec = false;
44727         if(store.getCount() < 1){
44728             return false;
44729         }
44730         store.each(function(r){
44731             if(r.data[prop] == value){
44732                 record = r;
44733             srec = r;
44734                 return false;
44735             }
44736             if (r.data.cn && r.data.cn.length) {
44737                 cstore.loadDataFromChildren( r);
44738                 var cret = _this.recordToStack(cstore, prop, value, stack);
44739                 if (cret !== false) {
44740                     record = cret;
44741                     srec = r;
44742                     return false;
44743                 }
44744             }
44745              
44746             return true;
44747         });
44748         if (record == false) {
44749             return false
44750         }
44751         stack.unshift(srec);
44752         return record;
44753     },
44754     
44755     /*
44756      * find the stack of stores that match our value.
44757      *
44758      * 
44759      */
44760     
44761     selectActive : function ()
44762     {
44763         // if store is not loaded, then we will need to wait for that to happen first.
44764         var stack = [];
44765         this.recordToStack(this.store, this.valueField, this.getValue(), stack);
44766         for (var i = 0; i < stack.length; i++ ) {
44767             this.views[i].select(stack[i].store.indexOf(stack[i]), false, false );
44768         }
44769         
44770     }
44771         
44772          
44773     
44774     
44775     
44776     
44777 });/*
44778  * Based on:
44779  * Ext JS Library 1.1.1
44780  * Copyright(c) 2006-2007, Ext JS, LLC.
44781  *
44782  * Originally Released Under LGPL - original licence link has changed is not relivant.
44783  *
44784  * Fork - LGPL
44785  * <script type="text/javascript">
44786  */
44787 /**
44788  * @class Roo.form.Checkbox
44789  * @extends Roo.form.Field
44790  * Single checkbox field.  Can be used as a direct replacement for traditional checkbox fields.
44791  * @constructor
44792  * Creates a new Checkbox
44793  * @param {Object} config Configuration options
44794  */
44795 Roo.form.Checkbox = function(config){
44796     Roo.form.Checkbox.superclass.constructor.call(this, config);
44797     this.addEvents({
44798         /**
44799          * @event check
44800          * Fires when the checkbox is checked or unchecked.
44801              * @param {Roo.form.Checkbox} this This checkbox
44802              * @param {Boolean} checked The new checked value
44803              */
44804         check : true
44805     });
44806 };
44807
44808 Roo.extend(Roo.form.Checkbox, Roo.form.Field,  {
44809     /**
44810      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
44811      */
44812     focusClass : undefined,
44813     /**
44814      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
44815      */
44816     fieldClass: "x-form-field",
44817     /**
44818      * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
44819      */
44820     checked: false,
44821     /**
44822      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
44823      * {tag: "input", type: "checkbox", autocomplete: "off"})
44824      */
44825     defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
44826     /**
44827      * @cfg {String} boxLabel The text that appears beside the checkbox
44828      */
44829     boxLabel : "",
44830     /**
44831      * @cfg {String} inputValue The value that should go into the generated input element's value attribute
44832      */  
44833     inputValue : '1',
44834     /**
44835      * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
44836      */
44837      valueOff: '0', // value when not checked..
44838
44839     actionMode : 'viewEl', 
44840     //
44841     // private
44842     itemCls : 'x-menu-check-item x-form-item',
44843     groupClass : 'x-menu-group-item',
44844     inputType : 'hidden',
44845     
44846     
44847     inSetChecked: false, // check that we are not calling self...
44848     
44849     inputElement: false, // real input element?
44850     basedOn: false, // ????
44851     
44852     isFormField: true, // not sure where this is needed!!!!
44853
44854     onResize : function(){
44855         Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
44856         if(!this.boxLabel){
44857             this.el.alignTo(this.wrap, 'c-c');
44858         }
44859     },
44860
44861     initEvents : function(){
44862         Roo.form.Checkbox.superclass.initEvents.call(this);
44863         this.el.on("click", this.onClick,  this);
44864         this.el.on("change", this.onClick,  this);
44865     },
44866
44867
44868     getResizeEl : function(){
44869         return this.wrap;
44870     },
44871
44872     getPositionEl : function(){
44873         return this.wrap;
44874     },
44875
44876     // private
44877     onRender : function(ct, position){
44878         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
44879         /*
44880         if(this.inputValue !== undefined){
44881             this.el.dom.value = this.inputValue;
44882         }
44883         */
44884         //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
44885         this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
44886         var viewEl = this.wrap.createChild({ 
44887             tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
44888         this.viewEl = viewEl;   
44889         this.wrap.on('click', this.onClick,  this); 
44890         
44891         this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
44892         this.el.on('propertychange', this.setFromHidden,  this);  //ie
44893         
44894         
44895         
44896         if(this.boxLabel){
44897             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
44898         //    viewEl.on('click', this.onClick,  this); 
44899         }
44900         //if(this.checked){
44901             this.setChecked(this.checked);
44902         //}else{
44903             //this.checked = this.el.dom;
44904         //}
44905
44906     },
44907
44908     // private
44909     initValue : Roo.emptyFn,
44910
44911     /**
44912      * Returns the checked state of the checkbox.
44913      * @return {Boolean} True if checked, else false
44914      */
44915     getValue : function(){
44916         if(this.el){
44917             return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
44918         }
44919         return this.valueOff;
44920         
44921     },
44922
44923         // private
44924     onClick : function(){ 
44925         if (this.disabled) {
44926             return;
44927         }
44928         this.setChecked(!this.checked);
44929
44930         //if(this.el.dom.checked != this.checked){
44931         //    this.setValue(this.el.dom.checked);
44932        // }
44933     },
44934
44935     /**
44936      * Sets the checked state of the checkbox.
44937      * On is always based on a string comparison between inputValue and the param.
44938      * @param {Boolean/String} value - the value to set 
44939      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
44940      */
44941     setValue : function(v,suppressEvent){
44942         
44943         
44944         //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
44945         //if(this.el && this.el.dom){
44946         //    this.el.dom.checked = this.checked;
44947         //    this.el.dom.defaultChecked = this.checked;
44948         //}
44949         this.setChecked(String(v) === String(this.inputValue), suppressEvent);
44950         //this.fireEvent("check", this, this.checked);
44951     },
44952     // private..
44953     setChecked : function(state,suppressEvent)
44954     {
44955         if (this.inSetChecked) {
44956             this.checked = state;
44957             return;
44958         }
44959         
44960     
44961         if(this.wrap){
44962             this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
44963         }
44964         this.checked = state;
44965         if(suppressEvent !== true){
44966             this.fireEvent('check', this, state);
44967         }
44968         this.inSetChecked = true;
44969         this.el.dom.value = state ? this.inputValue : this.valueOff;
44970         this.inSetChecked = false;
44971         
44972     },
44973     // handle setting of hidden value by some other method!!?!?
44974     setFromHidden: function()
44975     {
44976         if(!this.el){
44977             return;
44978         }
44979         //console.log("SET FROM HIDDEN");
44980         //alert('setFrom hidden');
44981         this.setValue(this.el.dom.value);
44982     },
44983     
44984     onDestroy : function()
44985     {
44986         if(this.viewEl){
44987             Roo.get(this.viewEl).remove();
44988         }
44989          
44990         Roo.form.Checkbox.superclass.onDestroy.call(this);
44991     },
44992     
44993     setBoxLabel : function(str)
44994     {
44995         this.wrap.select('.x-form-cb-label', true).first().dom.innerHTML = str;
44996     }
44997
44998 });/*
44999  * Based on:
45000  * Ext JS Library 1.1.1
45001  * Copyright(c) 2006-2007, Ext JS, LLC.
45002  *
45003  * Originally Released Under LGPL - original licence link has changed is not relivant.
45004  *
45005  * Fork - LGPL
45006  * <script type="text/javascript">
45007  */
45008  
45009 /**
45010  * @class Roo.form.Radio
45011  * @extends Roo.form.Checkbox
45012  * Single radio field.  Same as Checkbox, but provided as a convenience for automatically setting the input type.
45013  * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
45014  * @constructor
45015  * Creates a new Radio
45016  * @param {Object} config Configuration options
45017  */
45018 Roo.form.Radio = function(){
45019     Roo.form.Radio.superclass.constructor.apply(this, arguments);
45020 };
45021 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
45022     inputType: 'radio',
45023
45024     /**
45025      * If this radio is part of a group, it will return the selected value
45026      * @return {String}
45027      */
45028     getGroupValue : function(){
45029         return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
45030     },
45031     
45032     
45033     onRender : function(ct, position){
45034         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
45035         
45036         if(this.inputValue !== undefined){
45037             this.el.dom.value = this.inputValue;
45038         }
45039          
45040         this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
45041         //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
45042         //var viewEl = this.wrap.createChild({ 
45043         //    tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
45044         //this.viewEl = viewEl;   
45045         //this.wrap.on('click', this.onClick,  this); 
45046         
45047         //this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
45048         //this.el.on('propertychange', this.setFromHidden,  this);  //ie
45049         
45050         
45051         
45052         if(this.boxLabel){
45053             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
45054         //    viewEl.on('click', this.onClick,  this); 
45055         }
45056          if(this.checked){
45057             this.el.dom.checked =   'checked' ;
45058         }
45059          
45060     } 
45061     
45062     
45063 });Roo.rtf = {}; // namespace
45064 Roo.rtf.Hex = function(hex)
45065 {
45066     this.hexstr = hex;
45067 };
45068 Roo.rtf.Paragraph = function(opts)
45069 {
45070     this.content = []; ///??? is that used?
45071 };Roo.rtf.Span = function(opts)
45072 {
45073     this.value = opts.value;
45074 };
45075
45076 Roo.rtf.Group = function(parent)
45077 {
45078     // we dont want to acutally store parent - it will make debug a nightmare..
45079     this.content = [];
45080     this.cn  = [];
45081      
45082        
45083     
45084 };
45085
45086 Roo.rtf.Group.prototype = {
45087     ignorable : false,
45088     content: false,
45089     cn: false,
45090     addContent : function(node) {
45091         // could set styles...
45092         this.content.push(node);
45093     },
45094     addChild : function(cn)
45095     {
45096         this.cn.push(cn);
45097     },
45098     // only for images really...
45099     toDataURL : function()
45100     {
45101         var mimetype = false;
45102         switch(true) {
45103             case this.content.filter(function(a) { return a.value == 'pngblip' } ).length > 0: 
45104                 mimetype = "image/png";
45105                 break;
45106              case this.content.filter(function(a) { return a.value == 'jpegblip' } ).length > 0:
45107                 mimetype = "image/jpeg";
45108                 break;
45109             default :
45110                 return 'about:blank'; // ?? error?
45111         }
45112         
45113         
45114         var hexstring = this.content[this.content.length-1].value;
45115         
45116         return 'data:' + mimetype + ';base64,' + btoa(hexstring.match(/\w{2}/g).map(function(a) {
45117             return String.fromCharCode(parseInt(a, 16));
45118         }).join(""));
45119     }
45120     
45121 };
45122 // this looks like it's normally the {rtf{ .... }}
45123 Roo.rtf.Document = function()
45124 {
45125     // we dont want to acutally store parent - it will make debug a nightmare..
45126     this.rtlch  = [];
45127     this.content = [];
45128     this.cn = [];
45129     
45130 };
45131 Roo.extend(Roo.rtf.Document, Roo.rtf.Group, { 
45132     addChild : function(cn)
45133     {
45134         this.cn.push(cn);
45135         switch(cn.type) {
45136             case 'rtlch': // most content seems to be inside this??
45137             case 'listtext':
45138             case 'shpinst':
45139                 this.rtlch.push(cn);
45140                 return;
45141             default:
45142                 this[cn.type] = cn;
45143         }
45144         
45145     },
45146     
45147     getElementsByType : function(type)
45148     {
45149         var ret =  [];
45150         this._getElementsByType(type, ret, this.cn, 'rtf');
45151         return ret;
45152     },
45153     _getElementsByType : function (type, ret, search_array, path)
45154     {
45155         search_array.forEach(function(n,i) {
45156             if (n.type == type) {
45157                 n.path = path + '/' + n.type + ':' + i;
45158                 ret.push(n);
45159             }
45160             if (n.cn.length > 0) {
45161                 this._getElementsByType(type, ret, n.cn, path + '/' + n.type+':'+i);
45162             }
45163         },this);
45164     }
45165     
45166 });
45167  
45168 Roo.rtf.Ctrl = function(opts)
45169 {
45170     this.value = opts.value;
45171     this.param = opts.param;
45172 };
45173 /**
45174  *
45175  *
45176  * based on this https://github.com/iarna/rtf-parser
45177  * it's really only designed to extract pict from pasted RTF 
45178  *
45179  * usage:
45180  *
45181  *  var images = new Roo.rtf.Parser().parse(a_string).filter(function(g) { return g.type == 'pict'; });
45182  *  
45183  *
45184  */
45185
45186  
45187
45188
45189
45190 Roo.rtf.Parser = function(text) {
45191     //super({objectMode: true})
45192     this.text = '';
45193     this.parserState = this.parseText;
45194     
45195     // these are for interpeter...
45196     this.doc = {};
45197     ///this.parserState = this.parseTop
45198     this.groupStack = [];
45199     this.hexStore = [];
45200     this.doc = false;
45201     
45202     this.groups = []; // where we put the return.
45203     
45204     for (var ii = 0; ii < text.length; ++ii) {
45205         ++this.cpos;
45206         
45207         if (text[ii] === '\n') {
45208             ++this.row;
45209             this.col = 1;
45210         } else {
45211             ++this.col;
45212         }
45213         this.parserState(text[ii]);
45214     }
45215     
45216     
45217     
45218 };
45219 Roo.rtf.Parser.prototype = {
45220     text : '', // string being parsed..
45221     controlWord : '',
45222     controlWordParam :  '',
45223     hexChar : '',
45224     doc : false,
45225     group: false,
45226     groupStack : false,
45227     hexStore : false,
45228     
45229     
45230     cpos : 0, 
45231     row : 1, // reportin?
45232     col : 1, //
45233
45234      
45235     push : function (el)
45236     {
45237         var m = 'cmd'+ el.type;
45238         if (typeof(this[m]) == 'undefined') {
45239             Roo.log('invalid cmd:' + el.type);
45240             return;
45241         }
45242         this[m](el);
45243         //Roo.log(el);
45244     },
45245     flushHexStore : function()
45246     {
45247         if (this.hexStore.length < 1) {
45248             return;
45249         }
45250         var hexstr = this.hexStore.map(
45251             function(cmd) {
45252                 return cmd.value;
45253         }).join('');
45254         
45255         this.group.addContent( new Roo.rtf.Hex( hexstr ));
45256               
45257             
45258         this.hexStore.splice(0)
45259         
45260     },
45261     
45262     cmdgroupstart : function()
45263     {
45264         this.flushHexStore();
45265         if (this.group) {
45266             this.groupStack.push(this.group);
45267         }
45268          // parent..
45269         if (this.doc === false) {
45270             this.group = this.doc = new Roo.rtf.Document();
45271             return;
45272             
45273         }
45274         this.group = new Roo.rtf.Group(this.group);
45275     },
45276     cmdignorable : function()
45277     {
45278         this.flushHexStore();
45279         this.group.ignorable = true;
45280     },
45281     cmdendparagraph : function()
45282     {
45283         this.flushHexStore();
45284         this.group.addContent(new Roo.rtf.Paragraph());
45285     },
45286     cmdgroupend : function ()
45287     {
45288         this.flushHexStore();
45289         var endingGroup = this.group;
45290         
45291         
45292         this.group = this.groupStack.pop();
45293         if (this.group) {
45294             this.group.addChild(endingGroup);
45295         }
45296         
45297         
45298         
45299         var doc = this.group || this.doc;
45300         //if (endingGroup instanceof FontTable) {
45301         //  doc.fonts = endingGroup.table
45302         //} else if (endingGroup instanceof ColorTable) {
45303         //  doc.colors = endingGroup.table
45304         //} else if (endingGroup !== this.doc && !endingGroup.get('ignorable')) {
45305         if (endingGroup.ignorable === false) {
45306             //code
45307             this.groups.push(endingGroup);
45308            // Roo.log( endingGroup );
45309         }
45310             //Roo.each(endingGroup.content, function(item)) {
45311             //    doc.addContent(item);
45312             //}
45313             //process.emit('debug', 'GROUP END', endingGroup.type, endingGroup.get('ignorable'))
45314         //}
45315     },
45316     cmdtext : function (cmd)
45317     {
45318         this.flushHexStore();
45319         if (!this.group) { // an RTF fragment, missing the {\rtf1 header
45320             //this.group = this.doc
45321         }
45322         this.group.addContent(new Roo.rtf.Span(cmd));
45323     },
45324     cmdcontrolword : function (cmd)
45325     {
45326         this.flushHexStore();
45327         if (!this.group.type) {
45328             this.group.type = cmd.value;
45329             return;
45330         }
45331         this.group.addContent(new Roo.rtf.Ctrl(cmd));
45332         // we actually don't care about ctrl words...
45333         return ;
45334         /*
45335         var method = 'ctrl$' + cmd.value.replace(/-(.)/g, (_, char) => char.toUpperCase())
45336         if (this[method]) {
45337             this[method](cmd.param)
45338         } else {
45339             if (!this.group.get('ignorable')) process.emit('debug', method, cmd.param)
45340         }
45341         */
45342     },
45343     cmdhexchar : function(cmd) {
45344         this.hexStore.push(cmd);
45345     },
45346     cmderror : function(cmd) {
45347         throw new Exception (cmd.value);
45348     },
45349     
45350     /*
45351       _flush (done) {
45352         if (this.text !== '\u0000') this.emitText()
45353         done()
45354       }
45355       */
45356       
45357       
45358     parseText : function(c)
45359     {
45360         if (c === '\\') {
45361             this.parserState = this.parseEscapes;
45362         } else if (c === '{') {
45363             this.emitStartGroup();
45364         } else if (c === '}') {
45365             this.emitEndGroup();
45366         } else if (c === '\x0A' || c === '\x0D') {
45367             // cr/lf are noise chars
45368         } else {
45369             this.text += c;
45370         }
45371     },
45372     
45373     parseEscapes: function (c)
45374     {
45375         if (c === '\\' || c === '{' || c === '}') {
45376             this.text += c;
45377             this.parserState = this.parseText;
45378         } else {
45379             this.parserState = this.parseControlSymbol;
45380             this.parseControlSymbol(c);
45381         }
45382     },
45383     parseControlSymbol: function(c)
45384     {
45385         if (c === '~') {
45386             this.text += '\u00a0'; // nbsp
45387             this.parserState = this.parseText
45388         } else if (c === '-') {
45389              this.text += '\u00ad'; // soft hyphen
45390         } else if (c === '_') {
45391             this.text += '\u2011'; // non-breaking hyphen
45392         } else if (c === '*') {
45393             this.emitIgnorable();
45394             this.parserState = this.parseText;
45395         } else if (c === "'") {
45396             this.parserState = this.parseHexChar;
45397         } else if (c === '|') { // formula cacter
45398             this.emitFormula();
45399             this.parserState = this.parseText;
45400         } else if (c === ':') { // subentry in an index entry
45401             this.emitIndexSubEntry();
45402             this.parserState = this.parseText;
45403         } else if (c === '\x0a') {
45404             this.emitEndParagraph();
45405             this.parserState = this.parseText;
45406         } else if (c === '\x0d') {
45407             this.emitEndParagraph();
45408             this.parserState = this.parseText;
45409         } else {
45410             this.parserState = this.parseControlWord;
45411             this.parseControlWord(c);
45412         }
45413     },
45414     parseHexChar: function (c)
45415     {
45416         if (/^[A-Fa-f0-9]$/.test(c)) {
45417             this.hexChar += c;
45418             if (this.hexChar.length >= 2) {
45419               this.emitHexChar();
45420               this.parserState = this.parseText;
45421             }
45422             return;
45423         }
45424         this.emitError("Invalid character \"" + c + "\" in hex literal.");
45425         this.parserState = this.parseText;
45426         
45427     },
45428     parseControlWord : function(c)
45429     {
45430         if (c === ' ') {
45431             this.emitControlWord();
45432             this.parserState = this.parseText;
45433         } else if (/^[-\d]$/.test(c)) {
45434             this.parserState = this.parseControlWordParam;
45435             this.controlWordParam += c;
45436         } else if (/^[A-Za-z]$/.test(c)) {
45437           this.controlWord += c;
45438         } else {
45439           this.emitControlWord();
45440           this.parserState = this.parseText;
45441           this.parseText(c);
45442         }
45443     },
45444     parseControlWordParam : function (c) {
45445         if (/^\d$/.test(c)) {
45446           this.controlWordParam += c;
45447         } else if (c === ' ') {
45448           this.emitControlWord();
45449           this.parserState = this.parseText;
45450         } else {
45451           this.emitControlWord();
45452           this.parserState = this.parseText;
45453           this.parseText(c);
45454         }
45455     },
45456     
45457     
45458     
45459     
45460     emitText : function () {
45461         if (this.text === '') {
45462             return;
45463         }
45464         this.push({
45465             type: 'text',
45466             value: this.text,
45467             pos: this.cpos,
45468             row: this.row,
45469             col: this.col
45470         });
45471         this.text = ''
45472     },
45473     emitControlWord : function ()
45474     {
45475         this.emitText();
45476         if (this.controlWord === '') {
45477             this.emitError('empty control word');
45478         } else {
45479             this.push({
45480                   type: 'controlword',
45481                   value: this.controlWord,
45482                   param: this.controlWordParam !== '' && Number(this.controlWordParam),
45483                   pos: this.cpos,
45484                   row: this.row,
45485                   col: this.col
45486             });
45487         }
45488         this.controlWord = '';
45489         this.controlWordParam = '';
45490     },
45491     emitStartGroup : function ()
45492     {
45493         this.emitText();
45494         this.push({
45495             type: 'groupstart',
45496             pos: this.cpos,
45497             row: this.row,
45498             col: this.col
45499         });
45500     },
45501     emitEndGroup : function ()
45502     {
45503         this.emitText();
45504         this.push({
45505             type: 'groupend',
45506             pos: this.cpos,
45507             row: this.row,
45508             col: this.col
45509         });
45510     },
45511     emitIgnorable : function ()
45512     {
45513         this.emitText();
45514         this.push({
45515             type: 'ignorable',
45516             pos: this.cpos,
45517             row: this.row,
45518             col: this.col
45519         });
45520     },
45521     emitHexChar : function ()
45522     {
45523         this.emitText();
45524         this.push({
45525             type: 'hexchar',
45526             value: this.hexChar,
45527             pos: this.cpos,
45528             row: this.row,
45529             col: this.col
45530         });
45531         this.hexChar = ''
45532     },
45533     emitError : function (message)
45534     {
45535       this.emitText();
45536       this.push({
45537             type: 'error',
45538             value: message,
45539             row: this.row,
45540             col: this.col,
45541             char: this.cpos //,
45542             //stack: new Error().stack
45543         });
45544     },
45545     emitEndParagraph : function () {
45546         this.emitText();
45547         this.push({
45548             type: 'endparagraph',
45549             pos: this.cpos,
45550             row: this.row,
45551             col: this.col
45552         });
45553     }
45554      
45555 } ;
45556 Roo.htmleditor = {};
45557  
45558 /**
45559  * @class Roo.htmleditor.Filter
45560  * Base Class for filtering htmleditor stuff. - do not use this directly - extend it.
45561  * @cfg {DomElement} node The node to iterate and filter
45562  * @cfg {boolean|String|Array} tag Tags to replace 
45563  * @constructor
45564  * Create a new Filter.
45565  * @param {Object} config Configuration options
45566  */
45567
45568
45569
45570 Roo.htmleditor.Filter = function(cfg) {
45571     Roo.apply(this.cfg);
45572     // this does not actually call walk as it's really just a abstract class
45573 }
45574
45575
45576 Roo.htmleditor.Filter.prototype = {
45577     
45578     node: false,
45579     
45580     tag: false,
45581
45582     // overrride to do replace comments.
45583     replaceComment : false,
45584     
45585     // overrride to do replace or do stuff with tags..
45586     replaceTag : false,
45587     
45588     walk : function(dom)
45589     {
45590         Roo.each( Array.from(dom.childNodes), function( e ) {
45591             switch(true) {
45592                 
45593                 case e.nodeType == 8 && typeof(this.replaceComment) != 'undefined': // comment
45594                     this.replaceComment(e);
45595                     return;
45596                 
45597                 case e.nodeType != 1: //not a node.
45598                     return;
45599                 
45600                 case this.tag === true: // everything
45601                 case typeof(this.tag) == 'object' && this.tag.indexOf(e.tagName) > -1: // array and it matches.
45602                 case typeof(this.tag) == 'string' && this.tag == e.tagName: // array and it matches.
45603                     if (this.replaceTag && false === this.replaceTag(e)) {
45604                         return;
45605                     }
45606                     if (e.hasChildNodes()) {
45607                         this.walk(e);
45608                     }
45609                     return;
45610                 
45611                 default:    // tags .. that do not match.
45612                     if (e.hasChildNodes()) {
45613                         this.walk(e);
45614                     }
45615             }
45616             
45617         }, this);
45618         
45619     }
45620 }; 
45621
45622 /**
45623  * @class Roo.htmleditor.FilterAttributes
45624  * clean attributes and  styles including http:// etc.. in attribute
45625  * @constructor
45626 * Run a new Attribute Filter
45627 * @param {Object} config Configuration options
45628  */
45629 Roo.htmleditor.FilterAttributes = function(cfg)
45630 {
45631     Roo.apply(this, cfg);
45632     this.attrib_black = this.attrib_black || [];
45633     this.attrib_white = this.attrib_white || [];
45634
45635     this.attrib_clean = this.attrib_clean || [];
45636     this.style_white = this.style_white || [];
45637     this.style_black = this.style_black || [];
45638     this.walk(cfg.node);
45639 }
45640
45641 Roo.extend(Roo.htmleditor.FilterAttributes, Roo.htmleditor.Filter,
45642 {
45643     tag: true, // all tags
45644     
45645     attrib_black : false, // array
45646     attrib_clean : false,
45647     attrib_white : false,
45648
45649     style_white : false,
45650     style_black : false,
45651      
45652      
45653     replaceTag : function(node)
45654     {
45655         if (!node.attributes || !node.attributes.length) {
45656             return true;
45657         }
45658         
45659         for (var i = node.attributes.length-1; i > -1 ; i--) {
45660             var a = node.attributes[i];
45661             //console.log(a);
45662             if (this.attrib_white.length && this.attrib_white.indexOf(a.name.toLowerCase()) < 0) {
45663                 node.removeAttribute(a.name);
45664                 continue;
45665             }
45666             
45667             
45668             
45669             if (a.name.toLowerCase().substr(0,2)=='on')  {
45670                 node.removeAttribute(a.name);
45671                 continue;
45672             }
45673             
45674             
45675             if (this.attrib_black.indexOf(a.name.toLowerCase()) > -1) {
45676                 node.removeAttribute(a.name);
45677                 continue;
45678             }
45679             if (this.attrib_clean.indexOf(a.name.toLowerCase()) > -1) {
45680                 this.cleanAttr(node,a.name,a.value); // fixme..
45681                 continue;
45682             }
45683             if (a.name == 'style') {
45684                 this.cleanStyle(node,a.name,a.value);
45685                 continue;
45686             }
45687             /// clean up MS crap..
45688             // tecnically this should be a list of valid class'es..
45689             
45690             
45691             if (a.name == 'class') {
45692                 if (a.value.match(/^Mso/)) {
45693                     node.removeAttribute('class');
45694                 }
45695                 
45696                 if (a.value.match(/^body$/)) {
45697                     node.removeAttribute('class');
45698                 }
45699                 continue;
45700             }
45701             
45702             
45703             // style cleanup!?
45704             // class cleanup?
45705             
45706         }
45707         return true; // clean children
45708     },
45709         
45710     cleanAttr: function(node, n,v)
45711     {
45712         
45713         if (v.match(/^\./) || v.match(/^\//)) {
45714             return;
45715         }
45716         if (v.match(/^(http|https):\/\//)
45717             || v.match(/^mailto:/) 
45718             || v.match(/^ftp:/)
45719             || v.match(/^data:/)
45720             ) {
45721             return;
45722         }
45723         if (v.match(/^#/)) {
45724             return;
45725         }
45726         if (v.match(/^\{/)) { // allow template editing.
45727             return;
45728         }
45729 //            Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
45730         node.removeAttribute(n);
45731         
45732     },
45733     cleanStyle : function(node,  n,v)
45734     {
45735         if (v.match(/expression/)) { //XSS?? should we even bother..
45736             node.removeAttribute(n);
45737             return;
45738         }
45739         
45740         var parts = v.split(/;/);
45741         var clean = [];
45742         
45743         Roo.each(parts, function(p) {
45744             p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
45745             if (!p.length) {
45746                 return true;
45747             }
45748             var l = p.split(':').shift().replace(/\s+/g,'');
45749             l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
45750             
45751             if ( this.style_black.length && (this.style_black.indexOf(l) > -1 || this.style_black.indexOf(l.toLowerCase()) > -1)) {
45752                 return true;
45753             }
45754             //Roo.log()
45755             // only allow 'c whitelisted system attributes'
45756             if ( this.style_white.length &&  style_white.indexOf(l) < 0 && style_white.indexOf(l.toLowerCase()) < 0 ) {
45757                 return true;
45758             }
45759             
45760             
45761             clean.push(p);
45762             return true;
45763         },this);
45764         if (clean.length) { 
45765             node.setAttribute(n, clean.join(';'));
45766         } else {
45767             node.removeAttribute(n);
45768         }
45769         
45770     }
45771         
45772         
45773         
45774     
45775 });/**
45776  * @class Roo.htmleditor.FilterBlack
45777  * remove blacklisted elements.
45778  * @constructor
45779  * Run a new Blacklisted Filter
45780  * @param {Object} config Configuration options
45781  */
45782
45783 Roo.htmleditor.FilterBlack = function(cfg)
45784 {
45785     Roo.apply(this, cfg);
45786     this.walk(cfg.node);
45787 }
45788
45789 Roo.extend(Roo.htmleditor.FilterBlack, Roo.htmleditor.Filter,
45790 {
45791     tag : true, // all elements.
45792    
45793     replace : function(n)
45794     {
45795         n.parentNode.removeChild(n);
45796     }
45797 });
45798 /**
45799  * @class Roo.htmleditor.FilterComment
45800  * remove comments.
45801  * @constructor
45802 * Run a new Comments Filter
45803 * @param {Object} config Configuration options
45804  */
45805 Roo.htmleditor.FilterComment = function(cfg)
45806 {
45807     this.walk(cfg.node);
45808 }
45809
45810 Roo.extend(Roo.htmleditor.FilterComment, Roo.htmleditor.Filter,
45811 {
45812   
45813     replaceComment : function(n)
45814     {
45815         n.parentNode.removeChild(n);
45816     }
45817 });/**
45818  * @class Roo.htmleditor.FilterKeepChildren
45819  * remove tags but keep children
45820  * @constructor
45821  * Run a new Keep Children Filter
45822  * @param {Object} config Configuration options
45823  */
45824
45825 Roo.htmleditor.FilterKeepChildren = function(cfg)
45826 {
45827     Roo.apply(this, cfg);
45828     if (this.tag === false) {
45829         return; // dont walk.. (you can use this to use this just to do a child removal on a single tag )
45830     }
45831     this.walk(cfg.node);
45832 }
45833
45834 Roo.extend(Roo.htmleditor.FilterKeepChildren, Roo.htmleditor.FilterBlack,
45835 {
45836     
45837   
45838     replaceTag : function(node)
45839     {
45840         // walk children...
45841         //Roo.log(node);
45842         var ar = Array.from(node.childNodes);
45843         //remove first..
45844         for (var i = 0; i < ar.length; i++) {
45845             if (ar[i].nodeType == 1) {
45846                 if (
45847                     (typeof(this.tag) == 'object' && this.tag.indexOf(ar[i].tagName) > -1)
45848                     || // array and it matches
45849                     (typeof(this.tag) == 'string' && this.tag == ar[i].tagName)
45850                 ) {
45851                     this.replaceTag(ar[i]); // child is blacklisted as well...
45852                     continue;
45853                 }
45854             }
45855         }  
45856         ar = Array.from(node.childNodes);
45857         for (var i = 0; i < ar.length; i++) {
45858          
45859             node.removeChild(ar[i]);
45860             // what if we need to walk these???
45861             node.parentNode.insertBefore(ar[i], node);
45862             if (this.tag !== false) {
45863                 this.walk(ar[i]);
45864                 
45865             }
45866         }
45867         node.parentNode.removeChild(node);
45868         return false; // don't walk children
45869         
45870         
45871     }
45872 });/**
45873  * @class Roo.htmleditor.FilterParagraph
45874  * paragraphs cause a nightmare for shared content - this filter is designed to be called ? at various points when editing
45875  * like on 'push' to remove the <p> tags and replace them with line breaks.
45876  * @constructor
45877  * Run a new Paragraph Filter
45878  * @param {Object} config Configuration options
45879  */
45880
45881 Roo.htmleditor.FilterParagraph = function(cfg)
45882 {
45883     // no need to apply config.
45884     this.walk(cfg.node);
45885 }
45886
45887 Roo.extend(Roo.htmleditor.FilterParagraph, Roo.htmleditor.Filter,
45888 {
45889     
45890      
45891     tag : 'P',
45892     
45893      
45894     replaceTag : function(node)
45895     {
45896         
45897         if (node.childNodes.length == 1 &&
45898             node.childNodes[0].nodeType == 3 &&
45899             node.childNodes[0].textContent.trim().length < 1
45900             ) {
45901             // remove and replace with '<BR>';
45902             node.parentNode.replaceChild(node.ownerDocument.createElement('BR'),node);
45903             return false; // no need to walk..
45904         }
45905         var ar = Array.from(node.childNodes);
45906         for (var i = 0; i < ar.length; i++) {
45907             node.removeChild(ar[i]);
45908             // what if we need to walk these???
45909             node.parentNode.insertBefore(ar[i], node);
45910         }
45911         // now what about this?
45912         // <p> &nbsp; </p>
45913         
45914         // double BR.
45915         node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
45916         node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
45917         node.parentNode.removeChild(node);
45918         
45919         return false;
45920
45921     }
45922     
45923 });/**
45924  * @class Roo.htmleditor.FilterSpan
45925  * filter span's with no attributes out..
45926  * @constructor
45927  * Run a new Span Filter
45928  * @param {Object} config Configuration options
45929  */
45930
45931 Roo.htmleditor.FilterSpan = function(cfg)
45932 {
45933     // no need to apply config.
45934     this.walk(cfg.node);
45935 }
45936
45937 Roo.extend(Roo.htmleditor.FilterSpan, Roo.htmleditor.FilterKeepChildren,
45938 {
45939      
45940     tag : 'SPAN',
45941      
45942  
45943     replaceTag : function(node)
45944     {
45945         if (node.attributes && node.attributes.length > 0) {
45946             return true; // walk if there are any.
45947         }
45948         Roo.htmleditor.FilterKeepChildren.prototype.replaceTag.call(this, node);
45949         return false;
45950      
45951     }
45952     
45953 });/**
45954  * @class Roo.htmleditor.FilterTableWidth
45955   try and remove table width data - as that frequently messes up other stuff.
45956  * 
45957  *      was cleanTableWidths.
45958  *
45959  * Quite often pasting from word etc.. results in tables with column and widths.
45960  * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
45961  *
45962  * @constructor
45963  * Run a new Table Filter
45964  * @param {Object} config Configuration options
45965  */
45966
45967 Roo.htmleditor.FilterTableWidth = function(cfg)
45968 {
45969     // no need to apply config.
45970     this.tag = ['TABLE', 'TD', 'TR', 'TH', 'THEAD', 'TBODY' ];
45971     this.walk(cfg.node);
45972 }
45973
45974 Roo.extend(Roo.htmleditor.FilterTableWidth, Roo.htmleditor.Filter,
45975 {
45976      
45977      
45978     
45979     replaceTag: function(node) {
45980         
45981         
45982       
45983         if (node.hasAttribute('width')) {
45984             node.removeAttribute('width');
45985         }
45986         
45987          
45988         if (node.hasAttribute("style")) {
45989             // pretty basic...
45990             
45991             var styles = node.getAttribute("style").split(";");
45992             var nstyle = [];
45993             Roo.each(styles, function(s) {
45994                 if (!s.match(/:/)) {
45995                     return;
45996                 }
45997                 var kv = s.split(":");
45998                 if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
45999                     return;
46000                 }
46001                 // what ever is left... we allow.
46002                 nstyle.push(s);
46003             });
46004             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
46005             if (!nstyle.length) {
46006                 node.removeAttribute('style');
46007             }
46008         }
46009         
46010         return true; // continue doing children..
46011     }
46012 });/**
46013  * @class Roo.htmleditor.FilterWord
46014  * try and clean up all the mess that Word generates.
46015  * 
46016  * This is the 'nice version' - see 'Heavy' that white lists a very short list of elements, and multi-filters 
46017  
46018  * @constructor
46019  * Run a new Span Filter
46020  * @param {Object} config Configuration options
46021  */
46022
46023 Roo.htmleditor.FilterWord = function(cfg)
46024 {
46025     // no need to apply config.
46026     this.walk(cfg.node);
46027 }
46028
46029 Roo.extend(Roo.htmleditor.FilterWord, Roo.htmleditor.Filter,
46030 {
46031     tag: true,
46032      
46033     
46034     /**
46035      * Clean up MS wordisms...
46036      */
46037     replaceTag : function(node)
46038     {
46039          
46040         // no idea what this does - span with text, replaceds with just text.
46041         if(
46042                 node.nodeName == 'SPAN' &&
46043                 !node.hasAttributes() &&
46044                 node.childNodes.length == 1 &&
46045                 node.firstChild.nodeName == "#text"  
46046         ) {
46047             var textNode = node.firstChild;
46048             node.removeChild(textNode);
46049             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
46050                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" "), node);
46051             }
46052             node.parentNode.insertBefore(textNode, node);
46053             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
46054                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" ") , node);
46055             }
46056             
46057             node.parentNode.removeChild(node);
46058             return false; // dont do chidren - we have remove our node - so no need to do chdhilren?
46059         }
46060         
46061    
46062         
46063         if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
46064             node.parentNode.removeChild(node);
46065             return false; // dont do chidlren
46066         }
46067         //Roo.log(node.tagName);
46068         // remove - but keep children..
46069         if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|v:|font)/)) {
46070             //Roo.log('-- removed');
46071             while (node.childNodes.length) {
46072                 var cn = node.childNodes[0];
46073                 node.removeChild(cn);
46074                 node.parentNode.insertBefore(cn, node);
46075                 // move node to parent - and clean it..
46076                 this.replaceTag(cn);
46077             }
46078             node.parentNode.removeChild(node);
46079             /// no need to iterate chidlren = it's got none..
46080             //this.iterateChildren(node, this.cleanWord);
46081             return false; // no need to iterate children.
46082         }
46083         // clean styles
46084         if (node.className.length) {
46085             
46086             var cn = node.className.split(/\W+/);
46087             var cna = [];
46088             Roo.each(cn, function(cls) {
46089                 if (cls.match(/Mso[a-zA-Z]+/)) {
46090                     return;
46091                 }
46092                 cna.push(cls);
46093             });
46094             node.className = cna.length ? cna.join(' ') : '';
46095             if (!cna.length) {
46096                 node.removeAttribute("class");
46097             }
46098         }
46099         
46100         if (node.hasAttribute("lang")) {
46101             node.removeAttribute("lang");
46102         }
46103         
46104         if (node.hasAttribute("style")) {
46105             
46106             var styles = node.getAttribute("style").split(";");
46107             var nstyle = [];
46108             Roo.each(styles, function(s) {
46109                 if (!s.match(/:/)) {
46110                     return;
46111                 }
46112                 var kv = s.split(":");
46113                 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
46114                     return;
46115                 }
46116                 // what ever is left... we allow.
46117                 nstyle.push(s);
46118             });
46119             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
46120             if (!nstyle.length) {
46121                 node.removeAttribute('style');
46122             }
46123         }
46124         return true; // do children
46125         
46126         
46127         
46128     }
46129 });
46130 /**
46131  * @class Roo.htmleditor.FilterStyleToTag
46132  * part of the word stuff... - certain 'styles' should be converted to tags.
46133  * eg.
46134  *   font-weight: bold -> bold
46135  *   ?? super / subscrit etc..
46136  * 
46137  * @constructor
46138 * Run a new style to tag filter.
46139 * @param {Object} config Configuration options
46140  */
46141 Roo.htmleditor.FilterStyleToTag = function(cfg)
46142 {
46143     
46144     this.tags = {
46145         B  : [ 'fontWeight' , 'bold'],
46146         I :  [ 'fontStyle' , 'italic'],
46147         //pre :  [ 'font-style' , 'italic'],
46148         // h1.. h6 ?? font-size?
46149         SUP : [ 'verticalAlign' , 'super' ],
46150         SUB : [ 'verticalAlign' , 'sub' ]
46151         
46152         
46153     };
46154     
46155     Roo.apply(this, cfg);
46156      
46157     
46158     this.walk(cfg.node);
46159     
46160     
46161     
46162 }
46163
46164
46165 Roo.extend(Roo.htmleditor.FilterStyleToTag, Roo.htmleditor.Filter,
46166 {
46167     tag: true, // all tags
46168     
46169     tags : false,
46170     
46171     
46172     replaceTag : function(node)
46173     {
46174         
46175         
46176         if (node.getAttribute("style") === null) {
46177             return true;
46178         }
46179         var inject = [];
46180         for (var k in this.tags) {
46181             if (node.style[this.tags[k][0]] == this.tags[k][1]) {
46182                 inject.push(k);
46183                 node.style.removeProperty(this.tags[k][0]);
46184             }
46185         }
46186         if (!inject.length) {
46187             return true; 
46188         }
46189         var cn = Array.from(node.childNodes);
46190         var nn = node;
46191         Roo.each(inject, function(t) {
46192             var nc = node.ownerDocument.createElement(t);
46193             nn.appendChild(nc);
46194             nn = nc;
46195         });
46196         for(var i = 0;i < cn.length;cn++) {
46197             node.removeChild(cn[i]);
46198             nn.appendChild(cn[i]);
46199         }
46200         return true /// iterate thru
46201     }
46202     
46203 })/**
46204  * @class Roo.htmleditor.FilterLongBr
46205  * BR/BR/BR - keep a maximum of 2...
46206  * @constructor
46207  * Run a new Long BR Filter
46208  * @param {Object} config Configuration options
46209  */
46210
46211 Roo.htmleditor.FilterLongBr = function(cfg)
46212 {
46213     // no need to apply config.
46214     this.walk(cfg.node);
46215 }
46216
46217 Roo.extend(Roo.htmleditor.FilterLongBr, Roo.htmleditor.Filter,
46218 {
46219     
46220      
46221     tag : 'BR',
46222     
46223      
46224     replaceTag : function(node)
46225     {
46226         
46227         var ps = node.nextSibling;
46228         while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
46229             ps = ps.nextSibling;
46230         }
46231         
46232         if (!ps &&  [ 'TD', 'TH', 'LI', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(node.parentNode.tagName) > -1) { 
46233             node.parentNode.removeChild(node); // remove last BR inside one fo these tags
46234             return false;
46235         }
46236         
46237         if (!ps || ps.nodeType != 1) {
46238             return false;
46239         }
46240         
46241         if (!ps || ps.tagName != 'BR') {
46242            
46243             return false;
46244         }
46245         
46246         
46247         
46248         
46249         
46250         if (!node.previousSibling) {
46251             return false;
46252         }
46253         var ps = node.previousSibling;
46254         
46255         while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
46256             ps = ps.previousSibling;
46257         }
46258         if (!ps || ps.nodeType != 1) {
46259             return false;
46260         }
46261         // if header or BR before.. then it's a candidate for removal.. - as we only want '2' of these..
46262         if (!ps || [ 'BR', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(ps.tagName) < 0) {
46263             return false;
46264         }
46265         
46266         node.parentNode.removeChild(node); // remove me...
46267         
46268         return false; // no need to do children
46269
46270     }
46271     
46272 }); 
46273
46274 /**
46275  * @class Roo.htmleditor.FilterBlock
46276  * removes id / data-block and contenteditable that are associated with blocks
46277  * usage should be done on a cloned copy of the dom
46278  * @constructor
46279 * Run a new Attribute Filter { node : xxxx }}
46280 * @param {Object} config Configuration options
46281  */
46282 Roo.htmleditor.FilterBlock = function(cfg)
46283 {
46284     Roo.apply(this, cfg);
46285     var qa = cfg.node.querySelectorAll;
46286     this.removeAttributes('data-block');
46287     this.removeAttributes('contenteditable');
46288     this.removeAttributes('id');
46289     
46290 }
46291
46292 Roo.apply(Roo.htmleditor.FilterBlock.prototype,
46293 {
46294     node: true, // all tags
46295      
46296      
46297     removeAttributes : function(attr)
46298     {
46299         var ar = this.node.querySelectorAll('*[' + attr + ']');
46300         for (var i =0;i<ar.length;i++) {
46301             ar[i].removeAttribute(attr);
46302         }
46303     }
46304         
46305         
46306         
46307     
46308 });
46309 /**
46310  * @class Roo.htmleditor.Tidy
46311  * Tidy HTML 
46312  * @cfg {Roo.HtmlEditorCore} core the editor.
46313  * @constructor
46314  * Create a new Filter.
46315  * @param {Object} config Configuration options
46316  */
46317
46318
46319 Roo.htmleditor.Tidy = function(cfg) {
46320     Roo.apply(this, cfg);
46321     
46322     this.core.doc.body.innerHTML = this.tidy(this.core.doc.body, '');
46323      
46324 }
46325
46326 Roo.htmleditor.Tidy.toString = function(node)
46327 {
46328     return Roo.htmleditor.Tidy.prototype.tidy(node, '');
46329 }
46330
46331 Roo.htmleditor.Tidy.prototype = {
46332     
46333     
46334     wrap : function(s) {
46335         return s.replace(/\n/g, " ").replace(/(?![^\n]{1,80}$)([^\n]{1,80})\s/g, '$1\n');
46336     },
46337
46338     
46339     tidy : function(node, indent) {
46340      
46341         if  (node.nodeType == 3) {
46342             // text.
46343             
46344             
46345             return indent === false ? node.nodeValue : this.wrap(node.nodeValue.trim()).split("\n").join("\n" + indent);
46346                 
46347             
46348         }
46349         
46350         if  (node.nodeType != 1) {
46351             return '';
46352         }
46353         
46354         
46355         
46356         if (node.tagName == 'BODY') {
46357             
46358             return this.cn(node, '');
46359         }
46360              
46361              // Prints the node tagName, such as <A>, <IMG>, etc
46362         var ret = "<" + node.tagName +  this.attr(node) ;
46363         
46364         // elements with no children..
46365         if (['IMG', 'BR', 'HR', 'INPUT'].indexOf(node.tagName) > -1) {
46366                 return ret + '/>';
46367         }
46368         ret += '>';
46369         
46370         
46371         var cindent = indent === false ? '' : (indent + '  ');
46372         // tags where we will not pad the children.. (inline text tags etc..)
46373         if (['PRE', 'TEXTAREA', 'TD', 'A', 'SPAN', 'B', 'I', 'S'].indexOf(node.tagName) > -1) { // or code?
46374             cindent = false;
46375             
46376             
46377         }
46378         
46379         var cn = this.cn(node, cindent );
46380         
46381         return ret + cn  + '</' + node.tagName + '>';
46382         
46383     },
46384     cn: function(node, indent)
46385     {
46386         var ret = [];
46387         
46388         var ar = Array.from(node.childNodes);
46389         for (var i = 0 ; i < ar.length ; i++) {
46390             
46391             
46392             
46393             if (indent !== false   // indent==false preservies everything
46394                 && i > 0
46395                 && ar[i].nodeType == 3 
46396                 && ar[i].nodeValue.length > 0
46397                 && ar[i].nodeValue.match(/^\s+/)
46398             ) {
46399                 if (ret.length && ret[ret.length-1] == "\n" + indent) {
46400                     ret.pop(); // remove line break from last?
46401                 }
46402                 
46403                 ret.push(" "); // add a space if i'm a text item with a space at the front, as tidy will strip spaces.
46404             }
46405             if (indent !== false
46406                 && ar[i].nodeType == 1 // element - and indent is not set... 
46407             ) {
46408                 ret.push("\n" + indent); 
46409             }
46410             
46411             ret.push(this.tidy(ar[i], indent));
46412             // text + trailing indent 
46413             if (indent !== false
46414                 && ar[i].nodeType == 3
46415                 && ar[i].nodeValue.length > 0
46416                 && ar[i].nodeValue.match(/\s+$/)
46417             ){
46418                 ret.push("\n" + indent); 
46419             }
46420             
46421             
46422             
46423             
46424         }
46425         // what if all text?
46426         
46427         
46428         return ret.join('');
46429     },
46430     
46431          
46432         
46433     attr : function(node)
46434     {
46435         var attr = [];
46436         for(i = 0; i < node.attributes.length;i++) {
46437             
46438             // skip empty values?
46439             if (!node.attributes.item(i).value.length) {
46440                 continue;
46441             }
46442             attr.push(  node.attributes.item(i).name + '="' +
46443                     Roo.util.Format.htmlEncode(node.attributes.item(i).value) + '"'
46444             );
46445         }
46446         return attr.length ? (' ' + attr.join(' ') ) : '';
46447         
46448     }
46449     
46450     
46451     
46452 }
46453 /**
46454  * @class Roo.htmleditor.KeyEnter
46455  * Handle Enter press..
46456  * @cfg {Roo.HtmlEditorCore} core the editor.
46457  * @constructor
46458  * Create a new Filter.
46459  * @param {Object} config Configuration options
46460  */
46461
46462
46463
46464
46465
46466 Roo.htmleditor.KeyEnter = function(cfg) {
46467     Roo.apply(this, cfg);
46468     // this does not actually call walk as it's really just a abstract class
46469  
46470     Roo.get(this.core.doc.body).on('keypress', this.keypress, this);
46471 }
46472
46473 //Roo.htmleditor.KeyEnter.i = 0;
46474
46475
46476 Roo.htmleditor.KeyEnter.prototype = {
46477     
46478     core : false,
46479     
46480     keypress : function(e)
46481     {
46482         if (e.charCode != 13 && e.charCode != 10) {
46483             Roo.log([e.charCode,e]);
46484             return true;
46485         }
46486         e.preventDefault();
46487         // https://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome
46488         var doc = this.core.doc;
46489           //add a new line
46490        
46491     
46492         var sel = this.core.getSelection();
46493         var range = sel.getRangeAt(0);
46494         var n = range.commonAncestorContainer;
46495         var pc = range.closest([ 'ol', 'ul']);
46496         var pli = range.closest('li');
46497         if (!pc || e.ctrlKey) {
46498             sel.insertNode('br', 'after'); 
46499          
46500             this.core.undoManager.addEvent();
46501             this.core.fireEditorEvent(e);
46502             return false;
46503         }
46504         
46505         // deal with <li> insetion
46506         if (pli.innerText.trim() == '' &&
46507             pli.previousSibling &&
46508             pli.previousSibling.nodeName == 'LI' &&
46509             pli.previousSibling.innerText.trim() ==  '') {
46510             pli.parentNode.removeChild(pli.previousSibling);
46511             sel.cursorAfter(pc);
46512             this.core.undoManager.addEvent();
46513             this.core.fireEditorEvent(e);
46514             return false;
46515         }
46516     
46517         var li = doc.createElement('LI');
46518         li.innerHTML = '&nbsp;';
46519         if (!pli || !pli.firstSibling) {
46520             pc.appendChild(li);
46521         } else {
46522             pli.parentNode.insertBefore(li, pli.firstSibling);
46523         }
46524         sel.cursorText (li.firstChild);
46525       
46526         this.core.undoManager.addEvent();
46527         this.core.fireEditorEvent(e);
46528
46529         return false;
46530         
46531     
46532         
46533         
46534          
46535     }
46536 };
46537      
46538 /**
46539  * @class Roo.htmleditor.Block
46540  * Base class for html editor blocks - do not use it directly .. extend it..
46541  * @cfg {DomElement} node The node to apply stuff to.
46542  * @cfg {String} friendly_name the name that appears in the context bar about this block
46543  * @cfg {Object} Context menu - see Roo.form.HtmlEditor.ToolbarContext
46544  
46545  * @constructor
46546  * Create a new Filter.
46547  * @param {Object} config Configuration options
46548  */
46549
46550 Roo.htmleditor.Block  = function(cfg)
46551 {
46552     // do nothing .. should not be called really.
46553 }
46554 /**
46555  * factory method to get the block from an element (using cache if necessary)
46556  * @static
46557  * @param {HtmlElement} the dom element
46558  */
46559 Roo.htmleditor.Block.factory = function(node)
46560 {
46561     var cc = Roo.htmleditor.Block.cache;
46562     var id = Roo.get(node).id;
46563     if (typeof(cc[id]) != 'undefined' && (!cc[id].node || cc[id].node.closest('body'))) {
46564         Roo.htmleditor.Block.cache[id].readElement(node);
46565         return Roo.htmleditor.Block.cache[id];
46566     }
46567     var db  = node.getAttribute('data-block');
46568     if (!db) {
46569         db = node.nodeName.toLowerCase().toUpperCaseFirst();
46570     }
46571     var cls = Roo.htmleditor['Block' + db];
46572     if (typeof(cls) == 'undefined') {
46573         //Roo.log(node.getAttribute('data-block'));
46574         Roo.log("OOps missing block : " + 'Block' + db);
46575         return false;
46576     }
46577     Roo.htmleditor.Block.cache[id] = new cls({ node: node });
46578     return Roo.htmleditor.Block.cache[id];  /// should trigger update element
46579 };
46580
46581 /**
46582  * initalize all Elements from content that are 'blockable'
46583  * @static
46584  * @param the body element
46585  */
46586 Roo.htmleditor.Block.initAll = function(body, type)
46587 {
46588     if (typeof(type) == 'undefined') {
46589         var ia = Roo.htmleditor.Block.initAll;
46590         ia(body,'table');
46591         ia(body,'td');
46592         ia(body,'figure');
46593         return;
46594     }
46595     Roo.each(Roo.get(body).query(type), function(e) {
46596         Roo.htmleditor.Block.factory(e);    
46597     },this);
46598 };
46599 // question goes here... do we need to clear out this cache sometimes?
46600 // or show we make it relivant to the htmleditor.
46601 Roo.htmleditor.Block.cache = {};
46602
46603 Roo.htmleditor.Block.prototype = {
46604     
46605     node : false,
46606     
46607      // used by context menu
46608     friendly_name : 'Based Block',
46609     
46610     // text for button to delete this element
46611     deleteTitle : false,
46612     
46613     context : false,
46614     /**
46615      * Update a node with values from this object
46616      * @param {DomElement} node
46617      */
46618     updateElement : function(node)
46619     {
46620         Roo.DomHelper.update(node === undefined ? this.node : node, this.toObject());
46621     },
46622      /**
46623      * convert to plain HTML for calling insertAtCursor..
46624      */
46625     toHTML : function()
46626     {
46627         return Roo.DomHelper.markup(this.toObject());
46628     },
46629     /**
46630      * used by readEleemnt to extract data from a node
46631      * may need improving as it's pretty basic
46632      
46633      * @param {DomElement} node
46634      * @param {String} tag - tag to find, eg. IMG ?? might be better to use DomQuery ?
46635      * @param {String} attribute (use html - for contents, or style for using next param as style)
46636      * @param {String} style the style property - eg. text-align
46637      */
46638     getVal : function(node, tag, attr, style)
46639     {
46640         var n = node;
46641         if (tag !== true && n.tagName != tag.toUpperCase()) {
46642             // in theory we could do figure[3] << 3rd figure? or some more complex search..?
46643             // but kiss for now.
46644             n = node.getElementsByTagName(tag).item(0);
46645         }
46646         if (!n) {
46647             return '';
46648         }
46649         if (attr == 'html') {
46650             return n.innerHTML;
46651         }
46652         if (attr == 'style') {
46653             return n.style[style]; 
46654         }
46655         
46656         return n.hasAttribute(attr) ? n.getAttribute(attr) : '';
46657             
46658     },
46659     /**
46660      * create a DomHelper friendly object - for use with 
46661      * Roo.DomHelper.markup / overwrite / etc..
46662      * (override this)
46663      */
46664     toObject : function()
46665     {
46666         return {};
46667     },
46668       /**
46669      * Read a node that has a 'data-block' property - and extract the values from it.
46670      * @param {DomElement} node - the node
46671      */
46672     readElement : function(node)
46673     {
46674         
46675     } 
46676     
46677     
46678 };
46679
46680  
46681
46682 /**
46683  * @class Roo.htmleditor.BlockFigure
46684  * Block that has an image and a figcaption
46685  * @cfg {String} image_src the url for the image
46686  * @cfg {String} align (left|right) alignment for the block default left
46687  * @cfg {String} caption the text to appear below  (and in the alt tag)
46688  * @cfg {String} caption_display (block|none) display or not the caption
46689  * @cfg {String|number} image_width the width of the image number or %?
46690  * @cfg {String|number} image_height the height of the image number or %?
46691  * 
46692  * @constructor
46693  * Create a new Filter.
46694  * @param {Object} config Configuration options
46695  */
46696
46697 Roo.htmleditor.BlockFigure = function(cfg)
46698 {
46699     if (cfg.node) {
46700         this.readElement(cfg.node);
46701         this.updateElement(cfg.node);
46702     }
46703     Roo.apply(this, cfg);
46704 }
46705 Roo.extend(Roo.htmleditor.BlockFigure, Roo.htmleditor.Block, {
46706  
46707     
46708     // setable values.
46709     image_src: '',
46710     align: 'center',
46711     caption : '',
46712     caption_display : 'block',
46713     width : '100%',
46714     
46715     // margin: '2%', not used
46716     
46717     text_align: 'left', //   (left|right) alignment for the text caption default left. - not used at present
46718
46719     
46720     // used by context menu
46721     friendly_name : 'Image with caption',
46722     deleteTitle : "Delete Image and Caption",
46723     
46724     contextMenu : function(toolbar)
46725     {
46726         
46727         var block = function() {
46728             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
46729         };
46730         
46731         
46732         var rooui =  typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
46733         
46734         var syncValue = toolbar.editorcore.syncValue;
46735         
46736         var fields = {};
46737         
46738         return [
46739              {
46740                 xtype : 'TextItem',
46741                 text : "Source: ",
46742                 xns : rooui.Toolbar  //Boostrap?
46743             },
46744             {
46745                 xtype : 'TextField',
46746                 allowBlank : false,
46747                 width : 150,
46748                 name : 'image_src',
46749                 listeners : {
46750                     keyup : function (combo, e)
46751                     { 
46752                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
46753                         var b = block();
46754                         b.image_src = this.getValue();
46755                         b.updateElement();
46756                         syncValue();
46757                         toolbar.editorcore.onEditorEvent();
46758                     }
46759                 },
46760                 xns : rooui.form
46761                 
46762             },
46763             {
46764                 xtype : 'TextItem',
46765                 text : "Width: ",
46766                 xns : rooui.Toolbar  //Boostrap?
46767             },
46768             {
46769                 xtype : 'ComboBox',
46770                 allowBlank : false,
46771                 displayField : 'val',
46772                 editable : true,
46773                 listWidth : 100,
46774                 triggerAction : 'all',
46775                 typeAhead : true,
46776                 valueField : 'val',
46777                 width : 70,
46778                 name : 'width',
46779                 listeners : {
46780                     select : function (combo, r, index)
46781                     {
46782                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
46783                         var b = block();
46784                         b.width = r.get('val');
46785                         b.updateElement();
46786                         syncValue();
46787                         toolbar.editorcore.onEditorEvent();
46788                     }
46789                 },
46790                 xns : rooui.form,
46791                 store : {
46792                     xtype : 'SimpleStore',
46793                     data : [
46794                         ['auto'],
46795                         ['50%'],
46796                         ['100%']
46797                     ],
46798                     fields : [ 'val'],
46799                     xns : Roo.data
46800                 }
46801             },
46802             {
46803                 xtype : 'TextItem',
46804                 text : "Align: ",
46805                 xns : rooui.Toolbar  //Boostrap?
46806             },
46807             {
46808                 xtype : 'ComboBox',
46809                 allowBlank : false,
46810                 displayField : 'val',
46811                 editable : true,
46812                 listWidth : 100,
46813                 triggerAction : 'all',
46814                 typeAhead : true,
46815                 valueField : 'val',
46816                 width : 70,
46817                 name : 'align',
46818                 listeners : {
46819                     select : function (combo, r, index)
46820                     {
46821                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
46822                         var b = block();
46823                         b.align = r.get('val');
46824                         b.updateElement();
46825                         syncValue();
46826                         toolbar.editorcore.onEditorEvent();
46827                     }
46828                 },
46829                 xns : rooui.form,
46830                 store : {
46831                     xtype : 'SimpleStore',
46832                     data : [
46833                         ['left'],
46834                         ['right'],
46835                         ['center']
46836                     ],
46837                     fields : [ 'val'],
46838                     xns : Roo.data
46839                 }
46840             },
46841             
46842             
46843             {
46844                 xtype : 'Button',
46845                 text: 'Hide Caption',
46846                 name : 'caption_display',
46847                 pressed : false,
46848                 enableToggle : true,
46849                 setValue : function(v) {
46850                     this.toggle(v == 'block' ? false : true);
46851                 },
46852                 listeners : {
46853                     toggle: function (btn, state)
46854                     {
46855                         var b  = block();
46856                         b.caption_display = b.caption_display == 'block' ? 'none' : 'block';
46857                         this.setText(b.caption_display == 'block' ? "Hide Caption" : "Show Caption");
46858                         b.updateElement();
46859                         syncValue();
46860                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
46861                         toolbar.editorcore.onEditorEvent();
46862                     }
46863                 },
46864                 xns : rooui.Toolbar
46865             }
46866         ];
46867         
46868     },
46869     /**
46870      * create a DomHelper friendly object - for use with
46871      * Roo.DomHelper.markup / overwrite / etc..
46872      */
46873     toObject : function()
46874     {
46875         var d = document.createElement('div');
46876         d.innerHTML = this.caption;
46877         
46878         var m = this.width == '50%' && this.align == 'center' ? '0 auto' : 0; 
46879         
46880         var img =   {
46881             tag : 'img',
46882             src : this.image_src,
46883             alt : d.innerText.replace(/\n/g, " "), // removeHTML..
46884             style: {
46885                 width : 'auto',
46886                 'max-width': '100%',
46887                 margin : '0px' 
46888                 
46889                 
46890             }
46891         };
46892         
46893         '<div class="{0}" width="420" height="315" src="{1}" frameborder="0" allowfullscreen>' +
46894                     '<a href="{2}">' + 
46895                         '<img class="{0}-thumbnail" src="{3}/Images/{4}/{5}#image-{4}" />' + 
46896                     '</a>' + 
46897                 '</div>',
46898         
46899                 
46900         if (this.href) {
46901             img = {
46902                 tag : 'a',
46903                 href: this.href,
46904                 cn : [
46905                     img
46906                 ]
46907             };
46908         }
46909         
46910         return  {
46911             tag: 'figure',
46912             'data-block' : 'Figure',
46913             contenteditable : 'false',
46914             style : {
46915                 display: 'block',
46916                 float :  this.align ,
46917                 'max-width':  this.width,
46918                 width : 'auto',
46919                 margin:  m,
46920                 padding: '10px'
46921                 
46922             },
46923             frameborder : 0,
46924             allowfullscreen : true,
46925             src : this.video_src,
46926             cls : this.cls,
46927             align : this.align,
46928             cn : [
46929                 img,
46930               
46931                 {
46932                     tag: 'figcaption',
46933                     contenteditable : true,
46934                     style : {
46935                         'text-align': 'left',
46936                         'margin-top' : '16px',
46937                         'font-size' : '16px',
46938                         'line-height' : '24px',
46939                         'font-style': 'italic',
46940                         display : this.caption_display
46941                     },
46942                     html : this.caption
46943                     
46944                 }
46945             ]
46946         };
46947          
46948     },
46949     
46950     readElement : function(node)
46951     {
46952         // this should not really come from the link...
46953         this.video_src = this.getVal(node, false, 'src');
46954         this.cls = this.getVal(node, false, 'class');
46955         this.href = this.getVal(node, 'a', 'href');
46956         
46957         this.image_src = this.getVal(node, 'img', 'src');
46958          
46959         this.align = this.getVal(node, 'figure', 'align');
46960         this.caption = this.getVal(node, 'figcaption', 'html');
46961         //this.text_align = this.getVal(node, 'figcaption', 'style','text-align');
46962         this.width = this.getVal(node, 'figure', 'style', 'max-width');
46963         //this.margin = this.getVal(node, 'figure', 'style', 'margin');
46964         
46965     },
46966     removeNode : function()
46967     {
46968         return this.node;
46969     }
46970     
46971   
46972    
46973      
46974     
46975     
46976     
46977     
46978 })
46979
46980  
46981
46982 /**
46983  * @class Roo.htmleditor.BlockTable
46984  * Block that manages a table
46985  * 
46986  * @constructor
46987  * Create a new Filter.
46988  * @param {Object} config Configuration options
46989  */
46990
46991 Roo.htmleditor.BlockTable = function(cfg)
46992 {
46993     if (cfg.node) {
46994         this.readElement(cfg.node);
46995         this.updateElement(cfg.node);
46996     }
46997     Roo.apply(this, cfg);
46998     if (!cfg.node) {
46999         this.rows = [];
47000         for(var r = 0; r < this.no_row; r++) {
47001             this.rows[r] = [];
47002             for(var c = 0; c < this.no_col; c++) {
47003                 this.rows[r][c] = this.emptyCell();
47004             }
47005         }
47006     }
47007     
47008     
47009 }
47010 Roo.extend(Roo.htmleditor.BlockTable, Roo.htmleditor.Block, {
47011  
47012     rows : false,
47013     no_col : 1,
47014     no_row : 1,
47015     
47016     
47017     width: '100%',
47018     
47019     // used by context menu
47020     friendly_name : 'Table',
47021     deleteTitle : 'Delete Table',
47022     // context menu is drawn once..
47023     
47024     contextMenu : function(toolbar)
47025     {
47026         
47027         var block = function() {
47028             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
47029         };
47030         
47031         
47032         var rooui =  typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
47033         
47034         var syncValue = toolbar.editorcore.syncValue;
47035         
47036         var fields = {};
47037         
47038         return [
47039             {
47040                 xtype : 'TextItem',
47041                 text : "Width: ",
47042                 xns : rooui.Toolbar  //Boostrap?
47043             },
47044             {
47045                 xtype : 'ComboBox',
47046                 allowBlank : false,
47047                 displayField : 'val',
47048                 editable : true,
47049                 listWidth : 100,
47050                 triggerAction : 'all',
47051                 typeAhead : true,
47052                 valueField : 'val',
47053                 width : 100,
47054                 name : 'width',
47055                 listeners : {
47056                     select : function (combo, r, index)
47057                     {
47058                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
47059                         var b = block();
47060                         b.width = r.get('val');
47061                         b.updateElement();
47062                         syncValue();
47063                         toolbar.editorcore.onEditorEvent();
47064                     }
47065                 },
47066                 xns : rooui.form,
47067                 store : {
47068                     xtype : 'SimpleStore',
47069                     data : [
47070                         ['100%'],
47071                         ['auto']
47072                     ],
47073                     fields : [ 'val'],
47074                     xns : Roo.data
47075                 }
47076             },
47077             // -------- Cols
47078             
47079             {
47080                 xtype : 'TextItem',
47081                 text : "Columns: ",
47082                 xns : rooui.Toolbar  //Boostrap?
47083             },
47084          
47085             {
47086                 xtype : 'Button',
47087                 text: '-',
47088                 listeners : {
47089                     click : function (_self, e)
47090                     {
47091                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
47092                         block().removeColumn();
47093                         syncValue();
47094                         toolbar.editorcore.onEditorEvent();
47095                     }
47096                 },
47097                 xns : rooui.Toolbar
47098             },
47099             {
47100                 xtype : 'Button',
47101                 text: '+',
47102                 listeners : {
47103                     click : function (_self, e)
47104                     {
47105                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
47106                         block().addColumn();
47107                         syncValue();
47108                         toolbar.editorcore.onEditorEvent();
47109                     }
47110                 },
47111                 xns : rooui.Toolbar
47112             },
47113             // -------- ROWS
47114             {
47115                 xtype : 'TextItem',
47116                 text : "Rows: ",
47117                 xns : rooui.Toolbar  //Boostrap?
47118             },
47119          
47120             {
47121                 xtype : 'Button',
47122                 text: '-',
47123                 listeners : {
47124                     click : function (_self, e)
47125                     {
47126                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
47127                         block().removeRow();
47128                         syncValue();
47129                         toolbar.editorcore.onEditorEvent();
47130                     }
47131                 },
47132                 xns : rooui.Toolbar
47133             },
47134             {
47135                 xtype : 'Button',
47136                 text: '+',
47137                 listeners : {
47138                     click : function (_self, e)
47139                     {
47140                         block().addRow();
47141                         syncValue();
47142                         toolbar.editorcore.onEditorEvent();
47143                     }
47144                 },
47145                 xns : rooui.Toolbar
47146             },
47147             // -------- ROWS
47148             {
47149                 xtype : 'Button',
47150                 text: 'Reset Column Widths',
47151                 listeners : {
47152                     
47153                     click : function (_self, e)
47154                     {
47155                         block().resetWidths();
47156                         syncValue();
47157                         toolbar.editorcore.onEditorEvent();
47158                     }
47159                 },
47160                 xns : rooui.Toolbar
47161             } 
47162             
47163             
47164             
47165         ];
47166         
47167     },
47168     
47169     
47170   /**
47171      * create a DomHelper friendly object - for use with
47172      * Roo.DomHelper.markup / overwrite / etc..
47173      * ?? should it be called with option to hide all editing features?
47174      */
47175     toObject : function()
47176     {
47177         
47178         var ret = {
47179             tag : 'table',
47180             contenteditable : 'false', // this stops cell selection from picking the table.
47181             'data-block' : 'Table',
47182             style : {
47183                 width:  this.width,
47184                 border : 'solid 1px #000', // ??? hard coded?
47185                 'border-collapse' : 'collapse' 
47186             },
47187             cn : [
47188                 { tag : 'tbody' , cn : [] }
47189             ]
47190         };
47191         
47192         // do we have a head = not really 
47193         var ncols = 0;
47194         Roo.each(this.rows, function( row ) {
47195             var tr = {
47196                 tag: 'tr',
47197                 style : {
47198                     margin: '6px',
47199                     border : 'solid 1px #000',
47200                     textAlign : 'left' 
47201                 },
47202                 cn : [ ]
47203             };
47204             
47205             ret.cn[0].cn.push(tr);
47206             // does the row have any properties? ?? height?
47207             var nc = 0;
47208             Roo.each(row, function( cell ) {
47209                 
47210                 var td = {
47211                     tag : 'td',
47212                     contenteditable :  'true',
47213                     'data-block' : 'Td',
47214                     html : cell.html,
47215                     style : cell.style
47216                 };
47217                 if (cell.colspan > 1) {
47218                     td.colspan = cell.colspan ;
47219                     nc += cell.colspan;
47220                 } else {
47221                     nc++;
47222                 }
47223                 if (cell.rowspan > 1) {
47224                     td.rowspan = cell.rowspan ;
47225                 }
47226                 
47227                 
47228                 // widths ?
47229                 tr.cn.push(td);
47230                     
47231                 
47232             }, this);
47233             ncols = Math.max(nc, ncols);
47234             
47235             
47236         }, this);
47237         // add the header row..
47238         
47239         ncols++;
47240          
47241         
47242         return ret;
47243          
47244     },
47245     
47246     readElement : function(node)
47247     {
47248         node  = node ? node : this.node ;
47249         this.width = this.getVal(node, true, 'style', 'width') || '100%';
47250         
47251         this.rows = [];
47252         this.no_row = 0;
47253         var trs = Array.from(node.rows);
47254         trs.forEach(function(tr) {
47255             var row =  [];
47256             this.rows.push(row);
47257             
47258             this.no_row++;
47259             var no_column = 0;
47260             Array.from(tr.cells).forEach(function(td) {
47261                 
47262                 var add = {
47263                     colspan : td.hasAttribute('colspan') ? td.getAttribute('colspan')*1 : 1,
47264                     rowspan : td.hasAttribute('rowspan') ? td.getAttribute('rowspan')*1 : 1,
47265                     style : td.hasAttribute('style') ? td.getAttribute('style') : '',
47266                     html : td.innerHTML
47267                 };
47268                 no_column += add.colspan;
47269                      
47270                 
47271                 row.push(add);
47272                 
47273                 
47274             },this);
47275             this.no_col = Math.max(this.no_col, no_column);
47276             
47277             
47278         },this);
47279         
47280         
47281     },
47282     normalizeRows: function()
47283     {
47284         var ret= [];
47285         var rid = -1;
47286         this.rows.forEach(function(row) {
47287             rid++;
47288             ret[rid] = [];
47289             row = this.normalizeRow(row);
47290             var cid = 0;
47291             row.forEach(function(c) {
47292                 while (typeof(ret[rid][cid]) != 'undefined') {
47293                     cid++;
47294                 }
47295                 if (typeof(ret[rid]) == 'undefined') {
47296                     ret[rid] = [];
47297                 }
47298                 ret[rid][cid] = c;
47299                 c.row = rid;
47300                 c.col = cid;
47301                 if (c.rowspan < 2) {
47302                     return;
47303                 }
47304                 
47305                 for(var i = 1 ;i < c.rowspan; i++) {
47306                     if (typeof(ret[rid+i]) == 'undefined') {
47307                         ret[rid+i] = [];
47308                     }
47309                     ret[rid+i][cid] = c;
47310                 }
47311             });
47312         }, this);
47313         return ret;
47314     
47315     },
47316     
47317     normalizeRow: function(row)
47318     {
47319         var ret= [];
47320         row.forEach(function(c) {
47321             if (c.colspan < 2) {
47322                 ret.push(c);
47323                 return;
47324             }
47325             for(var i =0 ;i < c.colspan; i++) {
47326                 ret.push(c);
47327             }
47328         });
47329         return ret;
47330     
47331     },
47332     
47333     deleteColumn : function(sel)
47334     {
47335         if (!sel || sel.type != 'col') {
47336             return;
47337         }
47338         if (this.no_col < 2) {
47339             return;
47340         }
47341         
47342         this.rows.forEach(function(row) {
47343             var cols = this.normalizeRow(row);
47344             var col = cols[sel.col];
47345             if (col.colspan > 1) {
47346                 col.colspan --;
47347             } else {
47348                 row.remove(col);
47349             }
47350             
47351         }, this);
47352         this.no_col--;
47353         
47354     },
47355     removeColumn : function()
47356     {
47357         this.deleteColumn({
47358             type: 'col',
47359             col : this.no_col-1
47360         });
47361         this.updateElement();
47362     },
47363     
47364      
47365     addColumn : function()
47366     {
47367         
47368         this.rows.forEach(function(row) {
47369             row.push(this.emptyCell());
47370            
47371         }, this);
47372         this.updateElement();
47373     },
47374     
47375     deleteRow : function(sel)
47376     {
47377         if (!sel || sel.type != 'row') {
47378             return;
47379         }
47380         
47381         if (this.no_row < 2) {
47382             return;
47383         }
47384         
47385         var rows = this.normalizeRows();
47386         
47387         
47388         rows[sel.row].forEach(function(col) {
47389             if (col.rowspan > 1) {
47390                 col.rowspan--;
47391             } else {
47392                 col.remove = 1; // flage it as removed.
47393             }
47394             
47395         }, this);
47396         var newrows = [];
47397         this.rows.forEach(function(row) {
47398             newrow = [];
47399             row.forEach(function(c) {
47400                 if (typeof(c.remove) == 'undefined') {
47401                     newrow.push(c);
47402                 }
47403                 
47404             });
47405             if (newrow.length > 0) {
47406                 newrows.push(row);
47407             }
47408         });
47409         this.rows =  newrows;
47410         
47411         
47412         
47413         this.no_row--;
47414         this.updateElement();
47415         
47416     },
47417     removeRow : function()
47418     {
47419         this.deleteRow({
47420             type: 'row',
47421             row : this.no_row-1
47422         });
47423         
47424     },
47425     
47426      
47427     addRow : function()
47428     {
47429         
47430         var row = [];
47431         for (var i = 0; i < this.no_col; i++ ) {
47432             
47433             row.push(this.emptyCell());
47434            
47435         }
47436         this.rows.push(row);
47437         this.updateElement();
47438         
47439     },
47440      
47441     // the default cell object... at present...
47442     emptyCell : function() {
47443         return (new Roo.htmleditor.BlockTd({})).toObject();
47444         
47445      
47446     },
47447     
47448     removeNode : function()
47449     {
47450         return this.node;
47451     },
47452     
47453     
47454     
47455     resetWidths : function()
47456     {
47457         Array.from(this.node.getElementsByTagName('td')).forEach(function(n) {
47458             var nn = Roo.htmleditor.Block.factory(n);
47459             nn.width = '';
47460             nn.updateElement(n);
47461         });
47462     }
47463     
47464     
47465     
47466     
47467 })
47468
47469 /**
47470  *
47471  * editing a TD?
47472  *
47473  * since selections really work on the table cell, then editing really should work from there
47474  *
47475  * The original plan was to support merging etc... - but that may not be needed yet..
47476  *
47477  * So this simple version will support:
47478  *   add/remove cols
47479  *   adjust the width +/-
47480  *   reset the width...
47481  *   
47482  *
47483  */
47484
47485
47486  
47487
47488 /**
47489  * @class Roo.htmleditor.BlockTable
47490  * Block that manages a table
47491  * 
47492  * @constructor
47493  * Create a new Filter.
47494  * @param {Object} config Configuration options
47495  */
47496
47497 Roo.htmleditor.BlockTd = function(cfg)
47498 {
47499     if (cfg.node) {
47500         this.readElement(cfg.node);
47501         this.updateElement(cfg.node);
47502     }
47503     Roo.apply(this, cfg);
47504      
47505     
47506     
47507 }
47508 Roo.extend(Roo.htmleditor.BlockTd, Roo.htmleditor.Block, {
47509  
47510     node : false,
47511     
47512     width: '',
47513     textAlign : 'left',
47514     valign : 'top',
47515     
47516     colspan : 1,
47517     rowspan : 1,
47518     
47519     
47520     // used by context menu
47521     friendly_name : 'Table Cell',
47522     deleteTitle : false, // use our customer delete
47523     
47524     // context menu is drawn once..
47525     
47526     contextMenu : function(toolbar)
47527     {
47528         
47529         var cell = function() {
47530             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
47531         };
47532         
47533         var table = function() {
47534             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode.closest('table'));
47535         };
47536         
47537         var lr = false;
47538         var saveSel = function()
47539         {
47540             lr = toolbar.editorcore.getSelection().getRangeAt(0);
47541         }
47542         var restoreSel = function()
47543         {
47544             if (lr) {
47545                 (function() {
47546                     toolbar.editorcore.focus();
47547                     var cr = toolbar.editorcore.getSelection();
47548                     cr.removeAllRanges();
47549                     cr.addRange(lr);
47550                     toolbar.editorcore.onEditorEvent();
47551                 }).defer(10, this);
47552                 
47553                 
47554             }
47555         }
47556         
47557         var rooui =  typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
47558         
47559         var syncValue = toolbar.editorcore.syncValue;
47560         
47561         var fields = {};
47562         
47563         return [
47564             {
47565                 xtype : 'Button',
47566                 text : 'Edit Table',
47567                 listeners : {
47568                     click : function() {
47569                         var t = toolbar.tb.selectedNode.closest('table');
47570                         toolbar.editorcore.selectNode(t);
47571                         toolbar.editorcore.onEditorEvent();                        
47572                     }
47573                 }
47574                 
47575             },
47576               
47577            
47578              
47579             {
47580                 xtype : 'TextItem',
47581                 text : "Column Width: ",
47582                  xns : rooui.Toolbar 
47583                
47584             },
47585             {
47586                 xtype : 'Button',
47587                 text: '-',
47588                 listeners : {
47589                     click : function (_self, e)
47590                     {
47591                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
47592                         cell().shrinkColumn();
47593                         syncValue();
47594                          toolbar.editorcore.onEditorEvent();
47595                     }
47596                 },
47597                 xns : rooui.Toolbar
47598             },
47599             {
47600                 xtype : 'Button',
47601                 text: '+',
47602                 listeners : {
47603                     click : function (_self, e)
47604                     {
47605                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
47606                         cell().growColumn();
47607                         syncValue();
47608                         toolbar.editorcore.onEditorEvent();
47609                     }
47610                 },
47611                 xns : rooui.Toolbar
47612             },
47613             
47614             {
47615                 xtype : 'TextItem',
47616                 text : "Vertical Align: ",
47617                 xns : rooui.Toolbar  //Boostrap?
47618             },
47619             {
47620                 xtype : 'ComboBox',
47621                 allowBlank : false,
47622                 displayField : 'val',
47623                 editable : true,
47624                 listWidth : 100,
47625                 triggerAction : 'all',
47626                 typeAhead : true,
47627                 valueField : 'val',
47628                 width : 100,
47629                 name : 'valign',
47630                 listeners : {
47631                     select : function (combo, r, index)
47632                     {
47633                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
47634                         var b = cell();
47635                         b.valign = r.get('val');
47636                         b.updateElement();
47637                         syncValue();
47638                         toolbar.editorcore.onEditorEvent();
47639                     }
47640                 },
47641                 xns : rooui.form,
47642                 store : {
47643                     xtype : 'SimpleStore',
47644                     data : [
47645                         ['top'],
47646                         ['middle'],
47647                         ['bottom'] // there are afew more... 
47648                     ],
47649                     fields : [ 'val'],
47650                     xns : Roo.data
47651                 }
47652             },
47653             
47654             {
47655                 xtype : 'TextItem',
47656                 text : "Merge Cells: ",
47657                  xns : rooui.Toolbar 
47658                
47659             },
47660             
47661             
47662             {
47663                 xtype : 'Button',
47664                 text: 'Right',
47665                 listeners : {
47666                     click : function (_self, e)
47667                     {
47668                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
47669                         cell().mergeRight();
47670                         //block().growColumn();
47671                         syncValue();
47672                         toolbar.editorcore.onEditorEvent();
47673                     }
47674                 },
47675                 xns : rooui.Toolbar
47676             },
47677              
47678             {
47679                 xtype : 'Button',
47680                 text: 'Below',
47681                 listeners : {
47682                     click : function (_self, e)
47683                     {
47684                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
47685                         cell().mergeBelow();
47686                         //block().growColumn();
47687                         syncValue();
47688                         toolbar.editorcore.onEditorEvent();
47689                     }
47690                 },
47691                 xns : rooui.Toolbar
47692             },
47693             {
47694                 xtype : 'TextItem',
47695                 text : "| ",
47696                  xns : rooui.Toolbar 
47697                
47698             },
47699             
47700             {
47701                 xtype : 'Button',
47702                 text: 'Split',
47703                 listeners : {
47704                     click : function (_self, e)
47705                     {
47706                         //toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
47707                         cell().split();
47708                         syncValue();
47709                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
47710                         toolbar.editorcore.onEditorEvent();
47711                                              
47712                     }
47713                 },
47714                 xns : rooui.Toolbar
47715             },
47716             {
47717                 xtype : 'Fill',
47718                 xns : rooui.Toolbar 
47719                
47720             },
47721         
47722           
47723             {
47724                 xtype : 'Button',
47725                 text: 'Delete',
47726                  
47727                 xns : rooui.Toolbar,
47728                 menu : {
47729                     xtype : 'Menu',
47730                     xns : rooui.menu,
47731                     items : [
47732                         {
47733                             xtype : 'Item',
47734                             html: 'Column',
47735                             listeners : {
47736                                 click : function (_self, e)
47737                                 {
47738                                     var t = table();
47739                                     
47740                                     cell().deleteColumn();
47741                                     syncValue();
47742                                     toolbar.editorcore.selectNode(t.node);
47743                                     toolbar.editorcore.onEditorEvent();   
47744                                 }
47745                             },
47746                             xns : rooui.menu
47747                         },
47748                         {
47749                             xtype : 'Item',
47750                             html: 'Row',
47751                             listeners : {
47752                                 click : function (_self, e)
47753                                 {
47754                                     var t = table();
47755                                     cell().deleteRow();
47756                                     syncValue();
47757                                     
47758                                     toolbar.editorcore.selectNode(t.node);
47759                                     toolbar.editorcore.onEditorEvent();   
47760                                                          
47761                                 }
47762                             },
47763                             xns : rooui.menu
47764                         },
47765                        {
47766                             xtype : 'Separator',
47767                             xns : rooui.menu
47768                         },
47769                         {
47770                             xtype : 'Item',
47771                             html: 'Table',
47772                             listeners : {
47773                                 click : function (_self, e)
47774                                 {
47775                                     var t = table();
47776                                     var nn = t.node.nextSibling || t.node.previousSibling;
47777                                     t.node.parentNode.removeChild(t.node);
47778                                     if (nn) { 
47779                                         toolbar.editorcore.selectNode(nn, true);
47780                                     }
47781                                     toolbar.editorcore.onEditorEvent();   
47782                                                          
47783                                 }
47784                             },
47785                             xns : rooui.menu
47786                         }
47787                     ]
47788                 }
47789             }
47790             
47791             // align... << fixme
47792             
47793         ];
47794         
47795     },
47796     
47797     
47798   /**
47799      * create a DomHelper friendly object - for use with
47800      * Roo.DomHelper.markup / overwrite / etc..
47801      * ?? should it be called with option to hide all editing features?
47802      */
47803  /**
47804      * create a DomHelper friendly object - for use with
47805      * Roo.DomHelper.markup / overwrite / etc..
47806      * ?? should it be called with option to hide all editing features?
47807      */
47808     toObject : function()
47809     {
47810         
47811         var ret = {
47812             tag : 'td',
47813             contenteditable : 'true', // this stops cell selection from picking the table.
47814             'data-block' : 'Td',
47815             valign : this.valign,
47816             style : {  
47817                 'text-align' :  this.textAlign,
47818                 border : 'solid 1px rgb(0, 0, 0)', // ??? hard coded?
47819                 'border-collapse' : 'collapse',
47820                 padding : '6px', // 8 for desktop / 4 for mobile
47821                 'vertical-align': this.valign
47822             },
47823             html : this.html
47824         };
47825         if (this.width != '') {
47826             ret.width = this.width;
47827             ret.style.width = this.width;
47828         }
47829         
47830         
47831         if (this.colspan > 1) {
47832             ret.colspan = this.colspan ;
47833         } 
47834         if (this.rowspan > 1) {
47835             ret.rowspan = this.rowspan ;
47836         }
47837         
47838            
47839         
47840         return ret;
47841          
47842     },
47843     
47844     readElement : function(node)
47845     {
47846         node  = node ? node : this.node ;
47847         this.width = node.style.width;
47848         this.colspan = Math.max(1,1*node.getAttribute('colspan'));
47849         this.rowspan = Math.max(1,1*node.getAttribute('rowspan'));
47850         this.html = node.innerHTML;
47851         
47852         
47853     },
47854      
47855     // the default cell object... at present...
47856     emptyCell : function() {
47857         return {
47858             colspan :  1,
47859             rowspan :  1,
47860             textAlign : 'left',
47861             html : "&nbsp;" // is this going to be editable now?
47862         };
47863      
47864     },
47865     
47866     removeNode : function()
47867     {
47868         return this.node.closest('table');
47869          
47870     },
47871     
47872     cellData : false,
47873     
47874     colWidths : false,
47875     
47876     toTableArray  : function()
47877     {
47878         var ret = [];
47879         var tab = this.node.closest('tr').closest('table');
47880         Array.from(tab.rows).forEach(function(r, ri){
47881             ret[ri] = [];
47882         });
47883         var rn = 0;
47884         this.colWidths = [];
47885         var all_auto = true;
47886         Array.from(tab.rows).forEach(function(r, ri){
47887             
47888             var cn = 0;
47889             Array.from(r.cells).forEach(function(ce, ci){
47890                 var c =  {
47891                     cell : ce,
47892                     row : rn,
47893                     col: cn,
47894                     colspan : ce.colSpan,
47895                     rowspan : ce.rowSpan
47896                 };
47897                 if (ce.isEqualNode(this.node)) {
47898                     this.cellData = c;
47899                 }
47900                 // if we have been filled up by a row?
47901                 if (typeof(ret[rn][cn]) != 'undefined') {
47902                     while(typeof(ret[rn][cn]) != 'undefined') {
47903                         cn++;
47904                     }
47905                     c.col = cn;
47906                 }
47907                 
47908                 if (typeof(this.colWidths[cn]) == 'undefined') {
47909                     this.colWidths[cn] =   ce.style.width;
47910                     if (this.colWidths[cn] != '') {
47911                         all_auto = false;
47912                     }
47913                 }
47914                 
47915                 
47916                 if (c.colspan < 2 && c.rowspan < 2 ) {
47917                     ret[rn][cn] = c;
47918                     cn++;
47919                     return;
47920                 }
47921                 for(var j = 0; j < c.rowspan; j++) {
47922                     if (typeof(ret[rn+j]) == 'undefined') {
47923                         continue; // we have a problem..
47924                     }
47925                     ret[rn+j][cn] = c;
47926                     for(var i = 0; i < c.colspan; i++) {
47927                         ret[rn+j][cn+i] = c;
47928                     }
47929                 }
47930                 
47931                 cn += c.colspan;
47932             }, this);
47933             rn++;
47934         }, this);
47935         
47936         // initalize widths.?
47937         // either all widths or no widths..
47938         if (all_auto) {
47939             this.colWidths[0] = false; // no widths flag.
47940         }
47941         
47942         
47943         return ret;
47944         
47945     },
47946     
47947     
47948     
47949     
47950     mergeRight: function()
47951     {
47952          
47953         // get the contents of the next cell along..
47954         var tr = this.node.closest('tr');
47955         var i = Array.prototype.indexOf.call(tr.childNodes, this.node);
47956         if (i >= tr.childNodes.length - 1) {
47957             return; // no cells on right to merge with.
47958         }
47959         var table = this.toTableArray();
47960         
47961         if (typeof(table[this.cellData.row][this.cellData.col+this.cellData.colspan]) == 'undefined') {
47962             return; // nothing right?
47963         }
47964         var rc = table[this.cellData.row][this.cellData.col+this.cellData.colspan];
47965         // right cell - must be same rowspan and on the same row.
47966         if (rc.rowspan != this.cellData.rowspan || rc.row != this.cellData.row) {
47967             return; // right hand side is not same rowspan.
47968         }
47969         
47970         
47971         
47972         this.node.innerHTML += ' ' + rc.cell.innerHTML;
47973         tr.removeChild(rc.cell);
47974         this.colspan += rc.colspan;
47975         this.node.setAttribute('colspan', this.colspan);
47976
47977     },
47978     
47979     
47980     mergeBelow : function()
47981     {
47982         var table = this.toTableArray();
47983         if (typeof(table[this.cellData.row+this.cellData.rowspan]) == 'undefined') {
47984             return; // no row below
47985         }
47986         if (typeof(table[this.cellData.row+this.cellData.rowspan][this.cellData.col]) == 'undefined') {
47987             return; // nothing right?
47988         }
47989         var rc = table[this.cellData.row+this.cellData.rowspan][this.cellData.col];
47990         
47991         if (rc.colspan != this.cellData.colspan || rc.col != this.cellData.col) {
47992             return; // right hand side is not same rowspan.
47993         }
47994         this.node.innerHTML =  this.node.innerHTML + rc.cell.innerHTML ;
47995         rc.cell.parentNode.removeChild(rc.cell);
47996         this.rowspan += rc.rowspan;
47997         this.node.setAttribute('rowspan', this.rowspan);
47998     },
47999     
48000     split: function()
48001     {
48002         if (this.node.rowSpan < 2 && this.node.colSpan < 2) {
48003             return;
48004         }
48005         var table = this.toTableArray();
48006         var cd = this.cellData;
48007         this.rowspan = 1;
48008         this.colspan = 1;
48009         
48010         for(var r = cd.row; r < cd.row + cd.rowspan; r++) {
48011             
48012             
48013             
48014             for(var c = cd.col; c < cd.col + cd.colspan; c++) {
48015                 if (r == cd.row && c == cd.col) {
48016                     this.node.removeAttribute('rowspan');
48017                     this.node.removeAttribute('colspan');
48018                     continue;
48019                 }
48020                  
48021                 var ntd = this.node.cloneNode(); // which col/row should be 0..
48022                 ntd.removeAttribute('id'); //
48023                 //ntd.style.width  = '';
48024                 ntd.innerHTML = '';
48025                 table[r][c] = { cell : ntd, col : c, row: r , colspan : 1 , rowspan : 1   };
48026             }
48027             
48028         }
48029         this.redrawAllCells(table);
48030         
48031          
48032         
48033     },
48034     
48035     
48036     
48037     redrawAllCells: function(table)
48038     {
48039         
48040          
48041         var tab = this.node.closest('tr').closest('table');
48042         var ctr = tab.rows[0].parentNode;
48043         Array.from(tab.rows).forEach(function(r, ri){
48044             
48045             Array.from(r.cells).forEach(function(ce, ci){
48046                 ce.parentNode.removeChild(ce);
48047             });
48048             r.parentNode.removeChild(r);
48049         });
48050         for(var r = 0 ; r < table.length; r++) {
48051             var re = tab.rows[r];
48052             
48053             var re = tab.ownerDocument.createElement('tr');
48054             ctr.appendChild(re);
48055             for(var c = 0 ; c < table[r].length; c++) {
48056                 if (table[r][c].cell === false) {
48057                     continue;
48058                 }
48059                 
48060                 re.appendChild(table[r][c].cell);
48061                  
48062                 table[r][c].cell = false;
48063             }
48064         }
48065         
48066     },
48067     updateWidths : function(table)
48068     {
48069         for(var r = 0 ; r < table.length; r++) {
48070            
48071             for(var c = 0 ; c < table[r].length; c++) {
48072                 if (table[r][c].cell === false) {
48073                     continue;
48074                 }
48075                 
48076                 if (this.colWidths[0] != false && table[r][c].colspan < 2) {
48077                     var el = Roo.htmleditor.Block.factory(table[r][c].cell);
48078                     el.width = Math.floor(this.colWidths[c])  +'%';
48079                     el.updateElement(el.node);
48080                 }
48081                 table[r][c].cell = false; // done
48082             }
48083         }
48084     },
48085     normalizeWidths : function(table)
48086     {
48087     
48088         if (this.colWidths[0] === false) {
48089             var nw = 100.0 / this.colWidths.length;
48090             this.colWidths.forEach(function(w,i) {
48091                 this.colWidths[i] = nw;
48092             },this);
48093             return;
48094         }
48095     
48096         var t = 0, missing = [];
48097         
48098         this.colWidths.forEach(function(w,i) {
48099             //if you mix % and
48100             this.colWidths[i] = this.colWidths[i] == '' ? 0 : (this.colWidths[i]+'').replace(/[^0-9]+/g,'')*1;
48101             var add =  this.colWidths[i];
48102             if (add > 0) {
48103                 t+=add;
48104                 return;
48105             }
48106             missing.push(i);
48107             
48108             
48109         },this);
48110         var nc = this.colWidths.length;
48111         if (missing.length) {
48112             var mult = (nc - missing.length) / (1.0 * nc);
48113             var t = mult * t;
48114             var ew = (100 -t) / (1.0 * missing.length);
48115             this.colWidths.forEach(function(w,i) {
48116                 if (w > 0) {
48117                     this.colWidths[i] = w * mult;
48118                     return;
48119                 }
48120                 
48121                 this.colWidths[i] = ew;
48122             }, this);
48123             // have to make up numbers..
48124              
48125         }
48126         // now we should have all the widths..
48127         
48128     
48129     },
48130     
48131     shrinkColumn : function()
48132     {
48133         var table = this.toTableArray();
48134         this.normalizeWidths(table);
48135         var col = this.cellData.col;
48136         var nw = this.colWidths[col] * 0.8;
48137         if (nw < 5) {
48138             return;
48139         }
48140         var otherAdd = (this.colWidths[col]  * 0.2) / (this.colWidths.length -1);
48141         this.colWidths.forEach(function(w,i) {
48142             if (i == col) {
48143                  this.colWidths[i] = nw;
48144                 return;
48145             }
48146             this.colWidths[i] += otherAdd
48147         }, this);
48148         this.updateWidths(table);
48149          
48150     },
48151     growColumn : function()
48152     {
48153         var table = this.toTableArray();
48154         this.normalizeWidths(table);
48155         var col = this.cellData.col;
48156         var nw = this.colWidths[col] * 1.2;
48157         if (nw > 90) {
48158             return;
48159         }
48160         var otherSub = (this.colWidths[col]  * 0.2) / (this.colWidths.length -1);
48161         this.colWidths.forEach(function(w,i) {
48162             if (i == col) {
48163                 this.colWidths[i] = nw;
48164                 return;
48165             }
48166             this.colWidths[i] -= otherSub
48167         }, this);
48168         this.updateWidths(table);
48169          
48170     },
48171     deleteRow : function()
48172     {
48173         // delete this rows 'tr'
48174         // if any of the cells in this row have a rowspan > 1 && row!= this row..
48175         // then reduce the rowspan.
48176         var table = this.toTableArray();
48177         // this.cellData.row;
48178         for (var i =0;i< table[this.cellData.row].length ; i++) {
48179             var c = table[this.cellData.row][i];
48180             if (c.row != this.cellData.row) {
48181                 
48182                 c.rowspan--;
48183                 c.cell.setAttribute('rowspan', c.rowspan);
48184                 continue;
48185             }
48186             if (c.rowspan > 1) {
48187                 c.rowspan--;
48188                 c.cell.setAttribute('rowspan', c.rowspan);
48189             }
48190         }
48191         table.splice(this.cellData.row,1);
48192         this.redrawAllCells(table);
48193         
48194     },
48195     deleteColumn : function()
48196     {
48197         var table = this.toTableArray();
48198         
48199         for (var i =0;i< table.length ; i++) {
48200             var c = table[i][this.cellData.col];
48201             if (c.col != this.cellData.col) {
48202                 table[i][this.cellData.col].colspan--;
48203             } else if (c.colspan > 1) {
48204                 c.colspan--;
48205                 c.cell.setAttribute('colspan', c.colspan);
48206             }
48207             table[i].splice(this.cellData.col,1);
48208         }
48209         
48210         this.redrawAllCells(table);
48211     }
48212     
48213     
48214     
48215     
48216 })
48217
48218 //<script type="text/javascript">
48219
48220 /*
48221  * Based  Ext JS Library 1.1.1
48222  * Copyright(c) 2006-2007, Ext JS, LLC.
48223  * LGPL
48224  *
48225  */
48226  
48227 /**
48228  * @class Roo.HtmlEditorCore
48229  * @extends Roo.Component
48230  * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
48231  *
48232  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
48233  */
48234
48235 Roo.HtmlEditorCore = function(config){
48236     
48237     
48238     Roo.HtmlEditorCore.superclass.constructor.call(this, config);
48239     
48240     
48241     this.addEvents({
48242         /**
48243          * @event initialize
48244          * Fires when the editor is fully initialized (including the iframe)
48245          * @param {Roo.HtmlEditorCore} this
48246          */
48247         initialize: true,
48248         /**
48249          * @event activate
48250          * Fires when the editor is first receives the focus. Any insertion must wait
48251          * until after this event.
48252          * @param {Roo.HtmlEditorCore} this
48253          */
48254         activate: true,
48255          /**
48256          * @event beforesync
48257          * Fires before the textarea is updated with content from the editor iframe. Return false
48258          * to cancel the sync.
48259          * @param {Roo.HtmlEditorCore} this
48260          * @param {String} html
48261          */
48262         beforesync: true,
48263          /**
48264          * @event beforepush
48265          * Fires before the iframe editor is updated with content from the textarea. Return false
48266          * to cancel the push.
48267          * @param {Roo.HtmlEditorCore} this
48268          * @param {String} html
48269          */
48270         beforepush: true,
48271          /**
48272          * @event sync
48273          * Fires when the textarea is updated with content from the editor iframe.
48274          * @param {Roo.HtmlEditorCore} this
48275          * @param {String} html
48276          */
48277         sync: true,
48278          /**
48279          * @event push
48280          * Fires when the iframe editor is updated with content from the textarea.
48281          * @param {Roo.HtmlEditorCore} this
48282          * @param {String} html
48283          */
48284         push: true,
48285         
48286         /**
48287          * @event editorevent
48288          * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
48289          * @param {Roo.HtmlEditorCore} this
48290          */
48291         editorevent: true 
48292          
48293         
48294     });
48295     
48296     // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
48297     
48298     // defaults : white / black...
48299     this.applyBlacklists();
48300     
48301     
48302     
48303 };
48304
48305
48306 Roo.extend(Roo.HtmlEditorCore, Roo.Component,  {
48307
48308
48309      /**
48310      * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field 
48311      */
48312     
48313     owner : false,
48314     
48315      /**
48316      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
48317      *                        Roo.resizable.
48318      */
48319     resizable : false,
48320      /**
48321      * @cfg {Number} height (in pixels)
48322      */   
48323     height: 300,
48324    /**
48325      * @cfg {Number} width (in pixels)
48326      */   
48327     width: 500,
48328      /**
48329      * @cfg {boolean} autoClean - default true - loading and saving will remove quite a bit of formating,
48330      *         if you are doing an email editor, this probably needs disabling, it's designed
48331      */
48332     autoClean: true,
48333     
48334     /**
48335      * @cfg {boolean} enableBlocks - default true - if the block editor (table and figure should be enabled)
48336      */
48337     enableBlocks : true,
48338     /**
48339      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
48340      * 
48341      */
48342     stylesheets: false,
48343      /**
48344      * @cfg {String} language default en - language of text (usefull for rtl languages)
48345      * 
48346      */
48347     language: 'en',
48348     
48349     /**
48350      * @cfg {boolean} allowComments - default false - allow comments in HTML source
48351      *          - by default they are stripped - if you are editing email you may need this.
48352      */
48353     allowComments: false,
48354     // id of frame..
48355     frameId: false,
48356     
48357     // private properties
48358     validationEvent : false,
48359     deferHeight: true,
48360     initialized : false,
48361     activated : false,
48362     sourceEditMode : false,
48363     onFocus : Roo.emptyFn,
48364     iframePad:3,
48365     hideMode:'offsets',
48366     
48367     clearUp: true,
48368     
48369     // blacklist + whitelisted elements..
48370     black: false,
48371     white: false,
48372      
48373     bodyCls : '',
48374
48375     
48376     undoManager : false,
48377     /**
48378      * Protected method that will not generally be called directly. It
48379      * is called when the editor initializes the iframe with HTML contents. Override this method if you
48380      * want to change the initialization markup of the iframe (e.g. to add stylesheets).
48381      */
48382     getDocMarkup : function(){
48383         // body styles..
48384         var st = '';
48385         
48386         // inherit styels from page...?? 
48387         if (this.stylesheets === false) {
48388             
48389             Roo.get(document.head).select('style').each(function(node) {
48390                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
48391             });
48392             
48393             Roo.get(document.head).select('link').each(function(node) { 
48394                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
48395             });
48396             
48397         } else if (!this.stylesheets.length) {
48398                 // simple..
48399                 st = '<style type="text/css">' +
48400                     'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
48401                    '</style>';
48402         } else {
48403             for (var i in this.stylesheets) {
48404                 if (typeof(this.stylesheets[i]) != 'string') {
48405                     continue;
48406                 }
48407                 st += '<link rel="stylesheet" href="' + this.stylesheets[i] +'" type="text/css">';
48408             }
48409             
48410         }
48411         
48412         st +=  '<style type="text/css">' +
48413             'IMG { cursor: pointer } ' +
48414         '</style>';
48415
48416         var cls = 'roo-htmleditor-body';
48417         
48418         if(this.bodyCls.length){
48419             cls += ' ' + this.bodyCls;
48420         }
48421         
48422         return '<html><head>' + st  +
48423             //<style type="text/css">' +
48424             //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
48425             //'</style>' +
48426             ' </head><body contenteditable="true" data-enable-grammerly="true" class="' +  cls + '"></body></html>';
48427     },
48428
48429     // private
48430     onRender : function(ct, position)
48431     {
48432         var _t = this;
48433         //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
48434         this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
48435         
48436         
48437         this.el.dom.style.border = '0 none';
48438         this.el.dom.setAttribute('tabIndex', -1);
48439         this.el.addClass('x-hidden hide');
48440         
48441         
48442         
48443         if(Roo.isIE){ // fix IE 1px bogus margin
48444             this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
48445         }
48446        
48447         
48448         this.frameId = Roo.id();
48449         
48450          
48451         
48452         var iframe = this.owner.wrap.createChild({
48453             tag: 'iframe',
48454             cls: 'form-control', // bootstrap..
48455             id: this.frameId,
48456             name: this.frameId,
48457             frameBorder : 'no',
48458             'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL  :  "javascript:false"
48459         }, this.el
48460         );
48461         
48462         
48463         this.iframe = iframe.dom;
48464
48465         this.assignDocWin();
48466         
48467         this.doc.designMode = 'on';
48468        
48469         this.doc.open();
48470         this.doc.write(this.getDocMarkup());
48471         this.doc.close();
48472
48473         
48474         var task = { // must defer to wait for browser to be ready
48475             run : function(){
48476                 //console.log("run task?" + this.doc.readyState);
48477                 this.assignDocWin();
48478                 if(this.doc.body || this.doc.readyState == 'complete'){
48479                     try {
48480                         this.doc.designMode="on";
48481                         
48482                     } catch (e) {
48483                         return;
48484                     }
48485                     Roo.TaskMgr.stop(task);
48486                     this.initEditor.defer(10, this);
48487                 }
48488             },
48489             interval : 10,
48490             duration: 10000,
48491             scope: this
48492         };
48493         Roo.TaskMgr.start(task);
48494
48495     },
48496
48497     // private
48498     onResize : function(w, h)
48499     {
48500          Roo.log('resize: ' +w + ',' + h );
48501         //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
48502         if(!this.iframe){
48503             return;
48504         }
48505         if(typeof w == 'number'){
48506             
48507             this.iframe.style.width = w + 'px';
48508         }
48509         if(typeof h == 'number'){
48510             
48511             this.iframe.style.height = h + 'px';
48512             if(this.doc){
48513                 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
48514             }
48515         }
48516         
48517     },
48518
48519     /**
48520      * Toggles the editor between standard and source edit mode.
48521      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
48522      */
48523     toggleSourceEdit : function(sourceEditMode){
48524         
48525         this.sourceEditMode = sourceEditMode === true;
48526         
48527         if(this.sourceEditMode){
48528  
48529             Roo.get(this.iframe).addClass(['x-hidden','hide', 'd-none']);     //FIXME - what's the BS styles for these
48530             
48531         }else{
48532             Roo.get(this.iframe).removeClass(['x-hidden','hide', 'd-none']);
48533             //this.iframe.className = '';
48534             this.deferFocus();
48535         }
48536         //this.setSize(this.owner.wrap.getSize());
48537         //this.fireEvent('editmodechange', this, this.sourceEditMode);
48538     },
48539
48540     
48541   
48542
48543     /**
48544      * Protected method that will not generally be called directly. If you need/want
48545      * custom HTML cleanup, this is the method you should override.
48546      * @param {String} html The HTML to be cleaned
48547      * return {String} The cleaned HTML
48548      */
48549     cleanHtml : function(html){
48550         html = String(html);
48551         if(html.length > 5){
48552             if(Roo.isSafari){ // strip safari nonsense
48553                 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
48554             }
48555         }
48556         if(html == '&nbsp;'){
48557             html = '';
48558         }
48559         return html;
48560     },
48561
48562     /**
48563      * HTML Editor -> Textarea
48564      * Protected method that will not generally be called directly. Syncs the contents
48565      * of the editor iframe with the textarea.
48566      */
48567     syncValue : function()
48568     {
48569         //Roo.log("HtmlEditorCore:syncValue (EDITOR->TEXT)");
48570         if(this.initialized){
48571             
48572             this.undoManager.addEvent();
48573
48574             
48575             var bd = (this.doc.body || this.doc.documentElement);
48576            
48577             
48578             
48579             var div = document.createElement('div');
48580             div.innerHTML = bd.innerHTML;
48581              
48582            
48583             if (this.enableBlocks) {
48584                 new Roo.htmleditor.FilterBlock({ node : div });
48585             }
48586             //?? tidy?
48587             
48588             
48589             var html = div.innerHTML;
48590             if(Roo.isSafari){
48591                 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
48592                 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
48593                 if(m && m[1]){
48594                     html = '<div style="'+m[0]+'">' + html + '</div>';
48595                 }
48596             }
48597             html = this.cleanHtml(html);
48598             // fix up the special chars.. normaly like back quotes in word...
48599             // however we do not want to do this with chinese..
48600             html = html.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u0080-\uFFFF]/g, function(match) {
48601                 
48602                 var cc = match.charCodeAt();
48603
48604                 // Get the character value, handling surrogate pairs
48605                 if (match.length == 2) {
48606                     // It's a surrogate pair, calculate the Unicode code point
48607                     var high = match.charCodeAt(0) - 0xD800;
48608                     var low  = match.charCodeAt(1) - 0xDC00;
48609                     cc = (high * 0x400) + low + 0x10000;
48610                 }  else if (
48611                     (cc >= 0x4E00 && cc < 0xA000 ) ||
48612                     (cc >= 0x3400 && cc < 0x4E00 ) ||
48613                     (cc >= 0xf900 && cc < 0xfb00 )
48614                 ) {
48615                         return match;
48616                 }  
48617          
48618                 // No, use a numeric entity. Here we brazenly (and possibly mistakenly)
48619                 return "&#" + cc + ";";
48620                 
48621                 
48622             });
48623             
48624             
48625              
48626             if(this.owner.fireEvent('beforesync', this, html) !== false){
48627                 this.el.dom.value = html;
48628                 this.owner.fireEvent('sync', this, html);
48629             }
48630         }
48631     },
48632
48633     /**
48634      * TEXTAREA -> EDITABLE
48635      * Protected method that will not generally be called directly. Pushes the value of the textarea
48636      * into the iframe editor.
48637      */
48638     pushValue : function()
48639     {
48640         //Roo.log("HtmlEditorCore:pushValue (TEXT->EDITOR)");
48641         if(this.initialized){
48642             var v = this.el.dom.value.trim();
48643             
48644             
48645             if(this.owner.fireEvent('beforepush', this, v) !== false){
48646                 var d = (this.doc.body || this.doc.documentElement);
48647                 d.innerHTML = v;
48648                  
48649                 this.el.dom.value = d.innerHTML;
48650                 this.owner.fireEvent('push', this, v);
48651             }
48652             if (this.autoClean) {
48653                 new Roo.htmleditor.FilterParagraph({node : this.doc.body}); // paragraphs
48654                 new Roo.htmleditor.FilterSpan({node : this.doc.body}); // empty spans
48655             }
48656             
48657             Roo.htmleditor.Block.initAll(this.doc.body);
48658             this.updateLanguage();
48659             
48660             var lc = this.doc.body.lastChild;
48661             if (lc && lc.nodeType == 1 && lc.getAttribute("contenteditable") == "false") {
48662                 // add an extra line at the end.
48663                 this.doc.body.appendChild(this.doc.createElement('br'));
48664             }
48665             
48666             
48667         }
48668     },
48669
48670     // private
48671     deferFocus : function(){
48672         this.focus.defer(10, this);
48673     },
48674
48675     // doc'ed in Field
48676     focus : function(){
48677         if(this.win && !this.sourceEditMode){
48678             this.win.focus();
48679         }else{
48680             this.el.focus();
48681         }
48682     },
48683     
48684     assignDocWin: function()
48685     {
48686         var iframe = this.iframe;
48687         
48688          if(Roo.isIE){
48689             this.doc = iframe.contentWindow.document;
48690             this.win = iframe.contentWindow;
48691         } else {
48692 //            if (!Roo.get(this.frameId)) {
48693 //                return;
48694 //            }
48695 //            this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
48696 //            this.win = Roo.get(this.frameId).dom.contentWindow;
48697             
48698             if (!Roo.get(this.frameId) && !iframe.contentDocument) {
48699                 return;
48700             }
48701             
48702             this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
48703             this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
48704         }
48705     },
48706     
48707     // private
48708     initEditor : function(){
48709         //console.log("INIT EDITOR");
48710         this.assignDocWin();
48711         
48712         
48713         
48714         this.doc.designMode="on";
48715         this.doc.open();
48716         this.doc.write(this.getDocMarkup());
48717         this.doc.close();
48718         
48719         var dbody = (this.doc.body || this.doc.documentElement);
48720         //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
48721         // this copies styles from the containing element into thsi one..
48722         // not sure why we need all of this..
48723         //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
48724         
48725         //var ss = this.el.getStyles( 'background-image', 'background-repeat');
48726         //ss['background-attachment'] = 'fixed'; // w3c
48727         dbody.bgProperties = 'fixed'; // ie
48728         //Roo.DomHelper.applyStyles(dbody, ss);
48729         Roo.EventManager.on(this.doc, {
48730             //'mousedown': this.onEditorEvent,
48731             'mouseup': this.onEditorEvent,
48732             'dblclick': this.onEditorEvent,
48733             'click': this.onEditorEvent,
48734             'keyup': this.onEditorEvent,
48735             
48736             buffer:100,
48737             scope: this
48738         });
48739         Roo.EventManager.on(this.doc, {
48740             'paste': this.onPasteEvent,
48741             scope : this
48742         });
48743         if(Roo.isGecko){
48744             Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
48745         }
48746         //??? needed???
48747         if(Roo.isIE || Roo.isSafari || Roo.isOpera){
48748             Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
48749         }
48750         this.initialized = true;
48751
48752         
48753         // initialize special key events - enter
48754         new Roo.htmleditor.KeyEnter({core : this});
48755         
48756          
48757         
48758         this.owner.fireEvent('initialize', this);
48759         this.pushValue();
48760     },
48761     
48762     onPasteEvent : function(e,v)
48763     {
48764         // I think we better assume paste is going to be a dirty load of rubish from word..
48765         
48766         // even pasting into a 'email version' of this widget will have to clean up that mess.
48767         var cd = (e.browserEvent.clipboardData || window.clipboardData);
48768         
48769         // check what type of paste - if it's an image, then handle it differently.
48770         if (cd.files.length > 0) {
48771             // pasting images?
48772             var urlAPI = (window.createObjectURL && window) || 
48773                 (window.URL && URL.revokeObjectURL && URL) || 
48774                 (window.webkitURL && webkitURL);
48775     
48776             var url = urlAPI.createObjectURL( cd.files[0]);
48777             this.insertAtCursor('<img src=" + url + ">');
48778             return false;
48779         }
48780         
48781         var html = cd.getData('text/html'); // clipboard event
48782         var parser = new Roo.rtf.Parser(cd.getData('text/rtf'));
48783         var images = parser.doc ? parser.doc.getElementsByType('pict') : [];
48784         Roo.log(images);
48785         //Roo.log(imgs);
48786         // fixme..
48787         images = images.filter(function(g) { return !g.path.match(/^rtf\/(head|pgdsctbl|listtable)/); }) // ignore headers
48788                        .map(function(g) { return g.toDataURL(); });
48789         
48790         
48791         html = this.cleanWordChars(html);
48792         
48793         var d = (new DOMParser().parseFromString(html, 'text/html')).body;
48794         
48795         
48796         var sn = this.getParentElement();
48797         // check if d contains a table, and prevent nesting??
48798         //Roo.log(d.getElementsByTagName('table'));
48799         //Roo.log(sn);
48800         //Roo.log(sn.closest('table'));
48801         if (d.getElementsByTagName('table').length && sn && sn.closest('table')) {
48802             e.preventDefault();
48803             this.insertAtCursor("You can not nest tables");
48804             //Roo.log("prevent?"); // fixme - 
48805             return false;
48806         }
48807         
48808         if (images.length > 0) {
48809             Roo.each(d.getElementsByTagName('img'), function(img, i) {
48810                 img.setAttribute('src', images[i]);
48811             });
48812         }
48813         if (this.autoClean) {
48814             new Roo.htmleditor.FilterStyleToTag({ node : d });
48815             new Roo.htmleditor.FilterAttributes({
48816                 node : d,
48817                 attrib_white : ['href', 'src', 'name', 'align'],
48818                 attrib_clean : ['href', 'src' ] 
48819             });
48820             new Roo.htmleditor.FilterBlack({ node : d, tag : this.black});
48821             // should be fonts..
48822             new Roo.htmleditor.FilterKeepChildren({node : d, tag : [ 'FONT' ]} );
48823             new Roo.htmleditor.FilterParagraph({ node : d });
48824             new Roo.htmleditor.FilterSpan({ node : d });
48825             new Roo.htmleditor.FilterLongBr({ node : d });
48826         }
48827         if (this.enableBlocks) {
48828                 
48829             Array.from(d.getElementsByTagName('img')).forEach(function(img) {
48830                 if (img.closest('figure')) { // assume!! that it's aready
48831                     return;
48832                 }
48833                 var fig  = new Roo.htmleditor.BlockFigure({
48834                     image_src  : img.src
48835                 });
48836                 fig.updateElement(img); // replace it..
48837                 
48838             });
48839         }
48840         
48841         
48842         this.insertAtCursor(d.innerHTML.replace(/&nbsp;/g,' '));
48843         if (this.enableBlocks) {
48844             Roo.htmleditor.Block.initAll(this.doc.body);
48845         }
48846         
48847         
48848         e.preventDefault();
48849         return false;
48850         // default behaveiour should be our local cleanup paste? (optional?)
48851         // for simple editor - we want to hammer the paste and get rid of everything... - so over-rideable..
48852         //this.owner.fireEvent('paste', e, v);
48853     },
48854     // private
48855     onDestroy : function(){
48856         
48857         
48858         
48859         if(this.rendered){
48860             
48861             //for (var i =0; i < this.toolbars.length;i++) {
48862             //    // fixme - ask toolbars for heights?
48863             //    this.toolbars[i].onDestroy();
48864            // }
48865             
48866             //this.wrap.dom.innerHTML = '';
48867             //this.wrap.remove();
48868         }
48869     },
48870
48871     // private
48872     onFirstFocus : function(){
48873         
48874         this.assignDocWin();
48875         this.undoManager = new Roo.lib.UndoManager(100,(this.doc.body || this.doc.documentElement));
48876         
48877         this.activated = true;
48878          
48879     
48880         if(Roo.isGecko){ // prevent silly gecko errors
48881             this.win.focus();
48882             var s = this.win.getSelection();
48883             if(!s.focusNode || s.focusNode.nodeType != 3){
48884                 var r = s.getRangeAt(0);
48885                 r.selectNodeContents((this.doc.body || this.doc.documentElement));
48886                 r.collapse(true);
48887                 this.deferFocus();
48888             }
48889             try{
48890                 this.execCmd('useCSS', true);
48891                 this.execCmd('styleWithCSS', false);
48892             }catch(e){}
48893         }
48894         this.owner.fireEvent('activate', this);
48895     },
48896
48897     // private
48898     adjustFont: function(btn){
48899         var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
48900         //if(Roo.isSafari){ // safari
48901         //    adjust *= 2;
48902        // }
48903         var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
48904         if(Roo.isSafari){ // safari
48905             var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
48906             v =  (v < 10) ? 10 : v;
48907             v =  (v > 48) ? 48 : v;
48908             v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
48909             
48910         }
48911         
48912         
48913         v = Math.max(1, v+adjust);
48914         
48915         this.execCmd('FontSize', v  );
48916     },
48917
48918     onEditorEvent : function(e)
48919     {
48920         
48921         if (e && (e.ctrlKey || e.metaKey) && e.keyCode === 90) {
48922             return; // we do not handle this.. (undo manager does..)
48923         }
48924         // in theory this detects if the last element is not a br, then we try and do that.
48925         // its so clicking in space at bottom triggers adding a br and moving the cursor.
48926         if (e &&
48927             e.target.nodeName == 'BODY' &&
48928             e.type == "mouseup" &&
48929             this.doc.body.lastChild
48930            ) {
48931             var lc = this.doc.body.lastChild;
48932             // gtx-trans is google translate plugin adding crap.
48933             while ((lc.nodeType == 3 && lc.nodeValue == '') || lc.id == 'gtx-trans') {
48934                 lc = lc.previousSibling;
48935             }
48936             if (lc.nodeType == 1 && lc.nodeName != 'BR') {
48937             // if last element is <BR> - then dont do anything.
48938             
48939                 var ns = this.doc.createElement('br');
48940                 this.doc.body.appendChild(ns);
48941                 range = this.doc.createRange();
48942                 range.setStartAfter(ns);
48943                 range.collapse(true);
48944                 var sel = this.win.getSelection();
48945                 sel.removeAllRanges();
48946                 sel.addRange(range);
48947             }
48948         }
48949         
48950         
48951         
48952         this.fireEditorEvent(e);
48953       //  this.updateToolbar();
48954         this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
48955     },
48956     
48957     fireEditorEvent: function(e)
48958     {
48959         this.owner.fireEvent('editorevent', this, e);
48960     },
48961
48962     insertTag : function(tg)
48963     {
48964         // could be a bit smarter... -> wrap the current selected tRoo..
48965         if (tg.toLowerCase() == 'span' ||
48966             tg.toLowerCase() == 'code' ||
48967             tg.toLowerCase() == 'sup' ||
48968             tg.toLowerCase() == 'sub' 
48969             ) {
48970             
48971             range = this.createRange(this.getSelection());
48972             var wrappingNode = this.doc.createElement(tg.toLowerCase());
48973             wrappingNode.appendChild(range.extractContents());
48974             range.insertNode(wrappingNode);
48975
48976             return;
48977             
48978             
48979             
48980         }
48981         this.execCmd("formatblock",   tg);
48982         this.undoManager.addEvent(); 
48983     },
48984     
48985     insertText : function(txt)
48986     {
48987         
48988         
48989         var range = this.createRange();
48990         range.deleteContents();
48991                //alert(Sender.getAttribute('label'));
48992                
48993         range.insertNode(this.doc.createTextNode(txt));
48994         this.undoManager.addEvent();
48995     } ,
48996     
48997      
48998
48999     /**
49000      * Executes a Midas editor command on the editor document and performs necessary focus and
49001      * toolbar updates. <b>This should only be called after the editor is initialized.</b>
49002      * @param {String} cmd The Midas command
49003      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
49004      */
49005     relayCmd : function(cmd, value)
49006     {
49007         
49008         switch (cmd) {
49009             case 'justifyleft':
49010             case 'justifyright':
49011             case 'justifycenter':
49012                 // if we are in a cell, then we will adjust the
49013                 var n = this.getParentElement();
49014                 var td = n.closest('td');
49015                 if (td) {
49016                     var bl = Roo.htmleditor.Block.factory(td);
49017                     bl.textAlign = cmd.replace('justify','');
49018                     bl.updateElement();
49019                     this.owner.fireEvent('editorevent', this);
49020                     return;
49021                 }
49022                 this.execCmd('styleWithCSS', true); // 
49023                 break;
49024             case 'bold':
49025             case 'italic':
49026                 // if there is no selection, then we insert, and set the curson inside it..
49027                 this.execCmd('styleWithCSS', false); 
49028                 break;
49029                 
49030         
49031             default:
49032                 break;
49033         }
49034         
49035         
49036         this.win.focus();
49037         this.execCmd(cmd, value);
49038         this.owner.fireEvent('editorevent', this);
49039         //this.updateToolbar();
49040         this.owner.deferFocus();
49041     },
49042
49043     /**
49044      * Executes a Midas editor command directly on the editor document.
49045      * For visual commands, you should use {@link #relayCmd} instead.
49046      * <b>This should only be called after the editor is initialized.</b>
49047      * @param {String} cmd The Midas command
49048      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
49049      */
49050     execCmd : function(cmd, value){
49051         this.doc.execCommand(cmd, false, value === undefined ? null : value);
49052         this.syncValue();
49053     },
49054  
49055  
49056    
49057     /**
49058      * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
49059      * to insert tRoo.
49060      * @param {String} text | dom node.. 
49061      */
49062     insertAtCursor : function(text)
49063     {
49064         
49065         if(!this.activated){
49066             return;
49067         }
49068          
49069         if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
49070             this.win.focus();
49071             
49072             
49073             // from jquery ui (MIT licenced)
49074             var range, node;
49075             var win = this.win;
49076             
49077             if (win.getSelection && win.getSelection().getRangeAt) {
49078                 
49079                 // delete the existing?
49080                 
49081                 this.createRange(this.getSelection()).deleteContents();
49082                 range = win.getSelection().getRangeAt(0);
49083                 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
49084                 range.insertNode(node);
49085                 range = range.cloneRange();
49086                 range.collapse(false);
49087                  
49088                 win.getSelection().removeAllRanges();
49089                 win.getSelection().addRange(range);
49090                 
49091                 
49092                 
49093             } else if (win.document.selection && win.document.selection.createRange) {
49094                 // no firefox support
49095                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
49096                 win.document.selection.createRange().pasteHTML(txt);
49097             
49098             } else {
49099                 // no firefox support
49100                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
49101                 this.execCmd('InsertHTML', txt);
49102             } 
49103             this.syncValue();
49104             
49105             this.deferFocus();
49106         }
49107     },
49108  // private
49109     mozKeyPress : function(e){
49110         if(e.ctrlKey){
49111             var c = e.getCharCode(), cmd;
49112           
49113             if(c > 0){
49114                 c = String.fromCharCode(c).toLowerCase();
49115                 switch(c){
49116                     case 'b':
49117                         cmd = 'bold';
49118                         break;
49119                     case 'i':
49120                         cmd = 'italic';
49121                         break;
49122                     
49123                     case 'u':
49124                         cmd = 'underline';
49125                         break;
49126                     
49127                     //case 'v':
49128                       //  this.cleanUpPaste.defer(100, this);
49129                       //  return;
49130                         
49131                 }
49132                 if(cmd){
49133                     
49134                     this.relayCmd(cmd);
49135                     //this.win.focus();
49136                     //this.execCmd(cmd);
49137                     //this.deferFocus();
49138                     e.preventDefault();
49139                 }
49140                 
49141             }
49142         }
49143     },
49144
49145     // private
49146     fixKeys : function(){ // load time branching for fastest keydown performance
49147         
49148         
49149         if(Roo.isIE){
49150             return function(e){
49151                 var k = e.getKey(), r;
49152                 if(k == e.TAB){
49153                     e.stopEvent();
49154                     r = this.doc.selection.createRange();
49155                     if(r){
49156                         r.collapse(true);
49157                         r.pasteHTML('&#160;&#160;&#160;&#160;');
49158                         this.deferFocus();
49159                     }
49160                     return;
49161                 }
49162                 /// this is handled by Roo.htmleditor.KeyEnter
49163                  /*
49164                 if(k == e.ENTER){
49165                     r = this.doc.selection.createRange();
49166                     if(r){
49167                         var target = r.parentElement();
49168                         if(!target || target.tagName.toLowerCase() != 'li'){
49169                             e.stopEvent();
49170                             r.pasteHTML('<br/>');
49171                             r.collapse(false);
49172                             r.select();
49173                         }
49174                     }
49175                 }
49176                 */
49177                 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
49178                 //    this.cleanUpPaste.defer(100, this);
49179                 //    return;
49180                 //}
49181                 
49182                 
49183             };
49184         }else if(Roo.isOpera){
49185             return function(e){
49186                 var k = e.getKey();
49187                 if(k == e.TAB){
49188                     e.stopEvent();
49189                     this.win.focus();
49190                     this.execCmd('InsertHTML','&#160;&#160;&#160;&#160;');
49191                     this.deferFocus();
49192                 }
49193                
49194                 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
49195                 //    this.cleanUpPaste.defer(100, this);
49196                  //   return;
49197                 //}
49198                 
49199             };
49200         }else if(Roo.isSafari){
49201             return function(e){
49202                 var k = e.getKey();
49203                 
49204                 if(k == e.TAB){
49205                     e.stopEvent();
49206                     this.execCmd('InsertText','\t');
49207                     this.deferFocus();
49208                     return;
49209                 }
49210                  this.mozKeyPress(e);
49211                 
49212                //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
49213                  //   this.cleanUpPaste.defer(100, this);
49214                  //   return;
49215                // }
49216                 
49217              };
49218         }
49219     }(),
49220     
49221     getAllAncestors: function()
49222     {
49223         var p = this.getSelectedNode();
49224         var a = [];
49225         if (!p) {
49226             a.push(p); // push blank onto stack..
49227             p = this.getParentElement();
49228         }
49229         
49230         
49231         while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
49232             a.push(p);
49233             p = p.parentNode;
49234         }
49235         a.push(this.doc.body);
49236         return a;
49237     },
49238     lastSel : false,
49239     lastSelNode : false,
49240     
49241     
49242     getSelection : function() 
49243     {
49244         this.assignDocWin();
49245         return Roo.lib.Selection.wrap(Roo.isIE ? this.doc.selection : this.win.getSelection(), this.doc);
49246     },
49247     /**
49248      * Select a dom node
49249      * @param {DomElement} node the node to select
49250      */
49251     selectNode : function(node, collapse)
49252     {
49253         var nodeRange = node.ownerDocument.createRange();
49254         try {
49255             nodeRange.selectNode(node);
49256         } catch (e) {
49257             nodeRange.selectNodeContents(node);
49258         }
49259         if (collapse === true) {
49260             nodeRange.collapse(true);
49261         }
49262         //
49263         var s = this.win.getSelection();
49264         s.removeAllRanges();
49265         s.addRange(nodeRange);
49266     },
49267     
49268     getSelectedNode: function() 
49269     {
49270         // this may only work on Gecko!!!
49271         
49272         // should we cache this!!!!
49273         
49274          
49275          
49276         var range = this.createRange(this.getSelection()).cloneRange();
49277         
49278         if (Roo.isIE) {
49279             var parent = range.parentElement();
49280             while (true) {
49281                 var testRange = range.duplicate();
49282                 testRange.moveToElementText(parent);
49283                 if (testRange.inRange(range)) {
49284                     break;
49285                 }
49286                 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
49287                     break;
49288                 }
49289                 parent = parent.parentElement;
49290             }
49291             return parent;
49292         }
49293         
49294         // is ancestor a text element.
49295         var ac =  range.commonAncestorContainer;
49296         if (ac.nodeType == 3) {
49297             ac = ac.parentNode;
49298         }
49299         
49300         var ar = ac.childNodes;
49301          
49302         var nodes = [];
49303         var other_nodes = [];
49304         var has_other_nodes = false;
49305         for (var i=0;i<ar.length;i++) {
49306             if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ? 
49307                 continue;
49308             }
49309             // fullly contained node.
49310             
49311             if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
49312                 nodes.push(ar[i]);
49313                 continue;
49314             }
49315             
49316             // probably selected..
49317             if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
49318                 other_nodes.push(ar[i]);
49319                 continue;
49320             }
49321             // outer..
49322             if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0))  {
49323                 continue;
49324             }
49325             
49326             
49327             has_other_nodes = true;
49328         }
49329         if (!nodes.length && other_nodes.length) {
49330             nodes= other_nodes;
49331         }
49332         if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
49333             return false;
49334         }
49335         
49336         return nodes[0];
49337     },
49338     
49339     
49340     createRange: function(sel)
49341     {
49342         // this has strange effects when using with 
49343         // top toolbar - not sure if it's a great idea.
49344         //this.editor.contentWindow.focus();
49345         if (typeof sel != "undefined") {
49346             try {
49347                 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
49348             } catch(e) {
49349                 return this.doc.createRange();
49350             }
49351         } else {
49352             return this.doc.createRange();
49353         }
49354     },
49355     getParentElement: function()
49356     {
49357         
49358         this.assignDocWin();
49359         var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
49360         
49361         var range = this.createRange(sel);
49362          
49363         try {
49364             var p = range.commonAncestorContainer;
49365             while (p.nodeType == 3) { // text node
49366                 p = p.parentNode;
49367             }
49368             return p;
49369         } catch (e) {
49370             return null;
49371         }
49372     
49373     },
49374     /***
49375      *
49376      * Range intersection.. the hard stuff...
49377      *  '-1' = before
49378      *  '0' = hits..
49379      *  '1' = after.
49380      *         [ -- selected range --- ]
49381      *   [fail]                        [fail]
49382      *
49383      *    basically..
49384      *      if end is before start or  hits it. fail.
49385      *      if start is after end or hits it fail.
49386      *
49387      *   if either hits (but other is outside. - then it's not 
49388      *   
49389      *    
49390      **/
49391     
49392     
49393     // @see http://www.thismuchiknow.co.uk/?p=64.
49394     rangeIntersectsNode : function(range, node)
49395     {
49396         var nodeRange = node.ownerDocument.createRange();
49397         try {
49398             nodeRange.selectNode(node);
49399         } catch (e) {
49400             nodeRange.selectNodeContents(node);
49401         }
49402     
49403         var rangeStartRange = range.cloneRange();
49404         rangeStartRange.collapse(true);
49405     
49406         var rangeEndRange = range.cloneRange();
49407         rangeEndRange.collapse(false);
49408     
49409         var nodeStartRange = nodeRange.cloneRange();
49410         nodeStartRange.collapse(true);
49411     
49412         var nodeEndRange = nodeRange.cloneRange();
49413         nodeEndRange.collapse(false);
49414     
49415         return rangeStartRange.compareBoundaryPoints(
49416                  Range.START_TO_START, nodeEndRange) == -1 &&
49417                rangeEndRange.compareBoundaryPoints(
49418                  Range.START_TO_START, nodeStartRange) == 1;
49419         
49420          
49421     },
49422     rangeCompareNode : function(range, node)
49423     {
49424         var nodeRange = node.ownerDocument.createRange();
49425         try {
49426             nodeRange.selectNode(node);
49427         } catch (e) {
49428             nodeRange.selectNodeContents(node);
49429         }
49430         
49431         
49432         range.collapse(true);
49433     
49434         nodeRange.collapse(true);
49435      
49436         var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
49437         var ee = range.compareBoundaryPoints(  Range.END_TO_END, nodeRange);
49438          
49439         //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
49440         
49441         var nodeIsBefore   =  ss == 1;
49442         var nodeIsAfter    = ee == -1;
49443         
49444         if (nodeIsBefore && nodeIsAfter) {
49445             return 0; // outer
49446         }
49447         if (!nodeIsBefore && nodeIsAfter) {
49448             return 1; //right trailed.
49449         }
49450         
49451         if (nodeIsBefore && !nodeIsAfter) {
49452             return 2;  // left trailed.
49453         }
49454         // fully contined.
49455         return 3;
49456     },
49457  
49458     cleanWordChars : function(input) {// change the chars to hex code
49459         
49460        var swapCodes  = [ 
49461             [    8211, "&#8211;" ], 
49462             [    8212, "&#8212;" ], 
49463             [    8216,  "'" ],  
49464             [    8217, "'" ],  
49465             [    8220, '"' ],  
49466             [    8221, '"' ],  
49467             [    8226, "*" ],  
49468             [    8230, "..." ]
49469         ]; 
49470         var output = input;
49471         Roo.each(swapCodes, function(sw) { 
49472             var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
49473             
49474             output = output.replace(swapper, sw[1]);
49475         });
49476         
49477         return output;
49478     },
49479     
49480      
49481     
49482         
49483     
49484     cleanUpChild : function (node)
49485     {
49486         
49487         new Roo.htmleditor.FilterComment({node : node});
49488         new Roo.htmleditor.FilterAttributes({
49489                 node : node,
49490                 attrib_black : this.ablack,
49491                 attrib_clean : this.aclean,
49492                 style_white : this.cwhite,
49493                 style_black : this.cblack
49494         });
49495         new Roo.htmleditor.FilterBlack({ node : node, tag : this.black});
49496         new Roo.htmleditor.FilterKeepChildren({node : node, tag : this.tag_remove} );
49497          
49498         
49499     },
49500     
49501     /**
49502      * Clean up MS wordisms...
49503      * @deprecated - use filter directly
49504      */
49505     cleanWord : function(node)
49506     {
49507         new Roo.htmleditor.FilterWord({ node : node ? node : this.doc.body });
49508         
49509     },
49510    
49511     
49512     /**
49513
49514      * @deprecated - use filters
49515      */
49516     cleanTableWidths : function(node)
49517     {
49518         new Roo.htmleditor.FilterTableWidth({ node : node ? node : this.doc.body});
49519         
49520  
49521     },
49522     
49523      
49524         
49525     applyBlacklists : function()
49526     {
49527         var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white  : [];
49528         var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black :  [];
49529         
49530         this.aclean = typeof(this.owner.aclean) != 'undefined' && this.owner.aclean ? this.owner.aclean :  Roo.HtmlEditorCore.aclean;
49531         this.ablack = typeof(this.owner.ablack) != 'undefined' && this.owner.ablack ? this.owner.ablack :  Roo.HtmlEditorCore.ablack;
49532         this.tag_remove = typeof(this.owner.tag_remove) != 'undefined' && this.owner.tag_remove ? this.owner.tag_remove :  Roo.HtmlEditorCore.tag_remove;
49533         
49534         this.white = [];
49535         this.black = [];
49536         Roo.each(Roo.HtmlEditorCore.white, function(tag) {
49537             if (b.indexOf(tag) > -1) {
49538                 return;
49539             }
49540             this.white.push(tag);
49541             
49542         }, this);
49543         
49544         Roo.each(w, function(tag) {
49545             if (b.indexOf(tag) > -1) {
49546                 return;
49547             }
49548             if (this.white.indexOf(tag) > -1) {
49549                 return;
49550             }
49551             this.white.push(tag);
49552             
49553         }, this);
49554         
49555         
49556         Roo.each(Roo.HtmlEditorCore.black, function(tag) {
49557             if (w.indexOf(tag) > -1) {
49558                 return;
49559             }
49560             this.black.push(tag);
49561             
49562         }, this);
49563         
49564         Roo.each(b, function(tag) {
49565             if (w.indexOf(tag) > -1) {
49566                 return;
49567             }
49568             if (this.black.indexOf(tag) > -1) {
49569                 return;
49570             }
49571             this.black.push(tag);
49572             
49573         }, this);
49574         
49575         
49576         w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite  : [];
49577         b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack :  [];
49578         
49579         this.cwhite = [];
49580         this.cblack = [];
49581         Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
49582             if (b.indexOf(tag) > -1) {
49583                 return;
49584             }
49585             this.cwhite.push(tag);
49586             
49587         }, this);
49588         
49589         Roo.each(w, function(tag) {
49590             if (b.indexOf(tag) > -1) {
49591                 return;
49592             }
49593             if (this.cwhite.indexOf(tag) > -1) {
49594                 return;
49595             }
49596             this.cwhite.push(tag);
49597             
49598         }, this);
49599         
49600         
49601         Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
49602             if (w.indexOf(tag) > -1) {
49603                 return;
49604             }
49605             this.cblack.push(tag);
49606             
49607         }, this);
49608         
49609         Roo.each(b, function(tag) {
49610             if (w.indexOf(tag) > -1) {
49611                 return;
49612             }
49613             if (this.cblack.indexOf(tag) > -1) {
49614                 return;
49615             }
49616             this.cblack.push(tag);
49617             
49618         }, this);
49619     },
49620     
49621     setStylesheets : function(stylesheets)
49622     {
49623         if(typeof(stylesheets) == 'string'){
49624             Roo.get(this.iframe.contentDocument.head).createChild({
49625                 tag : 'link',
49626                 rel : 'stylesheet',
49627                 type : 'text/css',
49628                 href : stylesheets
49629             });
49630             
49631             return;
49632         }
49633         var _this = this;
49634      
49635         Roo.each(stylesheets, function(s) {
49636             if(!s.length){
49637                 return;
49638             }
49639             
49640             Roo.get(_this.iframe.contentDocument.head).createChild({
49641                 tag : 'link',
49642                 rel : 'stylesheet',
49643                 type : 'text/css',
49644                 href : s
49645             });
49646         });
49647
49648         
49649     },
49650     
49651     
49652     updateLanguage : function()
49653     {
49654         if (!this.iframe || !this.iframe.contentDocument) {
49655             return;
49656         }
49657         Roo.get(this.iframe.contentDocument.body).attr("lang", this.language);
49658     },
49659     
49660     
49661     removeStylesheets : function()
49662     {
49663         var _this = this;
49664         
49665         Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
49666             s.remove();
49667         });
49668     },
49669     
49670     setStyle : function(style)
49671     {
49672         Roo.get(this.iframe.contentDocument.head).createChild({
49673             tag : 'style',
49674             type : 'text/css',
49675             html : style
49676         });
49677
49678         return;
49679     }
49680     
49681     // hide stuff that is not compatible
49682     /**
49683      * @event blur
49684      * @hide
49685      */
49686     /**
49687      * @event change
49688      * @hide
49689      */
49690     /**
49691      * @event focus
49692      * @hide
49693      */
49694     /**
49695      * @event specialkey
49696      * @hide
49697      */
49698     /**
49699      * @cfg {String} fieldClass @hide
49700      */
49701     /**
49702      * @cfg {String} focusClass @hide
49703      */
49704     /**
49705      * @cfg {String} autoCreate @hide
49706      */
49707     /**
49708      * @cfg {String} inputType @hide
49709      */
49710     /**
49711      * @cfg {String} invalidClass @hide
49712      */
49713     /**
49714      * @cfg {String} invalidText @hide
49715      */
49716     /**
49717      * @cfg {String} msgFx @hide
49718      */
49719     /**
49720      * @cfg {String} validateOnBlur @hide
49721      */
49722 });
49723
49724 Roo.HtmlEditorCore.white = [
49725         'AREA', 'BR', 'IMG', 'INPUT', 'HR', 'WBR',
49726         
49727        'ADDRESS', 'BLOCKQUOTE', 'CENTER', 'DD',      'DIR',       'DIV', 
49728        'DL',      'DT',         'H1',     'H2',      'H3',        'H4', 
49729        'H5',      'H6',         'HR',     'ISINDEX', 'LISTING',   'MARQUEE', 
49730        'MENU',    'MULTICOL',   'OL',     'P',       'PLAINTEXT', 'PRE', 
49731        'TABLE',   'UL',         'XMP', 
49732        
49733        'CAPTION', 'COL', 'COLGROUP', 'TBODY', 'TD', 'TFOOT', 'TH', 
49734       'THEAD',   'TR', 
49735      
49736       'DIR', 'MENU', 'OL', 'UL', 'DL',
49737        
49738       'EMBED',  'OBJECT'
49739 ];
49740
49741
49742 Roo.HtmlEditorCore.black = [
49743     //    'embed',  'object', // enable - backend responsiblity to clean thiese
49744         'APPLET', // 
49745         'BASE',   'BASEFONT', 'BGSOUND', 'BLINK',  'BODY', 
49746         'FRAME',  'FRAMESET', 'HEAD',    'HTML',   'ILAYER', 
49747         'IFRAME', 'LAYER',  'LINK',     'META',    'OBJECT',   
49748         'SCRIPT', 'STYLE' ,'TITLE',  'XML',
49749         //'FONT' // CLEAN LATER..
49750         'COLGROUP', 'COL'  // messy tables.
49751         
49752 ];
49753 Roo.HtmlEditorCore.clean = [ // ?? needed???
49754      'SCRIPT', 'STYLE', 'TITLE', 'XML'
49755 ];
49756 Roo.HtmlEditorCore.tag_remove = [
49757     'FONT', 'TBODY'  
49758 ];
49759 // attributes..
49760
49761 Roo.HtmlEditorCore.ablack = [
49762     'on'
49763 ];
49764     
49765 Roo.HtmlEditorCore.aclean = [ 
49766     'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc' 
49767 ];
49768
49769 // protocols..
49770 Roo.HtmlEditorCore.pwhite= [
49771         'http',  'https',  'mailto'
49772 ];
49773
49774 // white listed style attributes.
49775 Roo.HtmlEditorCore.cwhite= [
49776       //  'text-align', /// default is to allow most things..
49777       
49778          
49779 //        'font-size'//??
49780 ];
49781
49782 // black listed style attributes.
49783 Roo.HtmlEditorCore.cblack= [
49784       //  'font-size' -- this can be set by the project 
49785 ];
49786
49787
49788
49789
49790     //<script type="text/javascript">
49791
49792 /*
49793  * Ext JS Library 1.1.1
49794  * Copyright(c) 2006-2007, Ext JS, LLC.
49795  * Licence LGPL
49796  * 
49797  */
49798  
49799  
49800 Roo.form.HtmlEditor = function(config){
49801     
49802     
49803     
49804     Roo.form.HtmlEditor.superclass.constructor.call(this, config);
49805     
49806     if (!this.toolbars) {
49807         this.toolbars = [];
49808     }
49809     this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
49810     
49811     
49812 };
49813
49814 /**
49815  * @class Roo.form.HtmlEditor
49816  * @extends Roo.form.Field
49817  * Provides a lightweight HTML Editor component.
49818  *
49819  * This has been tested on Fireforx / Chrome.. IE may not be so great..
49820  * 
49821  * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
49822  * supported by this editor.</b><br/><br/>
49823  * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
49824  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
49825  */
49826 Roo.extend(Roo.form.HtmlEditor, Roo.form.Field, {
49827     /**
49828      * @cfg {Boolean} clearUp
49829      */
49830     clearUp : true,
49831       /**
49832      * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
49833      */
49834     toolbars : false,
49835    
49836      /**
49837      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
49838      *                        Roo.resizable.
49839      */
49840     resizable : false,
49841      /**
49842      * @cfg {Number} height (in pixels)
49843      */   
49844     height: 300,
49845    /**
49846      * @cfg {Number} width (in pixels)
49847      */   
49848     width: 500,
49849     
49850     /**
49851      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets - this is usally a good idea  rootURL + '/roojs1/css/undoreset.css',   .
49852      * 
49853      */
49854     stylesheets: false,
49855     
49856     
49857      /**
49858      * @cfg {Array} blacklist of css styles style attributes (blacklist overrides whitelist)
49859      * 
49860      */
49861     cblack: false,
49862     /**
49863      * @cfg {Array} whitelist of css styles style attributes (blacklist overrides whitelist)
49864      * 
49865      */
49866     cwhite: false,
49867     
49868      /**
49869      * @cfg {Array} blacklist of html tags - in addition to standard blacklist.
49870      * 
49871      */
49872     black: false,
49873     /**
49874      * @cfg {Array} whitelist of html tags - in addition to statndard whitelist
49875      * 
49876      */
49877     white: false,
49878     /**
49879      * @cfg {boolean} allowComments - default false - allow comments in HTML source - by default they are stripped - if you are editing email you may need this.
49880      */
49881     allowComments: false,
49882     /**
49883      * @cfg {boolean} enableBlocks - default true - if the block editor (table and figure should be enabled)
49884      */
49885     enableBlocks : true,
49886     
49887     /**
49888      * @cfg {boolean} autoClean - default true - loading and saving will remove quite a bit of formating,
49889      *         if you are doing an email editor, this probably needs disabling, it's designed
49890      */
49891     autoClean: true,
49892     /**
49893      * @cfg {string} bodyCls- default '' default classes to add to body of editable area - usually undoreset is a good start..
49894      */
49895     bodyCls : '',
49896     /**
49897      * @cfg {String} language default en - language of text (usefull for rtl languages)
49898      * 
49899      */
49900     language: 'en',
49901     
49902      
49903     // id of frame..
49904     frameId: false,
49905     
49906     // private properties
49907     validationEvent : false,
49908     deferHeight: true,
49909     initialized : false,
49910     activated : false,
49911     
49912     onFocus : Roo.emptyFn,
49913     iframePad:3,
49914     hideMode:'offsets',
49915     
49916     actionMode : 'container', // defaults to hiding it...
49917     
49918     defaultAutoCreate : { // modified by initCompnoent..
49919         tag: "textarea",
49920         style:"width:500px;height:300px;",
49921         autocomplete: "new-password"
49922     },
49923
49924     // private
49925     initComponent : function(){
49926         this.addEvents({
49927             /**
49928              * @event initialize
49929              * Fires when the editor is fully initialized (including the iframe)
49930              * @param {HtmlEditor} this
49931              */
49932             initialize: true,
49933             /**
49934              * @event activate
49935              * Fires when the editor is first receives the focus. Any insertion must wait
49936              * until after this event.
49937              * @param {HtmlEditor} this
49938              */
49939             activate: true,
49940              /**
49941              * @event beforesync
49942              * Fires before the textarea is updated with content from the editor iframe. Return false
49943              * to cancel the sync.
49944              * @param {HtmlEditor} this
49945              * @param {String} html
49946              */
49947             beforesync: true,
49948              /**
49949              * @event beforepush
49950              * Fires before the iframe editor is updated with content from the textarea. Return false
49951              * to cancel the push.
49952              * @param {HtmlEditor} this
49953              * @param {String} html
49954              */
49955             beforepush: true,
49956              /**
49957              * @event sync
49958              * Fires when the textarea is updated with content from the editor iframe.
49959              * @param {HtmlEditor} this
49960              * @param {String} html
49961              */
49962             sync: true,
49963              /**
49964              * @event push
49965              * Fires when the iframe editor is updated with content from the textarea.
49966              * @param {HtmlEditor} this
49967              * @param {String} html
49968              */
49969             push: true,
49970              /**
49971              * @event editmodechange
49972              * Fires when the editor switches edit modes
49973              * @param {HtmlEditor} this
49974              * @param {Boolean} sourceEdit True if source edit, false if standard editing.
49975              */
49976             editmodechange: true,
49977             /**
49978              * @event editorevent
49979              * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
49980              * @param {HtmlEditor} this
49981              */
49982             editorevent: true,
49983             /**
49984              * @event firstfocus
49985              * Fires when on first focus - needed by toolbars..
49986              * @param {HtmlEditor} this
49987              */
49988             firstfocus: true,
49989             /**
49990              * @event autosave
49991              * Auto save the htmlEditor value as a file into Events
49992              * @param {HtmlEditor} this
49993              */
49994             autosave: true,
49995             /**
49996              * @event savedpreview
49997              * preview the saved version of htmlEditor
49998              * @param {HtmlEditor} this
49999              */
50000             savedpreview: true,
50001             
50002             /**
50003             * @event stylesheetsclick
50004             * Fires when press the Sytlesheets button
50005             * @param {Roo.HtmlEditorCore} this
50006             */
50007             stylesheetsclick: true,
50008             /**
50009             * @event paste
50010             * Fires when press user pastes into the editor
50011             * @param {Roo.HtmlEditorCore} this
50012             */
50013             paste: true 
50014         });
50015         this.defaultAutoCreate =  {
50016             tag: "textarea",
50017             style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
50018             autocomplete: "new-password"
50019         };
50020     },
50021
50022     /**
50023      * Protected method that will not generally be called directly. It
50024      * is called when the editor creates its toolbar. Override this method if you need to
50025      * add custom toolbar buttons.
50026      * @param {HtmlEditor} editor
50027      */
50028     createToolbar : function(editor){
50029         Roo.log("create toolbars");
50030         if (!editor.toolbars || !editor.toolbars.length) {
50031             editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
50032         }
50033         
50034         for (var i =0 ; i < editor.toolbars.length;i++) {
50035             editor.toolbars[i] = Roo.factory(
50036                     typeof(editor.toolbars[i]) == 'string' ?
50037                         { xtype: editor.toolbars[i]} : editor.toolbars[i],
50038                 Roo.form.HtmlEditor);
50039             editor.toolbars[i].init(editor);
50040         }
50041          
50042         
50043     },
50044     /**
50045      * get the Context selected node
50046      * @returns {DomElement|boolean} selected node if active or false if none
50047      * 
50048      */
50049     getSelectedNode : function()
50050     {
50051         if (this.toolbars.length < 2 || !this.toolbars[1].tb) {
50052             return false;
50053         }
50054         return this.toolbars[1].tb.selectedNode;
50055     
50056     },
50057     // private
50058     onRender : function(ct, position)
50059     {
50060         var _t = this;
50061         Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
50062         
50063         this.wrap = this.el.wrap({
50064             cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
50065         });
50066         
50067         this.editorcore.onRender(ct, position);
50068          
50069         if (this.resizable) {
50070             this.resizeEl = new Roo.Resizable(this.wrap, {
50071                 pinned : true,
50072                 wrap: true,
50073                 dynamic : true,
50074                 minHeight : this.height,
50075                 height: this.height,
50076                 handles : this.resizable,
50077                 width: this.width,
50078                 listeners : {
50079                     resize : function(r, w, h) {
50080                         _t.onResize(w,h); // -something
50081                     }
50082                 }
50083             });
50084             
50085         }
50086         this.createToolbar(this);
50087        
50088         
50089         if(!this.width){
50090             this.setSize(this.wrap.getSize());
50091         }
50092         if (this.resizeEl) {
50093             this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
50094             // should trigger onReize..
50095         }
50096         
50097         this.keyNav = new Roo.KeyNav(this.el, {
50098             
50099             "tab" : function(e){
50100                 e.preventDefault();
50101                 
50102                 var value = this.getValue();
50103                 
50104                 var start = this.el.dom.selectionStart;
50105                 var end = this.el.dom.selectionEnd;
50106                 
50107                 if(!e.shiftKey){
50108                     
50109                     this.setValue(value.substring(0, start) + "\t" + value.substring(end));
50110                     this.el.dom.setSelectionRange(end + 1, end + 1);
50111                     return;
50112                 }
50113                 
50114                 var f = value.substring(0, start).split("\t");
50115                 
50116                 if(f.pop().length != 0){
50117                     return;
50118                 }
50119                 
50120                 this.setValue(f.join("\t") + value.substring(end));
50121                 this.el.dom.setSelectionRange(start - 1, start - 1);
50122                 
50123             },
50124             
50125             "home" : function(e){
50126                 e.preventDefault();
50127                 
50128                 var curr = this.el.dom.selectionStart;
50129                 var lines = this.getValue().split("\n");
50130                 
50131                 if(!lines.length){
50132                     return;
50133                 }
50134                 
50135                 if(e.ctrlKey){
50136                     this.el.dom.setSelectionRange(0, 0);
50137                     return;
50138                 }
50139                 
50140                 var pos = 0;
50141                 
50142                 for (var i = 0; i < lines.length;i++) {
50143                     pos += lines[i].length;
50144                     
50145                     if(i != 0){
50146                         pos += 1;
50147                     }
50148                     
50149                     if(pos < curr){
50150                         continue;
50151                     }
50152                     
50153                     pos -= lines[i].length;
50154                     
50155                     break;
50156                 }
50157                 
50158                 if(!e.shiftKey){
50159                     this.el.dom.setSelectionRange(pos, pos);
50160                     return;
50161                 }
50162                 
50163                 this.el.dom.selectionStart = pos;
50164                 this.el.dom.selectionEnd = curr;
50165             },
50166             
50167             "end" : function(e){
50168                 e.preventDefault();
50169                 
50170                 var curr = this.el.dom.selectionStart;
50171                 var lines = this.getValue().split("\n");
50172                 
50173                 if(!lines.length){
50174                     return;
50175                 }
50176                 
50177                 if(e.ctrlKey){
50178                     this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
50179                     return;
50180                 }
50181                 
50182                 var pos = 0;
50183                 
50184                 for (var i = 0; i < lines.length;i++) {
50185                     
50186                     pos += lines[i].length;
50187                     
50188                     if(i != 0){
50189                         pos += 1;
50190                     }
50191                     
50192                     if(pos < curr){
50193                         continue;
50194                     }
50195                     
50196                     break;
50197                 }
50198                 
50199                 if(!e.shiftKey){
50200                     this.el.dom.setSelectionRange(pos, pos);
50201                     return;
50202                 }
50203                 
50204                 this.el.dom.selectionStart = curr;
50205                 this.el.dom.selectionEnd = pos;
50206             },
50207
50208             scope : this,
50209
50210             doRelay : function(foo, bar, hname){
50211                 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
50212             },
50213
50214             forceKeyDown: true
50215         });
50216         
50217 //        if(this.autosave && this.w){
50218 //            this.autoSaveFn = setInterval(this.autosave, 1000);
50219 //        }
50220     },
50221
50222     // private
50223     onResize : function(w, h)
50224     {
50225         Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
50226         var ew = false;
50227         var eh = false;
50228         
50229         if(this.el ){
50230             if(typeof w == 'number'){
50231                 var aw = w - this.wrap.getFrameWidth('lr');
50232                 this.el.setWidth(this.adjustWidth('textarea', aw));
50233                 ew = aw;
50234             }
50235             if(typeof h == 'number'){
50236                 var tbh = 0;
50237                 for (var i =0; i < this.toolbars.length;i++) {
50238                     // fixme - ask toolbars for heights?
50239                     tbh += this.toolbars[i].tb.el.getHeight();
50240                     if (this.toolbars[i].footer) {
50241                         tbh += this.toolbars[i].footer.el.getHeight();
50242                     }
50243                 }
50244                 
50245                 
50246                 
50247                 
50248                 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
50249                 ah -= 5; // knock a few pixes off for look..
50250 //                Roo.log(ah);
50251                 this.el.setHeight(this.adjustWidth('textarea', ah));
50252                 var eh = ah;
50253             }
50254         }
50255         Roo.log('onResize:' + [w,h,ew,eh].join(',') );
50256         this.editorcore.onResize(ew,eh);
50257         
50258     },
50259
50260     /**
50261      * Toggles the editor between standard and source edit mode.
50262      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
50263      */
50264     toggleSourceEdit : function(sourceEditMode)
50265     {
50266         this.editorcore.toggleSourceEdit(sourceEditMode);
50267         
50268         if(this.editorcore.sourceEditMode){
50269             Roo.log('editor - showing textarea');
50270             
50271 //            Roo.log('in');
50272 //            Roo.log(this.syncValue());
50273             this.editorcore.syncValue();
50274             this.el.removeClass('x-hidden');
50275             this.el.dom.removeAttribute('tabIndex');
50276             this.el.focus();
50277             this.el.dom.scrollTop = 0;
50278             
50279             
50280             for (var i = 0; i < this.toolbars.length; i++) {
50281                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
50282                     this.toolbars[i].tb.hide();
50283                     this.toolbars[i].footer.hide();
50284                 }
50285             }
50286             
50287         }else{
50288             Roo.log('editor - hiding textarea');
50289 //            Roo.log('out')
50290 //            Roo.log(this.pushValue()); 
50291             this.editorcore.pushValue();
50292             
50293             this.el.addClass('x-hidden');
50294             this.el.dom.setAttribute('tabIndex', -1);
50295             
50296             for (var i = 0; i < this.toolbars.length; i++) {
50297                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
50298                     this.toolbars[i].tb.show();
50299                     this.toolbars[i].footer.show();
50300                 }
50301             }
50302             
50303             //this.deferFocus();
50304         }
50305         
50306         this.setSize(this.wrap.getSize());
50307         this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
50308         
50309         this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
50310     },
50311  
50312     // private (for BoxComponent)
50313     adjustSize : Roo.BoxComponent.prototype.adjustSize,
50314
50315     // private (for BoxComponent)
50316     getResizeEl : function(){
50317         return this.wrap;
50318     },
50319
50320     // private (for BoxComponent)
50321     getPositionEl : function(){
50322         return this.wrap;
50323     },
50324
50325     // private
50326     initEvents : function(){
50327         this.originalValue = this.getValue();
50328     },
50329
50330     /**
50331      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
50332      * @method
50333      */
50334     markInvalid : Roo.emptyFn,
50335     /**
50336      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
50337      * @method
50338      */
50339     clearInvalid : Roo.emptyFn,
50340
50341     setValue : function(v){
50342         Roo.form.HtmlEditor.superclass.setValue.call(this, v);
50343         this.editorcore.pushValue();
50344     },
50345
50346     /**
50347      * update the language in the body - really done by core
50348      * @param {String} language - eg. en / ar / zh-CN etc..
50349      */
50350     updateLanguage : function(lang)
50351     {
50352         this.language = lang;
50353         this.editorcore.language = lang;
50354         this.editorcore.updateLanguage();
50355      
50356     },
50357     // private
50358     deferFocus : function(){
50359         this.focus.defer(10, this);
50360     },
50361
50362     // doc'ed in Field
50363     focus : function(){
50364         this.editorcore.focus();
50365         
50366     },
50367       
50368
50369     // private
50370     onDestroy : function(){
50371         
50372         
50373         
50374         if(this.rendered){
50375             
50376             for (var i =0; i < this.toolbars.length;i++) {
50377                 // fixme - ask toolbars for heights?
50378                 this.toolbars[i].onDestroy();
50379             }
50380             
50381             this.wrap.dom.innerHTML = '';
50382             this.wrap.remove();
50383         }
50384     },
50385
50386     // private
50387     onFirstFocus : function(){
50388         //Roo.log("onFirstFocus");
50389         this.editorcore.onFirstFocus();
50390          for (var i =0; i < this.toolbars.length;i++) {
50391             this.toolbars[i].onFirstFocus();
50392         }
50393         
50394     },
50395     
50396     // private
50397     syncValue : function()
50398     {
50399         this.editorcore.syncValue();
50400     },
50401     
50402     pushValue : function()
50403     {
50404         this.editorcore.pushValue();
50405     },
50406     
50407     setStylesheets : function(stylesheets)
50408     {
50409         this.editorcore.setStylesheets(stylesheets);
50410     },
50411     
50412     removeStylesheets : function()
50413     {
50414         this.editorcore.removeStylesheets();
50415     }
50416      
50417     
50418     // hide stuff that is not compatible
50419     /**
50420      * @event blur
50421      * @hide
50422      */
50423     /**
50424      * @event change
50425      * @hide
50426      */
50427     /**
50428      * @event focus
50429      * @hide
50430      */
50431     /**
50432      * @event specialkey
50433      * @hide
50434      */
50435     /**
50436      * @cfg {String} fieldClass @hide
50437      */
50438     /**
50439      * @cfg {String} focusClass @hide
50440      */
50441     /**
50442      * @cfg {String} autoCreate @hide
50443      */
50444     /**
50445      * @cfg {String} inputType @hide
50446      */
50447     /**
50448      * @cfg {String} invalidClass @hide
50449      */
50450     /**
50451      * @cfg {String} invalidText @hide
50452      */
50453     /**
50454      * @cfg {String} msgFx @hide
50455      */
50456     /**
50457      * @cfg {String} validateOnBlur @hide
50458      */
50459 });
50460  
50461     // <script type="text/javascript">
50462 /*
50463  * Based on
50464  * Ext JS Library 1.1.1
50465  * Copyright(c) 2006-2007, Ext JS, LLC.
50466  *  
50467  
50468  */
50469
50470 /**
50471  * @class Roo.form.HtmlEditorToolbar1
50472  * Basic Toolbar
50473  * 
50474  * Usage:
50475  *
50476  new Roo.form.HtmlEditor({
50477     ....
50478     toolbars : [
50479         new Roo.form.HtmlEditorToolbar1({
50480             disable : { fonts: 1 , format: 1, ..., ... , ...],
50481             btns : [ .... ]
50482         })
50483     }
50484      
50485  * 
50486  * @cfg {Object} disable List of elements to disable..
50487  * @cfg {Array} btns List of additional buttons.
50488  * 
50489  * 
50490  * NEEDS Extra CSS? 
50491  * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
50492  */
50493  
50494 Roo.form.HtmlEditor.ToolbarStandard = function(config)
50495 {
50496     
50497     Roo.apply(this, config);
50498     
50499     // default disabled, based on 'good practice'..
50500     this.disable = this.disable || {};
50501     Roo.applyIf(this.disable, {
50502         fontSize : true,
50503         colors : true,
50504         specialElements : true
50505     });
50506     
50507     
50508     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
50509     // dont call parent... till later.
50510 }
50511
50512 Roo.apply(Roo.form.HtmlEditor.ToolbarStandard.prototype,  {
50513     
50514     tb: false,
50515     
50516     rendered: false,
50517     
50518     editor : false,
50519     editorcore : false,
50520     /**
50521      * @cfg {Object} disable  List of toolbar elements to disable
50522          
50523      */
50524     disable : false,
50525     
50526     
50527      /**
50528      * @cfg {String} createLinkText The default text for the create link prompt
50529      */
50530     createLinkText : 'Please enter the URL for the link:',
50531     /**
50532      * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
50533      */
50534     defaultLinkValue : 'http:/'+'/',
50535    
50536     
50537       /**
50538      * @cfg {Array} fontFamilies An array of available font families
50539      */
50540     fontFamilies : [
50541         'Arial',
50542         'Courier New',
50543         'Tahoma',
50544         'Times New Roman',
50545         'Verdana'
50546     ],
50547     
50548     specialChars : [
50549            "&#169;",
50550           "&#174;",     
50551           "&#8482;",    
50552           "&#163;" ,    
50553          // "&#8212;",    
50554           "&#8230;",    
50555           "&#247;" ,    
50556         //  "&#225;" ,     ?? a acute?
50557            "&#8364;"    , //Euro
50558        //   "&#8220;"    ,
50559         //  "&#8221;"    ,
50560         //  "&#8226;"    ,
50561           "&#176;"  //   , // degrees
50562
50563          // "&#233;"     , // e ecute
50564          // "&#250;"     , // u ecute?
50565     ],
50566     
50567     specialElements : [
50568         {
50569             text: "Insert Table",
50570             xtype: 'MenuItem',
50571             xns : Roo.Menu,
50572             ihtml :  '<table><tr><td>Cell</td></tr></table>' 
50573                 
50574         },
50575         {    
50576             text: "Insert Image",
50577             xtype: 'MenuItem',
50578             xns : Roo.Menu,
50579             ihtml : '<img src="about:blank"/>'
50580             
50581         }
50582         
50583          
50584     ],
50585     
50586     
50587     inputElements : [ 
50588             "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password", 
50589             "input:submit", "input:button", "select", "textarea", "label" ],
50590     formats : [
50591         ["p"] ,  
50592         ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"], 
50593         ["pre"],[ "code"], 
50594         ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
50595         ['div'],['span'],
50596         ['sup'],['sub']
50597     ],
50598     
50599     cleanStyles : [
50600         "font-size"
50601     ],
50602      /**
50603      * @cfg {String} defaultFont default font to use.
50604      */
50605     defaultFont: 'tahoma',
50606    
50607     fontSelect : false,
50608     
50609     
50610     formatCombo : false,
50611     
50612     init : function(editor)
50613     {
50614         this.editor = editor;
50615         this.editorcore = editor.editorcore ? editor.editorcore : editor;
50616         var editorcore = this.editorcore;
50617         
50618         var _t = this;
50619         
50620         var fid = editorcore.frameId;
50621         var etb = this;
50622         function btn(id, toggle, handler){
50623             var xid = fid + '-'+ id ;
50624             return {
50625                 id : xid,
50626                 cmd : id,
50627                 cls : 'x-btn-icon x-edit-'+id,
50628                 enableToggle:toggle !== false,
50629                 scope: _t, // was editor...
50630                 handler:handler||_t.relayBtnCmd,
50631                 clickEvent:'mousedown',
50632                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
50633                 tabIndex:-1
50634             };
50635         }
50636         
50637         
50638         
50639         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
50640         this.tb = tb;
50641          // stop form submits
50642         tb.el.on('click', function(e){
50643             e.preventDefault(); // what does this do?
50644         });
50645
50646         if(!this.disable.font) { // && !Roo.isSafari){
50647             /* why no safari for fonts 
50648             editor.fontSelect = tb.el.createChild({
50649                 tag:'select',
50650                 tabIndex: -1,
50651                 cls:'x-font-select',
50652                 html: this.createFontOptions()
50653             });
50654             
50655             editor.fontSelect.on('change', function(){
50656                 var font = editor.fontSelect.dom.value;
50657                 editor.relayCmd('fontname', font);
50658                 editor.deferFocus();
50659             }, editor);
50660             
50661             tb.add(
50662                 editor.fontSelect.dom,
50663                 '-'
50664             );
50665             */
50666             
50667         };
50668         if(!this.disable.formats){
50669             this.formatCombo = new Roo.form.ComboBox({
50670                 store: new Roo.data.SimpleStore({
50671                     id : 'tag',
50672                     fields: ['tag'],
50673                     data : this.formats // from states.js
50674                 }),
50675                 blockFocus : true,
50676                 name : '',
50677                 //autoCreate : {tag: "div",  size: "20"},
50678                 displayField:'tag',
50679                 typeAhead: false,
50680                 mode: 'local',
50681                 editable : false,
50682                 triggerAction: 'all',
50683                 emptyText:'Add tag',
50684                 selectOnFocus:true,
50685                 width:135,
50686                 listeners : {
50687                     'select': function(c, r, i) {
50688                         editorcore.insertTag(r.get('tag'));
50689                         editor.focus();
50690                     }
50691                 }
50692
50693             });
50694             tb.addField(this.formatCombo);
50695             
50696         }
50697         
50698         if(!this.disable.format){
50699             tb.add(
50700                 btn('bold'),
50701                 btn('italic'),
50702                 btn('underline'),
50703                 btn('strikethrough')
50704             );
50705         };
50706         if(!this.disable.fontSize){
50707             tb.add(
50708                 '-',
50709                 
50710                 
50711                 btn('increasefontsize', false, editorcore.adjustFont),
50712                 btn('decreasefontsize', false, editorcore.adjustFont)
50713             );
50714         };
50715         
50716         
50717         if(!this.disable.colors){
50718             tb.add(
50719                 '-', {
50720                     id:editorcore.frameId +'-forecolor',
50721                     cls:'x-btn-icon x-edit-forecolor',
50722                     clickEvent:'mousedown',
50723                     tooltip: this.buttonTips['forecolor'] || undefined,
50724                     tabIndex:-1,
50725                     menu : new Roo.menu.ColorMenu({
50726                         allowReselect: true,
50727                         focus: Roo.emptyFn,
50728                         value:'000000',
50729                         plain:true,
50730                         selectHandler: function(cp, color){
50731                             editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
50732                             editor.deferFocus();
50733                         },
50734                         scope: editorcore,
50735                         clickEvent:'mousedown'
50736                     })
50737                 }, {
50738                     id:editorcore.frameId +'backcolor',
50739                     cls:'x-btn-icon x-edit-backcolor',
50740                     clickEvent:'mousedown',
50741                     tooltip: this.buttonTips['backcolor'] || undefined,
50742                     tabIndex:-1,
50743                     menu : new Roo.menu.ColorMenu({
50744                         focus: Roo.emptyFn,
50745                         value:'FFFFFF',
50746                         plain:true,
50747                         allowReselect: true,
50748                         selectHandler: function(cp, color){
50749                             if(Roo.isGecko){
50750                                 editorcore.execCmd('useCSS', false);
50751                                 editorcore.execCmd('hilitecolor', color);
50752                                 editorcore.execCmd('useCSS', true);
50753                                 editor.deferFocus();
50754                             }else{
50755                                 editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor', 
50756                                     Roo.isSafari || Roo.isIE ? '#'+color : color);
50757                                 editor.deferFocus();
50758                             }
50759                         },
50760                         scope:editorcore,
50761                         clickEvent:'mousedown'
50762                     })
50763                 }
50764             );
50765         };
50766         // now add all the items...
50767         
50768
50769         if(!this.disable.alignments){
50770             tb.add(
50771                 '-',
50772                 btn('justifyleft'),
50773                 btn('justifycenter'),
50774                 btn('justifyright')
50775             );
50776         };
50777
50778         //if(!Roo.isSafari){
50779             if(!this.disable.links){
50780                 tb.add(
50781                     '-',
50782                     btn('createlink', false, this.createLink)    /// MOVE TO HERE?!!?!?!?!
50783                 );
50784             };
50785
50786             if(!this.disable.lists){
50787                 tb.add(
50788                     '-',
50789                     btn('insertorderedlist'),
50790                     btn('insertunorderedlist')
50791                 );
50792             }
50793             if(!this.disable.sourceEdit){
50794                 tb.add(
50795                     '-',
50796                     btn('sourceedit', true, function(btn){
50797                         this.toggleSourceEdit(btn.pressed);
50798                     })
50799                 );
50800             }
50801         //}
50802         
50803         var smenu = { };
50804         // special menu.. - needs to be tidied up..
50805         if (!this.disable.special) {
50806             smenu = {
50807                 text: "&#169;",
50808                 cls: 'x-edit-none',
50809                 
50810                 menu : {
50811                     items : []
50812                 }
50813             };
50814             for (var i =0; i < this.specialChars.length; i++) {
50815                 smenu.menu.items.push({
50816                     
50817                     html: this.specialChars[i],
50818                     handler: function(a,b) {
50819                         editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
50820                         //editor.insertAtCursor(a.html);
50821                         
50822                     },
50823                     tabIndex:-1
50824                 });
50825             }
50826             
50827             
50828             tb.add(smenu);
50829             
50830             
50831         }
50832         
50833         var cmenu = { };
50834         if (!this.disable.cleanStyles) {
50835             cmenu = {
50836                 cls: 'x-btn-icon x-btn-clear',
50837                 
50838                 menu : {
50839                     items : []
50840                 }
50841             };
50842             for (var i =0; i < this.cleanStyles.length; i++) {
50843                 cmenu.menu.items.push({
50844                     actiontype : this.cleanStyles[i],
50845                     html: 'Remove ' + this.cleanStyles[i],
50846                     handler: function(a,b) {
50847 //                        Roo.log(a);
50848 //                        Roo.log(b);
50849                         var c = Roo.get(editorcore.doc.body);
50850                         c.select('[style]').each(function(s) {
50851                             s.dom.style.removeProperty(a.actiontype);
50852                         });
50853                         editorcore.syncValue();
50854                     },
50855                     tabIndex:-1
50856                 });
50857             }
50858             cmenu.menu.items.push({
50859                 actiontype : 'tablewidths',
50860                 html: 'Remove Table Widths',
50861                 handler: function(a,b) {
50862                     editorcore.cleanTableWidths();
50863                     editorcore.syncValue();
50864                 },
50865                 tabIndex:-1
50866             });
50867             cmenu.menu.items.push({
50868                 actiontype : 'word',
50869                 html: 'Remove MS Word Formating',
50870                 handler: function(a,b) {
50871                     editorcore.cleanWord();
50872                     editorcore.syncValue();
50873                 },
50874                 tabIndex:-1
50875             });
50876             
50877             cmenu.menu.items.push({
50878                 actiontype : 'all',
50879                 html: 'Remove All Styles',
50880                 handler: function(a,b) {
50881                     
50882                     var c = Roo.get(editorcore.doc.body);
50883                     c.select('[style]').each(function(s) {
50884                         s.dom.removeAttribute('style');
50885                     });
50886                     editorcore.syncValue();
50887                 },
50888                 tabIndex:-1
50889             });
50890             
50891             cmenu.menu.items.push({
50892                 actiontype : 'all',
50893                 html: 'Remove All CSS Classes',
50894                 handler: function(a,b) {
50895                     
50896                     var c = Roo.get(editorcore.doc.body);
50897                     c.select('[class]').each(function(s) {
50898                         s.dom.removeAttribute('class');
50899                     });
50900                     editorcore.cleanWord();
50901                     editorcore.syncValue();
50902                 },
50903                 tabIndex:-1
50904             });
50905             
50906              cmenu.menu.items.push({
50907                 actiontype : 'tidy',
50908                 html: 'Tidy HTML Source',
50909                 handler: function(a,b) {
50910                     new Roo.htmleditor.Tidy(editorcore.doc.body);
50911                     editorcore.syncValue();
50912                 },
50913                 tabIndex:-1
50914             });
50915             
50916             
50917             tb.add(cmenu);
50918         }
50919          
50920         if (!this.disable.specialElements) {
50921             var semenu = {
50922                 text: "Other;",
50923                 cls: 'x-edit-none',
50924                 menu : {
50925                     items : []
50926                 }
50927             };
50928             for (var i =0; i < this.specialElements.length; i++) {
50929                 semenu.menu.items.push(
50930                     Roo.apply({ 
50931                         handler: function(a,b) {
50932                             editor.insertAtCursor(this.ihtml);
50933                         }
50934                     }, this.specialElements[i])
50935                 );
50936                     
50937             }
50938             
50939             tb.add(semenu);
50940             
50941             
50942         }
50943          
50944         
50945         if (this.btns) {
50946             for(var i =0; i< this.btns.length;i++) {
50947                 var b = Roo.factory(this.btns[i],this.btns[i].xns || Roo.form);
50948                 b.cls =  'x-edit-none';
50949                 
50950                 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
50951                     b.cls += ' x-init-enable';
50952                 }
50953                 
50954                 b.scope = editorcore;
50955                 tb.add(b);
50956             }
50957         
50958         }
50959         
50960         
50961         
50962         // disable everything...
50963         
50964         this.tb.items.each(function(item){
50965             
50966            if(
50967                 item.id != editorcore.frameId+ '-sourceedit' && 
50968                 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
50969             ){
50970                 
50971                 item.disable();
50972             }
50973         });
50974         this.rendered = true;
50975         
50976         // the all the btns;
50977         editor.on('editorevent', this.updateToolbar, this);
50978         // other toolbars need to implement this..
50979         //editor.on('editmodechange', this.updateToolbar, this);
50980     },
50981     
50982     
50983     relayBtnCmd : function(btn) {
50984         this.editorcore.relayCmd(btn.cmd);
50985     },
50986     // private used internally
50987     createLink : function(){
50988         Roo.log("create link?");
50989         var ec = this.editorcore;
50990         Roo.MessageBox.prompt("Add Link URL",this.createLinkText, function(url) {
50991             if(url && url != 'http:/'+'/'){
50992                 ec.relayCmd('createlink', url);
50993             }
50994         });
50995         
50996     },
50997
50998     
50999     /**
51000      * Protected method that will not generally be called directly. It triggers
51001      * a toolbar update by reading the markup state of the current selection in the editor.
51002      */
51003     updateToolbar: function(){
51004
51005         if(!this.editorcore.activated){
51006             this.editor.onFirstFocus();
51007             return;
51008         }
51009
51010         var btns = this.tb.items.map, 
51011             doc = this.editorcore.doc,
51012             frameId = this.editorcore.frameId;
51013
51014         if(!this.disable.font && !Roo.isSafari){
51015             /*
51016             var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
51017             if(name != this.fontSelect.dom.value){
51018                 this.fontSelect.dom.value = name;
51019             }
51020             */
51021         }
51022         if(!this.disable.format){
51023             btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
51024             btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
51025             btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
51026             btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
51027         }
51028         if(!this.disable.alignments){
51029             btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
51030             btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
51031             btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
51032         }
51033         if(!Roo.isSafari && !this.disable.lists){
51034             btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
51035             btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
51036         }
51037         
51038         var ans = this.editorcore.getAllAncestors();
51039         if (this.formatCombo) {
51040             
51041             
51042             var store = this.formatCombo.store;
51043             this.formatCombo.setValue("");
51044             for (var i =0; i < ans.length;i++) {
51045                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
51046                     // select it..
51047                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
51048                     break;
51049                 }
51050             }
51051         }
51052         
51053         
51054         
51055         // hides menus... - so this cant be on a menu...
51056         Roo.menu.MenuMgr.hideAll();
51057
51058         //this.editorsyncValue();
51059     },
51060    
51061     
51062     createFontOptions : function(){
51063         var buf = [], fs = this.fontFamilies, ff, lc;
51064         
51065         
51066         
51067         for(var i = 0, len = fs.length; i< len; i++){
51068             ff = fs[i];
51069             lc = ff.toLowerCase();
51070             buf.push(
51071                 '<option value="',lc,'" style="font-family:',ff,';"',
51072                     (this.defaultFont == lc ? ' selected="true">' : '>'),
51073                     ff,
51074                 '</option>'
51075             );
51076         }
51077         return buf.join('');
51078     },
51079     
51080     toggleSourceEdit : function(sourceEditMode){
51081         
51082         Roo.log("toolbar toogle");
51083         if(sourceEditMode === undefined){
51084             sourceEditMode = !this.sourceEditMode;
51085         }
51086         this.sourceEditMode = sourceEditMode === true;
51087         var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
51088         // just toggle the button?
51089         if(btn.pressed !== this.sourceEditMode){
51090             btn.toggle(this.sourceEditMode);
51091             return;
51092         }
51093         
51094         if(sourceEditMode){
51095             Roo.log("disabling buttons");
51096             this.tb.items.each(function(item){
51097                 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
51098                     item.disable();
51099                 }
51100             });
51101           
51102         }else{
51103             Roo.log("enabling buttons");
51104             if(this.editorcore.initialized){
51105                 this.tb.items.each(function(item){
51106                     item.enable();
51107                 });
51108                 // initialize 'blocks'
51109                 Roo.each(Roo.get(this.editorcore.doc.body).query('*[data-block]'), function(e) {
51110                     Roo.htmleditor.Block.factory(e).updateElement(e);
51111                 },this);
51112             
51113             }
51114             
51115         }
51116         Roo.log("calling toggole on editor");
51117         // tell the editor that it's been pressed..
51118         this.editor.toggleSourceEdit(sourceEditMode);
51119        
51120     },
51121      /**
51122      * Object collection of toolbar tooltips for the buttons in the editor. The key
51123      * is the command id associated with that button and the value is a valid QuickTips object.
51124      * For example:
51125 <pre><code>
51126 {
51127     bold : {
51128         title: 'Bold (Ctrl+B)',
51129         text: 'Make the selected text bold.',
51130         cls: 'x-html-editor-tip'
51131     },
51132     italic : {
51133         title: 'Italic (Ctrl+I)',
51134         text: 'Make the selected text italic.',
51135         cls: 'x-html-editor-tip'
51136     },
51137     ...
51138 </code></pre>
51139     * @type Object
51140      */
51141     buttonTips : {
51142         bold : {
51143             title: 'Bold (Ctrl+B)',
51144             text: 'Make the selected text bold.',
51145             cls: 'x-html-editor-tip'
51146         },
51147         italic : {
51148             title: 'Italic (Ctrl+I)',
51149             text: 'Make the selected text italic.',
51150             cls: 'x-html-editor-tip'
51151         },
51152         underline : {
51153             title: 'Underline (Ctrl+U)',
51154             text: 'Underline the selected text.',
51155             cls: 'x-html-editor-tip'
51156         },
51157         strikethrough : {
51158             title: 'Strikethrough',
51159             text: 'Strikethrough the selected text.',
51160             cls: 'x-html-editor-tip'
51161         },
51162         increasefontsize : {
51163             title: 'Grow Text',
51164             text: 'Increase the font size.',
51165             cls: 'x-html-editor-tip'
51166         },
51167         decreasefontsize : {
51168             title: 'Shrink Text',
51169             text: 'Decrease the font size.',
51170             cls: 'x-html-editor-tip'
51171         },
51172         backcolor : {
51173             title: 'Text Highlight Color',
51174             text: 'Change the background color of the selected text.',
51175             cls: 'x-html-editor-tip'
51176         },
51177         forecolor : {
51178             title: 'Font Color',
51179             text: 'Change the color of the selected text.',
51180             cls: 'x-html-editor-tip'
51181         },
51182         justifyleft : {
51183             title: 'Align Text Left',
51184             text: 'Align text to the left.',
51185             cls: 'x-html-editor-tip'
51186         },
51187         justifycenter : {
51188             title: 'Center Text',
51189             text: 'Center text in the editor.',
51190             cls: 'x-html-editor-tip'
51191         },
51192         justifyright : {
51193             title: 'Align Text Right',
51194             text: 'Align text to the right.',
51195             cls: 'x-html-editor-tip'
51196         },
51197         insertunorderedlist : {
51198             title: 'Bullet List',
51199             text: 'Start a bulleted list.',
51200             cls: 'x-html-editor-tip'
51201         },
51202         insertorderedlist : {
51203             title: 'Numbered List',
51204             text: 'Start a numbered list.',
51205             cls: 'x-html-editor-tip'
51206         },
51207         createlink : {
51208             title: 'Hyperlink',
51209             text: 'Make the selected text a hyperlink.',
51210             cls: 'x-html-editor-tip'
51211         },
51212         sourceedit : {
51213             title: 'Source Edit',
51214             text: 'Switch to source editing mode.',
51215             cls: 'x-html-editor-tip'
51216         }
51217     },
51218     // private
51219     onDestroy : function(){
51220         if(this.rendered){
51221             
51222             this.tb.items.each(function(item){
51223                 if(item.menu){
51224                     item.menu.removeAll();
51225                     if(item.menu.el){
51226                         item.menu.el.destroy();
51227                     }
51228                 }
51229                 item.destroy();
51230             });
51231              
51232         }
51233     },
51234     onFirstFocus: function() {
51235         this.tb.items.each(function(item){
51236            item.enable();
51237         });
51238     }
51239 });
51240
51241
51242
51243
51244 // <script type="text/javascript">
51245 /*
51246  * Based on
51247  * Ext JS Library 1.1.1
51248  * Copyright(c) 2006-2007, Ext JS, LLC.
51249  *  
51250  
51251  */
51252
51253  
51254 /**
51255  * @class Roo.form.HtmlEditor.ToolbarContext
51256  * Context Toolbar
51257  * 
51258  * Usage:
51259  *
51260  new Roo.form.HtmlEditor({
51261     ....
51262     toolbars : [
51263         { xtype: 'ToolbarStandard', styles : {} }
51264         { xtype: 'ToolbarContext', disable : {} }
51265     ]
51266 })
51267
51268      
51269  * 
51270  * @config : {Object} disable List of elements to disable.. (not done yet.)
51271  * @config : {Object} styles  Map of styles available.
51272  * 
51273  */
51274
51275 Roo.form.HtmlEditor.ToolbarContext = function(config)
51276 {
51277     
51278     Roo.apply(this, config);
51279     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
51280     // dont call parent... till later.
51281     this.styles = this.styles || {};
51282 }
51283
51284  
51285
51286 Roo.form.HtmlEditor.ToolbarContext.types = {
51287     'IMG' : [
51288         {
51289             name : 'width',
51290             title: "Width",
51291             width: 40
51292         },
51293         {
51294             name : 'height',
51295             title: "Height",
51296             width: 40
51297         },
51298         {
51299             name : 'align',
51300             title: "Align",
51301             opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
51302             width : 80
51303             
51304         },
51305         {
51306             name : 'border',
51307             title: "Border",
51308             width: 40
51309         },
51310         {
51311             name : 'alt',
51312             title: "Alt",
51313             width: 120
51314         },
51315         {
51316             name : 'src',
51317             title: "Src",
51318             width: 220
51319         }
51320         
51321     ],
51322     
51323     'FIGURE' : [
51324         {
51325             name : 'align',
51326             title: "Align",
51327             opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
51328             width : 80  
51329         }
51330     ],
51331     'A' : [
51332         {
51333             name : 'name',
51334             title: "Name",
51335             width: 50
51336         },
51337         {
51338             name : 'target',
51339             title: "Target",
51340             width: 120
51341         },
51342         {
51343             name : 'href',
51344             title: "Href",
51345             width: 220
51346         } // border?
51347         
51348     ],
51349     
51350     'INPUT' : [
51351         {
51352             name : 'name',
51353             title: "name",
51354             width: 120
51355         },
51356         {
51357             name : 'value',
51358             title: "Value",
51359             width: 120
51360         },
51361         {
51362             name : 'width',
51363             title: "Width",
51364             width: 40
51365         }
51366     ],
51367     'LABEL' : [
51368          {
51369             name : 'for',
51370             title: "For",
51371             width: 120
51372         }
51373     ],
51374     'TEXTAREA' : [
51375         {
51376             name : 'name',
51377             title: "name",
51378             width: 120
51379         },
51380         {
51381             name : 'rows',
51382             title: "Rows",
51383             width: 20
51384         },
51385         {
51386             name : 'cols',
51387             title: "Cols",
51388             width: 20
51389         }
51390     ],
51391     'SELECT' : [
51392         {
51393             name : 'name',
51394             title: "name",
51395             width: 120
51396         },
51397         {
51398             name : 'selectoptions',
51399             title: "Options",
51400             width: 200
51401         }
51402     ],
51403     
51404     // should we really allow this??
51405     // should this just be 
51406     'BODY' : [
51407         
51408         {
51409             name : 'title',
51410             title: "Title",
51411             width: 200,
51412             disabled : true
51413         }
51414     ],
51415  
51416     '*' : [
51417         // empty.
51418     ]
51419
51420 };
51421
51422 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
51423 Roo.form.HtmlEditor.ToolbarContext.stores = false;
51424
51425 Roo.form.HtmlEditor.ToolbarContext.options = {
51426         'font-family'  : [ 
51427                 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
51428                 [ 'Courier New', 'Courier New'],
51429                 [ 'Tahoma', 'Tahoma'],
51430                 [ 'Times New Roman,serif', 'Times'],
51431                 [ 'Verdana','Verdana' ]
51432         ]
51433 };
51434
51435 // fixme - these need to be configurable..
51436  
51437
51438 //Roo.form.HtmlEditor.ToolbarContext.types
51439
51440
51441 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype,  {
51442     
51443     tb: false,
51444     
51445     rendered: false,
51446     
51447     editor : false,
51448     editorcore : false,
51449     /**
51450      * @cfg {Object} disable  List of toolbar elements to disable
51451          
51452      */
51453     disable : false,
51454     /**
51455      * @cfg {Object} styles List of styles 
51456      *    eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] } 
51457      *
51458      * These must be defined in the page, so they get rendered correctly..
51459      * .headline { }
51460      * TD.underline { }
51461      * 
51462      */
51463     styles : false,
51464     
51465     options: false,
51466     
51467     toolbars : false,
51468     
51469     init : function(editor)
51470     {
51471         this.editor = editor;
51472         this.editorcore = editor.editorcore ? editor.editorcore : editor;
51473         var editorcore = this.editorcore;
51474         
51475         var fid = editorcore.frameId;
51476         var etb = this;
51477         function btn(id, toggle, handler){
51478             var xid = fid + '-'+ id ;
51479             return {
51480                 id : xid,
51481                 cmd : id,
51482                 cls : 'x-btn-icon x-edit-'+id,
51483                 enableToggle:toggle !== false,
51484                 scope: editorcore, // was editor...
51485                 handler:handler||editorcore.relayBtnCmd,
51486                 clickEvent:'mousedown',
51487                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
51488                 tabIndex:-1
51489             };
51490         }
51491         // create a new element.
51492         var wdiv = editor.wrap.createChild({
51493                 tag: 'div'
51494             }, editor.wrap.dom.firstChild.nextSibling, true);
51495         
51496         // can we do this more than once??
51497         
51498          // stop form submits
51499       
51500  
51501         // disable everything...
51502         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
51503         this.toolbars = {};
51504         // block toolbars are built in updateToolbar when needed.
51505         for (var i in  ty) {
51506             
51507             this.toolbars[i] = this.buildToolbar(ty[i],i);
51508         }
51509         this.tb = this.toolbars.BODY;
51510         this.tb.el.show();
51511         this.buildFooter();
51512         this.footer.show();
51513         editor.on('hide', function( ) { this.footer.hide() }, this);
51514         editor.on('show', function( ) { this.footer.show() }, this);
51515         
51516          
51517         this.rendered = true;
51518         
51519         // the all the btns;
51520         editor.on('editorevent', this.updateToolbar, this);
51521         // other toolbars need to implement this..
51522         //editor.on('editmodechange', this.updateToolbar, this);
51523     },
51524     
51525     
51526     
51527     /**
51528      * Protected method that will not generally be called directly. It triggers
51529      * a toolbar update by reading the markup state of the current selection in the editor.
51530      *
51531      * Note you can force an update by calling on('editorevent', scope, false)
51532      */
51533     updateToolbar: function(editor ,ev, sel)
51534     {
51535         
51536         if (ev) {
51537             ev.stopEvent(); // se if we can stop this looping with mutiple events.
51538         }
51539         
51540         //Roo.log(ev);
51541         // capture mouse up - this is handy for selecting images..
51542         // perhaps should go somewhere else...
51543         if(!this.editorcore.activated){
51544              this.editor.onFirstFocus();
51545             return;
51546         }
51547         //Roo.log(ev ? ev.target : 'NOTARGET');
51548         
51549         
51550         // http://developer.yahoo.com/yui/docs/simple-editor.js.html
51551         // selectNode - might want to handle IE?
51552         
51553         
51554         
51555         if (ev &&
51556             (ev.type == 'mouseup' || ev.type == 'click' ) &&
51557             ev.target && ev.target.tagName != 'BODY' ) { // && ev.target.tagName == 'IMG') {
51558             // they have click on an image...
51559             // let's see if we can change the selection...
51560             sel = ev.target;
51561             
51562             // this triggers looping?
51563             //this.editorcore.selectNode(sel);
51564              
51565         }
51566         
51567         // this forces an id..
51568         Array.from(this.editorcore.doc.body.querySelectorAll('.roo-ed-selection')).forEach(function(e) {
51569              e.classList.remove('roo-ed-selection');
51570         });
51571         //Roo.select('.roo-ed-selection', false, this.editorcore.doc).removeClass('roo-ed-selection');
51572         //Roo.get(node).addClass('roo-ed-selection');
51573       
51574         //var updateFooter = sel ? false : true; 
51575         
51576         
51577         var ans = this.editorcore.getAllAncestors();
51578         
51579         // pick
51580         var ty = Roo.form.HtmlEditor.ToolbarContext.types;
51581         
51582         if (!sel) { 
51583             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editorcore.doc.body;
51584             sel = sel ? sel : this.editorcore.doc.body;
51585             sel = sel.tagName.length ? sel : this.editorcore.doc.body;
51586             
51587         }
51588         
51589         var tn = sel.tagName.toUpperCase();
51590         var lastSel = this.tb.selectedNode;
51591         this.tb.selectedNode = sel;
51592         var left_label = tn;
51593         
51594         // ok see if we are editing a block?
51595         
51596         var db = false;
51597         // you are not actually selecting the block.
51598         if (sel && sel.hasAttribute('data-block')) {
51599             db = sel;
51600         } else if (sel && sel.closest('[data-block]')) {
51601             
51602             db = sel.closest('[data-block]');
51603             //var cepar = sel.closest('[contenteditable=true]');
51604             //if (db && cepar && cepar.tagName != 'BODY') {
51605             //   db = false; // we are inside an editable block.. = not sure how we are going to handle nested blocks!?
51606             //}   
51607         }
51608         
51609         
51610         var block = false;
51611         //if (db && !sel.hasAttribute('contenteditable') && sel.getAttribute('contenteditable') != 'true' ) {
51612         if (db && this.editorcore.enableBlocks) {
51613             block = Roo.htmleditor.Block.factory(db);
51614             
51615             
51616             if (block) {
51617                  db.className = (
51618                         db.classList.length > 0  ? db.className + ' ' : ''
51619                     )  + 'roo-ed-selection';
51620                  
51621                  // since we removed it earlier... its not there..
51622                 tn = 'BLOCK.' + db.getAttribute('data-block');
51623                 
51624                 //this.editorcore.selectNode(db);
51625                 if (typeof(this.toolbars[tn]) == 'undefined') {
51626                    this.toolbars[tn] = this.buildToolbar( false  ,tn ,block.friendly_name, block);
51627                 }
51628                 this.toolbars[tn].selectedNode = db;
51629                 left_label = block.friendly_name;
51630                 ans = this.editorcore.getAllAncestors();
51631             }
51632             
51633                 
51634             
51635         }
51636         
51637         
51638         if (this.tb.name == tn && lastSel == this.tb.selectedNode && ev !== false) {
51639             return; // no change?
51640         }
51641         
51642         
51643           
51644         this.tb.el.hide();
51645         ///console.log("show: " + tn);
51646         this.tb =  typeof(this.toolbars[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
51647         
51648         this.tb.el.show();
51649         // update name
51650         this.tb.items.first().el.innerHTML = left_label + ':&nbsp;';
51651         
51652         
51653         // update attributes
51654         if (block && this.tb.fields) {
51655              
51656             this.tb.fields.each(function(e) {
51657                 e.setValue(block[e.name]);
51658             });
51659             
51660             
51661         } else  if (this.tb.fields && this.tb.selectedNode) {
51662             this.tb.fields.each( function(e) {
51663                 if (e.stylename) {
51664                     e.setValue(this.tb.selectedNode.style[e.stylename]);
51665                     return;
51666                 } 
51667                 e.setValue(this.tb.selectedNode.getAttribute(e.attrname));
51668             }, this);
51669             this.updateToolbarStyles(this.tb.selectedNode);  
51670         }
51671         
51672         
51673        
51674         Roo.menu.MenuMgr.hideAll();
51675
51676         
51677         
51678     
51679         // update the footer
51680         //
51681         this.updateFooter(ans);
51682              
51683     },
51684     
51685     updateToolbarStyles : function(sel)
51686     {
51687         var hasStyles = false;
51688         for(var i in this.styles) {
51689             hasStyles = true;
51690             break;
51691         }
51692         
51693         // update styles
51694         if (hasStyles && this.tb.hasStyles) { 
51695             var st = this.tb.fields.item(0);
51696             
51697             st.store.removeAll();
51698             var cn = sel.className.split(/\s+/);
51699             
51700             var avs = [];
51701             if (this.styles['*']) {
51702                 
51703                 Roo.each(this.styles['*'], function(v) {
51704                     avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
51705                 });
51706             }
51707             if (this.styles[tn]) { 
51708                 Roo.each(this.styles[tn], function(v) {
51709                     avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
51710                 });
51711             }
51712             
51713             st.store.loadData(avs);
51714             st.collapse();
51715             st.setValue(cn);
51716         }
51717     },
51718     
51719      
51720     updateFooter : function(ans)
51721     {
51722         var html = '';
51723         if (ans === false) {
51724             this.footDisp.dom.innerHTML = '';
51725             return;
51726         }
51727         
51728         this.footerEls = ans.reverse();
51729         Roo.each(this.footerEls, function(a,i) {
51730             if (!a) { return; }
51731             html += html.length ? ' &gt; '  :  '';
51732             
51733             html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
51734             
51735         });
51736        
51737         // 
51738         var sz = this.footDisp.up('td').getSize();
51739         this.footDisp.dom.style.width = (sz.width -10) + 'px';
51740         this.footDisp.dom.style.marginLeft = '5px';
51741         
51742         this.footDisp.dom.style.overflow = 'hidden';
51743         
51744         this.footDisp.dom.innerHTML = html;
51745             
51746         
51747     },
51748    
51749        
51750     // private
51751     onDestroy : function(){
51752         if(this.rendered){
51753             
51754             this.tb.items.each(function(item){
51755                 if(item.menu){
51756                     item.menu.removeAll();
51757                     if(item.menu.el){
51758                         item.menu.el.destroy();
51759                     }
51760                 }
51761                 item.destroy();
51762             });
51763              
51764         }
51765     },
51766     onFirstFocus: function() {
51767         // need to do this for all the toolbars..
51768         this.tb.items.each(function(item){
51769            item.enable();
51770         });
51771     },
51772     buildToolbar: function(tlist, nm, friendly_name, block)
51773     {
51774         var editor = this.editor;
51775         var editorcore = this.editorcore;
51776          // create a new element.
51777         var wdiv = editor.wrap.createChild({
51778                 tag: 'div'
51779             }, editor.wrap.dom.firstChild.nextSibling, true);
51780         
51781        
51782         var tb = new Roo.Toolbar(wdiv);
51783         ///this.tb = tb; // << this sets the active toolbar..
51784         if (tlist === false && block) {
51785             tlist = block.contextMenu(this);
51786         }
51787         
51788         tb.hasStyles = false;
51789         tb.name = nm;
51790         
51791         tb.add((typeof(friendly_name) == 'undefined' ? nm : friendly_name) + ":&nbsp;");
51792         
51793         var styles = Array.from(this.styles);
51794         
51795         
51796         // styles...
51797         if (styles && styles.length) {
51798             tb.hasStyles = true;
51799             // this needs a multi-select checkbox...
51800             tb.addField( new Roo.form.ComboBox({
51801                 store: new Roo.data.SimpleStore({
51802                     id : 'val',
51803                     fields: ['val', 'selected'],
51804                     data : [] 
51805                 }),
51806                 name : '-roo-edit-className',
51807                 attrname : 'className',
51808                 displayField: 'val',
51809                 typeAhead: false,
51810                 mode: 'local',
51811                 editable : false,
51812                 triggerAction: 'all',
51813                 emptyText:'Select Style',
51814                 selectOnFocus:true,
51815                 width: 130,
51816                 listeners : {
51817                     'select': function(c, r, i) {
51818                         // initial support only for on class per el..
51819                         tb.selectedNode.className =  r ? r.get('val') : '';
51820                         editorcore.syncValue();
51821                     }
51822                 }
51823     
51824             }));
51825         }
51826         
51827         var tbc = Roo.form.HtmlEditor.ToolbarContext;
51828         
51829         
51830         for (var i = 0; i < tlist.length; i++) {
51831             
51832             // newer versions will use xtype cfg to create menus.
51833             if (typeof(tlist[i].xtype) != 'undefined') {
51834                 
51835                 tb[typeof(tlist[i].name)== 'undefined' ? 'add' : 'addField'](Roo.factory(tlist[i]));
51836                 
51837                 
51838                 continue;
51839             }
51840             
51841             var item = tlist[i];
51842             tb.add(item.title + ":&nbsp;");
51843             
51844             
51845             //optname == used so you can configure the options available..
51846             var opts = item.opts ? item.opts : false;
51847             if (item.optname) { // use the b
51848                 opts = Roo.form.HtmlEditor.ToolbarContext.options[item.optname];
51849            
51850             }
51851             
51852             if (opts) {
51853                 // opts == pulldown..
51854                 tb.addField( new Roo.form.ComboBox({
51855                     store:   typeof(tbc.stores[i]) != 'undefined' ?  Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
51856                         id : 'val',
51857                         fields: ['val', 'display'],
51858                         data : opts  
51859                     }),
51860                     name : '-roo-edit-' + tlist[i].name,
51861                     
51862                     attrname : tlist[i].name,
51863                     stylename : item.style ? item.style : false,
51864                     
51865                     displayField: item.displayField ? item.displayField : 'val',
51866                     valueField :  'val',
51867                     typeAhead: false,
51868                     mode: typeof(tbc.stores[tlist[i].name]) != 'undefined'  ? 'remote' : 'local',
51869                     editable : false,
51870                     triggerAction: 'all',
51871                     emptyText:'Select',
51872                     selectOnFocus:true,
51873                     width: item.width ? item.width  : 130,
51874                     listeners : {
51875                         'select': function(c, r, i) {
51876                              
51877                             
51878                             if (c.stylename) {
51879                                 tb.selectedNode.style[c.stylename] =  r.get('val');
51880                                 editorcore.syncValue();
51881                                 return;
51882                             }
51883                             if (r === false) {
51884                                 tb.selectedNode.removeAttribute(c.attrname);
51885                                 editorcore.syncValue();
51886                                 return;
51887                             }
51888                             tb.selectedNode.setAttribute(c.attrname, r.get('val'));
51889                             editorcore.syncValue();
51890                         }
51891                     }
51892
51893                 }));
51894                 continue;
51895                     
51896                  
51897                 /*
51898                 tb.addField( new Roo.form.TextField({
51899                     name: i,
51900                     width: 100,
51901                     //allowBlank:false,
51902                     value: ''
51903                 }));
51904                 continue;
51905                 */
51906             }
51907             tb.addField( new Roo.form.TextField({
51908                 name: '-roo-edit-' + tlist[i].name,
51909                 attrname : tlist[i].name,
51910                 
51911                 width: item.width,
51912                 //allowBlank:true,
51913                 value: '',
51914                 listeners: {
51915                     'change' : function(f, nv, ov) {
51916                         
51917                          
51918                         tb.selectedNode.setAttribute(f.attrname, nv);
51919                         editorcore.syncValue();
51920                     }
51921                 }
51922             }));
51923              
51924         }
51925         
51926         var _this = this;
51927         var show_delete = !block || block.deleteTitle !== false;
51928         if(nm == 'BODY'){
51929             show_delete = false;
51930             tb.addSeparator();
51931         
51932             tb.addButton( {
51933                 text: 'Stylesheets',
51934
51935                 listeners : {
51936                     click : function ()
51937                     {
51938                         _this.editor.fireEvent('stylesheetsclick', _this.editor);
51939                     }
51940                 }
51941             });
51942         }
51943         
51944         tb.addFill();
51945         if (show_delete) {
51946             tb.addButton({
51947                 text: block && block.deleteTitle ? block.deleteTitle  : 'Remove Block or Formating', // remove the tag, and puts the children outside...
51948         
51949                 listeners : {
51950                     click : function ()
51951                     {
51952                         var sn = tb.selectedNode;
51953                         if (block) {
51954                             sn = Roo.htmleditor.Block.factory(tb.selectedNode).removeNode();
51955                             
51956                         }
51957                         if (!sn) {
51958                             return;
51959                         }
51960                         var stn =  sn.childNodes[0] || sn.nextSibling || sn.previousSibling || sn.parentNode;
51961                         if (sn.hasAttribute('data-block')) {
51962                             stn =  sn.nextSibling || sn.previousSibling || sn.parentNode;
51963                             sn.parentNode.removeChild(sn);
51964                             
51965                         } else if (sn && sn.tagName != 'BODY') {
51966                             // remove and keep parents.
51967                             a = new Roo.htmleditor.FilterKeepChildren({tag : false});
51968                             a.replaceTag(sn);
51969                         }
51970                         
51971                         
51972                         var range = editorcore.createRange();
51973             
51974                         range.setStart(stn,0);
51975                         range.setEnd(stn,0); 
51976                         var selection = editorcore.getSelection();
51977                         selection.removeAllRanges();
51978                         selection.addRange(range);
51979                         
51980                         
51981                         //_this.updateToolbar(null, null, pn);
51982                         _this.updateToolbar(null, null, null);
51983                         _this.updateFooter(false);
51984                         
51985                     }
51986                 }
51987                 
51988                         
51989                     
51990                 
51991             });
51992         }    
51993         
51994         tb.el.on('click', function(e){
51995             e.preventDefault(); // what does this do?
51996         });
51997         tb.el.setVisibilityMode( Roo.Element.DISPLAY);
51998         tb.el.hide();
51999         
52000         // dont need to disable them... as they will get hidden
52001         return tb;
52002          
52003         
52004     },
52005     buildFooter : function()
52006     {
52007         
52008         var fel = this.editor.wrap.createChild();
52009         this.footer = new Roo.Toolbar(fel);
52010         // toolbar has scrolly on left / right?
52011         var footDisp= new Roo.Toolbar.Fill();
52012         var _t = this;
52013         this.footer.add(
52014             {
52015                 text : '&lt;',
52016                 xtype: 'Button',
52017                 handler : function() {
52018                     _t.footDisp.scrollTo('left',0,true)
52019                 }
52020             }
52021         );
52022         this.footer.add( footDisp );
52023         this.footer.add( 
52024             {
52025                 text : '&gt;',
52026                 xtype: 'Button',
52027                 handler : function() {
52028                     // no animation..
52029                     _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
52030                 }
52031             }
52032         );
52033         var fel = Roo.get(footDisp.el);
52034         fel.addClass('x-editor-context');
52035         this.footDispWrap = fel; 
52036         this.footDispWrap.overflow  = 'hidden';
52037         
52038         this.footDisp = fel.createChild();
52039         this.footDispWrap.on('click', this.onContextClick, this)
52040         
52041         
52042     },
52043     // when the footer contect changes
52044     onContextClick : function (ev,dom)
52045     {
52046         ev.preventDefault();
52047         var  cn = dom.className;
52048         //Roo.log(cn);
52049         if (!cn.match(/x-ed-loc-/)) {
52050             return;
52051         }
52052         var n = cn.split('-').pop();
52053         var ans = this.footerEls;
52054         var sel = ans[n];
52055         
52056         this.editorcore.selectNode(sel);
52057         
52058         
52059         this.updateToolbar(null, null, sel);
52060         
52061         
52062     }
52063     
52064     
52065     
52066     
52067     
52068 });
52069
52070
52071
52072
52073
52074 /*
52075  * Based on:
52076  * Ext JS Library 1.1.1
52077  * Copyright(c) 2006-2007, Ext JS, LLC.
52078  *
52079  * Originally Released Under LGPL - original licence link has changed is not relivant.
52080  *
52081  * Fork - LGPL
52082  * <script type="text/javascript">
52083  */
52084  
52085 /**
52086  * @class Roo.form.BasicForm
52087  * @extends Roo.util.Observable
52088  * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
52089  * @constructor
52090  * @param {String/HTMLElement/Roo.Element} el The form element or its id
52091  * @param {Object} config Configuration options
52092  */
52093 Roo.form.BasicForm = function(el, config){
52094     this.allItems = [];
52095     this.childForms = [];
52096     Roo.apply(this, config);
52097     /*
52098      * The Roo.form.Field items in this form.
52099      * @type MixedCollection
52100      */
52101      
52102      
52103     this.items = new Roo.util.MixedCollection(false, function(o){
52104         return o.id || (o.id = Roo.id());
52105     });
52106     this.addEvents({
52107         /**
52108          * @event beforeaction
52109          * Fires before any action is performed. Return false to cancel the action.
52110          * @param {Form} this
52111          * @param {Action} action The action to be performed
52112          */
52113         beforeaction: true,
52114         /**
52115          * @event actionfailed
52116          * Fires when an action fails.
52117          * @param {Form} this
52118          * @param {Action} action The action that failed
52119          */
52120         actionfailed : true,
52121         /**
52122          * @event actioncomplete
52123          * Fires when an action is completed.
52124          * @param {Form} this
52125          * @param {Action} action The action that completed
52126          */
52127         actioncomplete : true
52128     });
52129     if(el){
52130         this.initEl(el);
52131     }
52132     Roo.form.BasicForm.superclass.constructor.call(this);
52133     
52134     Roo.form.BasicForm.popover.apply();
52135 };
52136
52137 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
52138     /**
52139      * @cfg {String} method
52140      * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
52141      */
52142     /**
52143      * @cfg {DataReader} reader
52144      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
52145      * This is optional as there is built-in support for processing JSON.
52146      */
52147     /**
52148      * @cfg {DataReader} errorReader
52149      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
52150      * This is completely optional as there is built-in support for processing JSON.
52151      */
52152     /**
52153      * @cfg {String} url
52154      * The URL to use for form actions if one isn't supplied in the action options.
52155      */
52156     /**
52157      * @cfg {Boolean} fileUpload
52158      * Set to true if this form is a file upload.
52159      */
52160      
52161     /**
52162      * @cfg {Object} baseParams
52163      * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
52164      */
52165      /**
52166      
52167     /**
52168      * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
52169      */
52170     timeout: 30,
52171
52172     // private
52173     activeAction : null,
52174
52175     /**
52176      * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
52177      * or setValues() data instead of when the form was first created.
52178      */
52179     trackResetOnLoad : false,
52180     
52181     
52182     /**
52183      * childForms - used for multi-tab forms
52184      * @type {Array}
52185      */
52186     childForms : false,
52187     
52188     /**
52189      * allItems - full list of fields.
52190      * @type {Array}
52191      */
52192     allItems : false,
52193     
52194     /**
52195      * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
52196      * element by passing it or its id or mask the form itself by passing in true.
52197      * @type Mixed
52198      */
52199     waitMsgTarget : false,
52200     
52201     /**
52202      * @type Boolean
52203      */
52204     disableMask : false,
52205     
52206     /**
52207      * @cfg {Boolean} errorMask (true|false) default false
52208      */
52209     errorMask : false,
52210     
52211     /**
52212      * @cfg {Number} maskOffset Default 100
52213      */
52214     maskOffset : 100,
52215
52216     // private
52217     initEl : function(el){
52218         this.el = Roo.get(el);
52219         this.id = this.el.id || Roo.id();
52220         this.el.on('submit', this.onSubmit, this);
52221         this.el.addClass('x-form');
52222     },
52223
52224     // private
52225     onSubmit : function(e){
52226         e.stopEvent();
52227     },
52228
52229     /**
52230      * Returns true if client-side validation on the form is successful.
52231      * @return Boolean
52232      */
52233     isValid : function(){
52234         var valid = true;
52235         var target = false;
52236         this.items.each(function(f){
52237             if(f.validate()){
52238                 return;
52239             }
52240             
52241             valid = false;
52242                 
52243             if(!target && f.el.isVisible(true)){
52244                 target = f;
52245             }
52246         });
52247         
52248         if(this.errorMask && !valid){
52249             Roo.form.BasicForm.popover.mask(this, target);
52250         }
52251         
52252         return valid;
52253     },
52254     /**
52255      * Returns array of invalid form fields.
52256      * @return Array
52257      */
52258     
52259     invalidFields : function()
52260     {
52261         var ret = [];
52262         this.items.each(function(f){
52263             if(f.validate()){
52264                 return;
52265             }
52266             ret.push(f);
52267             
52268         });
52269         
52270         return ret;
52271     },
52272     
52273     
52274     /**
52275      * DEPRICATED Returns true if any fields in this form have changed since their original load. 
52276      * @return Boolean
52277      */
52278     isDirty : function(){
52279         var dirty = false;
52280         this.items.each(function(f){
52281            if(f.isDirty()){
52282                dirty = true;
52283                return false;
52284            }
52285         });
52286         return dirty;
52287     },
52288     
52289     /**
52290      * Returns true if any fields in this form have changed since their original load. (New version)
52291      * @return Boolean
52292      */
52293     
52294     hasChanged : function()
52295     {
52296         var dirty = false;
52297         this.items.each(function(f){
52298            if(f.hasChanged()){
52299                dirty = true;
52300                return false;
52301            }
52302         });
52303         return dirty;
52304         
52305     },
52306     /**
52307      * Resets all hasChanged to 'false' -
52308      * The old 'isDirty' used 'original value..' however this breaks reset() and a few other things.
52309      * So hasChanged storage is only to be used for this purpose
52310      * @return Boolean
52311      */
52312     resetHasChanged : function()
52313     {
52314         this.items.each(function(f){
52315            f.resetHasChanged();
52316         });
52317         
52318     },
52319     
52320     
52321     /**
52322      * Performs a predefined action (submit or load) or custom actions you define on this form.
52323      * @param {String} actionName The name of the action type
52324      * @param {Object} options (optional) The options to pass to the action.  All of the config options listed
52325      * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
52326      * accept other config options):
52327      * <pre>
52328 Property          Type             Description
52329 ----------------  ---------------  ----------------------------------------------------------------------------------
52330 url               String           The url for the action (defaults to the form's url)
52331 method            String           The form method to use (defaults to the form's method, or POST if not defined)
52332 params            String/Object    The params to pass (defaults to the form's baseParams, or none if not defined)
52333 clientValidation  Boolean          Applies to submit only.  Pass true to call form.isValid() prior to posting to
52334                                    validate the form on the client (defaults to false)
52335      * </pre>
52336      * @return {BasicForm} this
52337      */
52338     doAction : function(action, options){
52339         if(typeof action == 'string'){
52340             action = new Roo.form.Action.ACTION_TYPES[action](this, options);
52341         }
52342         if(this.fireEvent('beforeaction', this, action) !== false){
52343             this.beforeAction(action);
52344             action.run.defer(100, action);
52345         }
52346         return this;
52347     },
52348
52349     /**
52350      * Shortcut to do a submit action.
52351      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
52352      * @return {BasicForm} this
52353      */
52354     submit : function(options){
52355         this.doAction('submit', options);
52356         return this;
52357     },
52358
52359     /**
52360      * Shortcut to do a load action.
52361      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
52362      * @return {BasicForm} this
52363      */
52364     load : function(options){
52365         this.doAction('load', options);
52366         return this;
52367     },
52368
52369     /**
52370      * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
52371      * @param {Record} record The record to edit
52372      * @return {BasicForm} this
52373      */
52374     updateRecord : function(record){
52375         record.beginEdit();
52376         var fs = record.fields;
52377         fs.each(function(f){
52378             var field = this.findField(f.name);
52379             if(field){
52380                 record.set(f.name, field.getValue());
52381             }
52382         }, this);
52383         record.endEdit();
52384         return this;
52385     },
52386
52387     /**
52388      * Loads an Roo.data.Record into this form.
52389      * @param {Record} record The record to load
52390      * @return {BasicForm} this
52391      */
52392     loadRecord : function(record){
52393         this.setValues(record.data);
52394         return this;
52395     },
52396
52397     // private
52398     beforeAction : function(action){
52399         var o = action.options;
52400         
52401         if(!this.disableMask) {
52402             if(this.waitMsgTarget === true){
52403                 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
52404             }else if(this.waitMsgTarget){
52405                 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
52406                 this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
52407             }else {
52408                 Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
52409             }
52410         }
52411         
52412          
52413     },
52414
52415     // private
52416     afterAction : function(action, success){
52417         this.activeAction = null;
52418         var o = action.options;
52419         
52420         if(!this.disableMask) {
52421             if(this.waitMsgTarget === true){
52422                 this.el.unmask();
52423             }else if(this.waitMsgTarget){
52424                 this.waitMsgTarget.unmask();
52425             }else{
52426                 Roo.MessageBox.updateProgress(1);
52427                 Roo.MessageBox.hide();
52428             }
52429         }
52430         
52431         if(success){
52432             if(o.reset){
52433                 this.reset();
52434             }
52435             Roo.callback(o.success, o.scope, [this, action]);
52436             this.fireEvent('actioncomplete', this, action);
52437             
52438         }else{
52439             
52440             // failure condition..
52441             // we have a scenario where updates need confirming.
52442             // eg. if a locking scenario exists..
52443             // we look for { errors : { needs_confirm : true }} in the response.
52444             if (
52445                 (typeof(action.result) != 'undefined')  &&
52446                 (typeof(action.result.errors) != 'undefined')  &&
52447                 (typeof(action.result.errors.needs_confirm) != 'undefined')
52448            ){
52449                 var _t = this;
52450                 Roo.MessageBox.confirm(
52451                     "Change requires confirmation",
52452                     action.result.errorMsg,
52453                     function(r) {
52454                         if (r != 'yes') {
52455                             return;
52456                         }
52457                         _t.doAction('submit', { params :  { _submit_confirmed : 1 } }  );
52458                     }
52459                     
52460                 );
52461                 
52462                 
52463                 
52464                 return;
52465             }
52466             
52467             Roo.callback(o.failure, o.scope, [this, action]);
52468             // show an error message if no failed handler is set..
52469             if (!this.hasListener('actionfailed')) {
52470                 Roo.MessageBox.alert("Error",
52471                     (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
52472                         action.result.errorMsg :
52473                         "Saving Failed, please check your entries or try again"
52474                 );
52475             }
52476             
52477             this.fireEvent('actionfailed', this, action);
52478         }
52479         
52480     },
52481
52482     /**
52483      * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
52484      * @param {String} id The value to search for
52485      * @return Field
52486      */
52487     findField : function(id){
52488         var field = this.items.get(id);
52489         if(!field){
52490             this.items.each(function(f){
52491                 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
52492                     field = f;
52493                     return false;
52494                 }
52495             });
52496         }
52497         return field || null;
52498     },
52499
52500     /**
52501      * Add a secondary form to this one, 
52502      * Used to provide tabbed forms. One form is primary, with hidden values 
52503      * which mirror the elements from the other forms.
52504      * 
52505      * @param {Roo.form.Form} form to add.
52506      * 
52507      */
52508     addForm : function(form)
52509     {
52510        
52511         if (this.childForms.indexOf(form) > -1) {
52512             // already added..
52513             return;
52514         }
52515         this.childForms.push(form);
52516         var n = '';
52517         Roo.each(form.allItems, function (fe) {
52518             
52519             n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
52520             if (this.findField(n)) { // already added..
52521                 return;
52522             }
52523             var add = new Roo.form.Hidden({
52524                 name : n
52525             });
52526             add.render(this.el);
52527             
52528             this.add( add );
52529         }, this);
52530         
52531     },
52532     /**
52533      * Mark fields in this form invalid in bulk.
52534      * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
52535      * @return {BasicForm} this
52536      */
52537     markInvalid : function(errors){
52538         if(errors instanceof Array){
52539             for(var i = 0, len = errors.length; i < len; i++){
52540                 var fieldError = errors[i];
52541                 var f = this.findField(fieldError.id);
52542                 if(f){
52543                     f.markInvalid(fieldError.msg);
52544                 }
52545             }
52546         }else{
52547             var field, id;
52548             for(id in errors){
52549                 if(typeof errors[id] != 'function' && (field = this.findField(id))){
52550                     field.markInvalid(errors[id]);
52551                 }
52552             }
52553         }
52554         Roo.each(this.childForms || [], function (f) {
52555             f.markInvalid(errors);
52556         });
52557         
52558         return this;
52559     },
52560
52561     /**
52562      * Set values for fields in this form in bulk.
52563      * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
52564      * @return {BasicForm} this
52565      */
52566     setValues : function(values){
52567         if(values instanceof Array){ // array of objects
52568             for(var i = 0, len = values.length; i < len; i++){
52569                 var v = values[i];
52570                 var f = this.findField(v.id);
52571                 if(f){
52572                     f.setValue(v.value);
52573                     if(this.trackResetOnLoad){
52574                         f.originalValue = f.getValue();
52575                     }
52576                 }
52577             }
52578         }else{ // object hash
52579             var field, id;
52580             for(id in values){
52581                 if(typeof values[id] != 'function' && (field = this.findField(id))){
52582                     
52583                     if (field.setFromData && 
52584                         field.valueField && 
52585                         field.displayField &&
52586                         // combos' with local stores can 
52587                         // be queried via setValue()
52588                         // to set their value..
52589                         (field.store && !field.store.isLocal)
52590                         ) {
52591                         // it's a combo
52592                         var sd = { };
52593                         sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
52594                         sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
52595                         field.setFromData(sd);
52596                         
52597                     } else {
52598                         field.setValue(values[id]);
52599                     }
52600                     
52601                     
52602                     if(this.trackResetOnLoad){
52603                         field.originalValue = field.getValue();
52604                     }
52605                 }
52606             }
52607         }
52608         this.resetHasChanged();
52609         
52610         
52611         Roo.each(this.childForms || [], function (f) {
52612             f.setValues(values);
52613             f.resetHasChanged();
52614         });
52615                 
52616         return this;
52617     },
52618  
52619     /**
52620      * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
52621      * they are returned as an array.
52622      * @param {Boolean} asString
52623      * @return {Object}
52624      */
52625     getValues : function(asString)
52626     {
52627         if (this.childForms) {
52628             // copy values from the child forms
52629             Roo.each(this.childForms, function (f) {
52630                 this.setValues(f.getFieldValues()); // get the full set of data, as we might be copying comboboxes from external into this one.
52631             }, this);
52632         }
52633         
52634         // use formdata
52635         if (typeof(FormData) != 'undefined' && asString !== true) {
52636             // this relies on a 'recent' version of chrome apparently...
52637             try {
52638                 var fd = (new FormData(this.el.dom)).entries();
52639                 var ret = {};
52640                 var ent = fd.next();
52641                 while (!ent.done) {
52642                     ret[ent.value[0]] = ent.value[1]; // not sure how this will handle duplicates..
52643                     ent = fd.next();
52644                 };
52645                 return ret;
52646             } catch(e) {
52647                 
52648             }
52649             
52650         }
52651         
52652         
52653         var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
52654         if(asString === true){
52655             return fs;
52656         }
52657         return Roo.urlDecode(fs);
52658     },
52659     
52660     /**
52661      * Returns the fields in this form as an object with key/value pairs. 
52662      * This differs from getValues as it calls getValue on each child item, rather than using dom data.
52663      * Normally this will not return readOnly data 
52664      * @param {Boolean} with_readonly return readonly field data.
52665      * @return {Object}
52666      */
52667     getFieldValues : function(with_readonly)
52668     {
52669         if (this.childForms) {
52670             // copy values from the child forms
52671             // should this call getFieldValues - probably not as we do not currently copy
52672             // hidden fields when we generate..
52673             Roo.each(this.childForms, function (f) {
52674                 this.setValues(f.getFieldValues());
52675             }, this);
52676         }
52677         
52678         var ret = {};
52679         this.items.each(function(f){
52680             
52681             if (f.readOnly && with_readonly !== true) {
52682                 return; // skip read only values. - this is in theory to stop 'old' values being copied over new ones
52683                         // if a subform contains a copy of them.
52684                         // if you have subforms with the same editable data, you will need to copy the data back
52685                         // and forth.
52686             }
52687             
52688             if (!f.getName()) {
52689                 return;
52690             }
52691             var v = f.getValue();
52692             if (f.inputType =='radio') {
52693                 if (typeof(ret[f.getName()]) == 'undefined') {
52694                     ret[f.getName()] = ''; // empty..
52695                 }
52696                 
52697                 if (!f.el.dom.checked) {
52698                     return;
52699                     
52700                 }
52701                 v = f.el.dom.value;
52702                 
52703             }
52704             
52705             // not sure if this supported any more..
52706             if ((typeof(v) == 'object') && f.getRawValue) {
52707                 v = f.getRawValue() ; // dates..
52708             }
52709             // combo boxes where name != hiddenName...
52710             if (f.name != f.getName()) {
52711                 ret[f.name] = f.getRawValue();
52712             }
52713             ret[f.getName()] = v;
52714         });
52715         
52716         return ret;
52717     },
52718
52719     /**
52720      * Clears all invalid messages in this form.
52721      * @return {BasicForm} this
52722      */
52723     clearInvalid : function(){
52724         this.items.each(function(f){
52725            f.clearInvalid();
52726         });
52727         
52728         Roo.each(this.childForms || [], function (f) {
52729             f.clearInvalid();
52730         });
52731         
52732         
52733         return this;
52734     },
52735
52736     /**
52737      * Resets this form.
52738      * @return {BasicForm} this
52739      */
52740     reset : function(){
52741         this.items.each(function(f){
52742             f.reset();
52743         });
52744         
52745         Roo.each(this.childForms || [], function (f) {
52746             f.reset();
52747         });
52748         this.resetHasChanged();
52749         
52750         return this;
52751     },
52752
52753     /**
52754      * Add Roo.form components to this form.
52755      * @param {Field} field1
52756      * @param {Field} field2 (optional)
52757      * @param {Field} etc (optional)
52758      * @return {BasicForm} this
52759      */
52760     add : function(){
52761         this.items.addAll(Array.prototype.slice.call(arguments, 0));
52762         return this;
52763     },
52764
52765
52766     /**
52767      * Removes a field from the items collection (does NOT remove its markup).
52768      * @param {Field} field
52769      * @return {BasicForm} this
52770      */
52771     remove : function(field){
52772         this.items.remove(field);
52773         return this;
52774     },
52775
52776     /**
52777      * Looks at the fields in this form, checks them for an id attribute,
52778      * and calls applyTo on the existing dom element with that id.
52779      * @return {BasicForm} this
52780      */
52781     render : function(){
52782         this.items.each(function(f){
52783             if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
52784                 f.applyTo(f.id);
52785             }
52786         });
52787         return this;
52788     },
52789
52790     /**
52791      * Calls {@link Ext#apply} for all fields in this form with the passed object.
52792      * @param {Object} values
52793      * @return {BasicForm} this
52794      */
52795     applyToFields : function(o){
52796         this.items.each(function(f){
52797            Roo.apply(f, o);
52798         });
52799         return this;
52800     },
52801
52802     /**
52803      * Calls {@link Ext#applyIf} for all field in this form with the passed object.
52804      * @param {Object} values
52805      * @return {BasicForm} this
52806      */
52807     applyIfToFields : function(o){
52808         this.items.each(function(f){
52809            Roo.applyIf(f, o);
52810         });
52811         return this;
52812     }
52813 });
52814
52815 // back compat
52816 Roo.BasicForm = Roo.form.BasicForm;
52817
52818 Roo.apply(Roo.form.BasicForm, {
52819     
52820     popover : {
52821         
52822         padding : 5,
52823         
52824         isApplied : false,
52825         
52826         isMasked : false,
52827         
52828         form : false,
52829         
52830         target : false,
52831         
52832         intervalID : false,
52833         
52834         maskEl : false,
52835         
52836         apply : function()
52837         {
52838             if(this.isApplied){
52839                 return;
52840             }
52841             
52842             this.maskEl = {
52843                 top : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-top-mask" }, true),
52844                 left : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-left-mask" }, true),
52845                 bottom : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-bottom-mask" }, true),
52846                 right : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-right-mask" }, true)
52847             };
52848             
52849             this.maskEl.top.enableDisplayMode("block");
52850             this.maskEl.left.enableDisplayMode("block");
52851             this.maskEl.bottom.enableDisplayMode("block");
52852             this.maskEl.right.enableDisplayMode("block");
52853             
52854             Roo.get(document.body).on('click', function(){
52855                 this.unmask();
52856             }, this);
52857             
52858             Roo.get(document.body).on('touchstart', function(){
52859                 this.unmask();
52860             }, this);
52861             
52862             this.isApplied = true
52863         },
52864         
52865         mask : function(form, target)
52866         {
52867             this.form = form;
52868             
52869             this.target = target;
52870             
52871             if(!this.form.errorMask || !target.el){
52872                 return;
52873             }
52874             
52875             var scrollable = this.target.el.findScrollableParent() || this.target.el.findParent('div.x-layout-active-content', 100, true) || Roo.get(document.body);
52876             
52877             var ot = this.target.el.calcOffsetsTo(scrollable);
52878             
52879             var scrollTo = ot[1] - this.form.maskOffset;
52880             
52881             scrollTo = Math.min(scrollTo, scrollable.dom.scrollHeight);
52882             
52883             scrollable.scrollTo('top', scrollTo);
52884             
52885             var el = this.target.wrap || this.target.el;
52886             
52887             var box = el.getBox();
52888             
52889             this.maskEl.top.setStyle('position', 'absolute');
52890             this.maskEl.top.setStyle('z-index', 10000);
52891             this.maskEl.top.setSize(Roo.lib.Dom.getDocumentWidth(), box.y - this.padding);
52892             this.maskEl.top.setLeft(0);
52893             this.maskEl.top.setTop(0);
52894             this.maskEl.top.show();
52895             
52896             this.maskEl.left.setStyle('position', 'absolute');
52897             this.maskEl.left.setStyle('z-index', 10000);
52898             this.maskEl.left.setSize(box.x - this.padding, box.height + this.padding * 2);
52899             this.maskEl.left.setLeft(0);
52900             this.maskEl.left.setTop(box.y - this.padding);
52901             this.maskEl.left.show();
52902
52903             this.maskEl.bottom.setStyle('position', 'absolute');
52904             this.maskEl.bottom.setStyle('z-index', 10000);
52905             this.maskEl.bottom.setSize(Roo.lib.Dom.getDocumentWidth(), Roo.lib.Dom.getDocumentHeight() - box.bottom - this.padding);
52906             this.maskEl.bottom.setLeft(0);
52907             this.maskEl.bottom.setTop(box.bottom + this.padding);
52908             this.maskEl.bottom.show();
52909
52910             this.maskEl.right.setStyle('position', 'absolute');
52911             this.maskEl.right.setStyle('z-index', 10000);
52912             this.maskEl.right.setSize(Roo.lib.Dom.getDocumentWidth() - box.right - this.padding, box.height + this.padding * 2);
52913             this.maskEl.right.setLeft(box.right + this.padding);
52914             this.maskEl.right.setTop(box.y - this.padding);
52915             this.maskEl.right.show();
52916
52917             this.intervalID = window.setInterval(function() {
52918                 Roo.form.BasicForm.popover.unmask();
52919             }, 10000);
52920
52921             window.onwheel = function(){ return false;};
52922             
52923             (function(){ this.isMasked = true; }).defer(500, this);
52924             
52925         },
52926         
52927         unmask : function()
52928         {
52929             if(!this.isApplied || !this.isMasked || !this.form || !this.target || !this.form.errorMask){
52930                 return;
52931             }
52932             
52933             this.maskEl.top.setStyle('position', 'absolute');
52934             this.maskEl.top.setSize(0, 0).setXY([0, 0]);
52935             this.maskEl.top.hide();
52936
52937             this.maskEl.left.setStyle('position', 'absolute');
52938             this.maskEl.left.setSize(0, 0).setXY([0, 0]);
52939             this.maskEl.left.hide();
52940
52941             this.maskEl.bottom.setStyle('position', 'absolute');
52942             this.maskEl.bottom.setSize(0, 0).setXY([0, 0]);
52943             this.maskEl.bottom.hide();
52944
52945             this.maskEl.right.setStyle('position', 'absolute');
52946             this.maskEl.right.setSize(0, 0).setXY([0, 0]);
52947             this.maskEl.right.hide();
52948             
52949             window.onwheel = function(){ return true;};
52950             
52951             if(this.intervalID){
52952                 window.clearInterval(this.intervalID);
52953                 this.intervalID = false;
52954             }
52955             
52956             this.isMasked = false;
52957             
52958         }
52959         
52960     }
52961     
52962 });/*
52963  * Based on:
52964  * Ext JS Library 1.1.1
52965  * Copyright(c) 2006-2007, Ext JS, LLC.
52966  *
52967  * Originally Released Under LGPL - original licence link has changed is not relivant.
52968  *
52969  * Fork - LGPL
52970  * <script type="text/javascript">
52971  */
52972
52973 /**
52974  * @class Roo.form.Form
52975  * @extends Roo.form.BasicForm
52976  * @children Roo.form.Column Roo.form.FieldSet Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
52977  * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
52978  * @constructor
52979  * @param {Object} config Configuration options
52980  */
52981 Roo.form.Form = function(config){
52982     var xitems =  [];
52983     if (config.items) {
52984         xitems = config.items;
52985         delete config.items;
52986     }
52987    
52988     
52989     Roo.form.Form.superclass.constructor.call(this, null, config);
52990     this.url = this.url || this.action;
52991     if(!this.root){
52992         this.root = new Roo.form.Layout(Roo.applyIf({
52993             id: Roo.id()
52994         }, config));
52995     }
52996     this.active = this.root;
52997     /**
52998      * Array of all the buttons that have been added to this form via {@link addButton}
52999      * @type Array
53000      */
53001     this.buttons = [];
53002     this.allItems = [];
53003     this.addEvents({
53004         /**
53005          * @event clientvalidation
53006          * If the monitorValid config option is true, this event fires repetitively to notify of valid state
53007          * @param {Form} this
53008          * @param {Boolean} valid true if the form has passed client-side validation
53009          */
53010         clientvalidation: true,
53011         /**
53012          * @event rendered
53013          * Fires when the form is rendered
53014          * @param {Roo.form.Form} form
53015          */
53016         rendered : true
53017     });
53018     
53019     if (this.progressUrl) {
53020             // push a hidden field onto the list of fields..
53021             this.addxtype( {
53022                     xns: Roo.form, 
53023                     xtype : 'Hidden', 
53024                     name : 'UPLOAD_IDENTIFIER' 
53025             });
53026         }
53027         
53028     
53029     Roo.each(xitems, this.addxtype, this);
53030     
53031 };
53032
53033 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
53034      /**
53035      * @cfg {Roo.Button} buttons[] buttons at bottom of form
53036      */
53037     
53038     /**
53039      * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
53040      */
53041     /**
53042      * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
53043      */
53044     /**
53045      * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
53046      */
53047     buttonAlign:'center',
53048
53049     /**
53050      * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
53051      */
53052     minButtonWidth:75,
53053
53054     /**
53055      * @cfg {String} labelAlign Valid values are "left," "top" and "right" (defaults to "left").
53056      * This property cascades to child containers if not set.
53057      */
53058     labelAlign:'left',
53059
53060     /**
53061      * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
53062      * fires a looping event with that state. This is required to bind buttons to the valid
53063      * state using the config value formBind:true on the button.
53064      */
53065     monitorValid : false,
53066
53067     /**
53068      * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
53069      */
53070     monitorPoll : 200,
53071     
53072     /**
53073      * @cfg {String} progressUrl - Url to return progress data 
53074      */
53075     
53076     progressUrl : false,
53077     /**
53078      * @cfg {boolean|FormData} formData - true to use new 'FormData' post, or set to a new FormData({dom form}) Object, if
53079      * sending a formdata with extra parameters - eg uploaded elements.
53080      */
53081     
53082     formData : false,
53083     
53084     /**
53085      * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
53086      * fields are added and the column is closed. If no fields are passed the column remains open
53087      * until end() is called.
53088      * @param {Object} config The config to pass to the column
53089      * @param {Field} field1 (optional)
53090      * @param {Field} field2 (optional)
53091      * @param {Field} etc (optional)
53092      * @return Column The column container object
53093      */
53094     column : function(c){
53095         var col = new Roo.form.Column(c);
53096         this.start(col);
53097         if(arguments.length > 1){ // duplicate code required because of Opera
53098             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
53099             this.end();
53100         }
53101         return col;
53102     },
53103
53104     /**
53105      * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
53106      * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
53107      * until end() is called.
53108      * @param {Object} config The config to pass to the fieldset
53109      * @param {Field} field1 (optional)
53110      * @param {Field} field2 (optional)
53111      * @param {Field} etc (optional)
53112      * @return FieldSet The fieldset container object
53113      */
53114     fieldset : function(c){
53115         var fs = new Roo.form.FieldSet(c);
53116         this.start(fs);
53117         if(arguments.length > 1){ // duplicate code required because of Opera
53118             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
53119             this.end();
53120         }
53121         return fs;
53122     },
53123
53124     /**
53125      * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
53126      * fields are added and the container is closed. If no fields are passed the container remains open
53127      * until end() is called.
53128      * @param {Object} config The config to pass to the Layout
53129      * @param {Field} field1 (optional)
53130      * @param {Field} field2 (optional)
53131      * @param {Field} etc (optional)
53132      * @return Layout The container object
53133      */
53134     container : function(c){
53135         var l = new Roo.form.Layout(c);
53136         this.start(l);
53137         if(arguments.length > 1){ // duplicate code required because of Opera
53138             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
53139             this.end();
53140         }
53141         return l;
53142     },
53143
53144     /**
53145      * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
53146      * @param {Object} container A Roo.form.Layout or subclass of Layout
53147      * @return {Form} this
53148      */
53149     start : function(c){
53150         // cascade label info
53151         Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
53152         this.active.stack.push(c);
53153         c.ownerCt = this.active;
53154         this.active = c;
53155         return this;
53156     },
53157
53158     /**
53159      * Closes the current open container
53160      * @return {Form} this
53161      */
53162     end : function(){
53163         if(this.active == this.root){
53164             return this;
53165         }
53166         this.active = this.active.ownerCt;
53167         return this;
53168     },
53169
53170     /**
53171      * Add Roo.form components to the current open container (e.g. column, fieldset, etc.).  Fields added via this method
53172      * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
53173      * as the label of the field.
53174      * @param {Field} field1
53175      * @param {Field} field2 (optional)
53176      * @param {Field} etc. (optional)
53177      * @return {Form} this
53178      */
53179     add : function(){
53180         this.active.stack.push.apply(this.active.stack, arguments);
53181         this.allItems.push.apply(this.allItems,arguments);
53182         var r = [];
53183         for(var i = 0, a = arguments, len = a.length; i < len; i++) {
53184             if(a[i].isFormField){
53185                 r.push(a[i]);
53186             }
53187         }
53188         if(r.length > 0){
53189             Roo.form.Form.superclass.add.apply(this, r);
53190         }
53191         return this;
53192     },
53193     
53194
53195     
53196     
53197     
53198      /**
53199      * Find any element that has been added to a form, using it's ID or name
53200      * This can include framesets, columns etc. along with regular fields..
53201      * @param {String} id - id or name to find.
53202      
53203      * @return {Element} e - or false if nothing found.
53204      */
53205     findbyId : function(id)
53206     {
53207         var ret = false;
53208         if (!id) {
53209             return ret;
53210         }
53211         Roo.each(this.allItems, function(f){
53212             if (f.id == id || f.name == id ){
53213                 ret = f;
53214                 return false;
53215             }
53216         });
53217         return ret;
53218     },
53219
53220     
53221     
53222     /**
53223      * Render this form into the passed container. This should only be called once!
53224      * @param {String/HTMLElement/Element} container The element this component should be rendered into
53225      * @return {Form} this
53226      */
53227     render : function(ct)
53228     {
53229         
53230         
53231         
53232         ct = Roo.get(ct);
53233         var o = this.autoCreate || {
53234             tag: 'form',
53235             method : this.method || 'POST',
53236             id : this.id || Roo.id()
53237         };
53238         this.initEl(ct.createChild(o));
53239
53240         this.root.render(this.el);
53241         
53242        
53243              
53244         this.items.each(function(f){
53245             f.render('x-form-el-'+f.id);
53246         });
53247
53248         if(this.buttons.length > 0){
53249             // tables are required to maintain order and for correct IE layout
53250             var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
53251                 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
53252                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
53253             }}, null, true);
53254             var tr = tb.getElementsByTagName('tr')[0];
53255             for(var i = 0, len = this.buttons.length; i < len; i++) {
53256                 var b = this.buttons[i];
53257                 var td = document.createElement('td');
53258                 td.className = 'x-form-btn-td';
53259                 b.render(tr.appendChild(td));
53260             }
53261         }
53262         if(this.monitorValid){ // initialize after render
53263             this.startMonitoring();
53264         }
53265         this.fireEvent('rendered', this);
53266         return this;
53267     },
53268
53269     /**
53270      * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
53271      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
53272      * object or a valid Roo.DomHelper element config
53273      * @param {Function} handler The function called when the button is clicked
53274      * @param {Object} scope (optional) The scope of the handler function
53275      * @return {Roo.Button}
53276      */
53277     addButton : function(config, handler, scope){
53278         var bc = {
53279             handler: handler,
53280             scope: scope,
53281             minWidth: this.minButtonWidth,
53282             hideParent:true
53283         };
53284         if(typeof config == "string"){
53285             bc.text = config;
53286         }else{
53287             Roo.apply(bc, config);
53288         }
53289         var btn = new Roo.Button(null, bc);
53290         this.buttons.push(btn);
53291         return btn;
53292     },
53293
53294      /**
53295      * Adds a series of form elements (using the xtype property as the factory method.
53296      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
53297      * @param {Object} config 
53298      */
53299     
53300     addxtype : function()
53301     {
53302         var ar = Array.prototype.slice.call(arguments, 0);
53303         var ret = false;
53304         for(var i = 0; i < ar.length; i++) {
53305             if (!ar[i]) {
53306                 continue; // skip -- if this happends something invalid got sent, we 
53307                 // should ignore it, as basically that interface element will not show up
53308                 // and that should be pretty obvious!!
53309             }
53310             
53311             if (Roo.form[ar[i].xtype]) {
53312                 ar[i].form = this;
53313                 var fe = Roo.factory(ar[i], Roo.form);
53314                 if (!ret) {
53315                     ret = fe;
53316                 }
53317                 fe.form = this;
53318                 if (fe.store) {
53319                     fe.store.form = this;
53320                 }
53321                 if (fe.isLayout) {  
53322                          
53323                     this.start(fe);
53324                     this.allItems.push(fe);
53325                     if (fe.items && fe.addxtype) {
53326                         fe.addxtype.apply(fe, fe.items);
53327                         delete fe.items;
53328                     }
53329                      this.end();
53330                     continue;
53331                 }
53332                 
53333                 
53334                  
53335                 this.add(fe);
53336               //  console.log('adding ' + ar[i].xtype);
53337             }
53338             if (ar[i].xtype == 'Button') {  
53339                 //console.log('adding button');
53340                 //console.log(ar[i]);
53341                 this.addButton(ar[i]);
53342                 this.allItems.push(fe);
53343                 continue;
53344             }
53345             
53346             if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
53347                 alert('end is not supported on xtype any more, use items');
53348             //    this.end();
53349             //    //console.log('adding end');
53350             }
53351             
53352         }
53353         return ret;
53354     },
53355     
53356     /**
53357      * Starts monitoring of the valid state of this form. Usually this is done by passing the config
53358      * option "monitorValid"
53359      */
53360     startMonitoring : function(){
53361         if(!this.bound){
53362             this.bound = true;
53363             Roo.TaskMgr.start({
53364                 run : this.bindHandler,
53365                 interval : this.monitorPoll || 200,
53366                 scope: this
53367             });
53368         }
53369     },
53370
53371     /**
53372      * Stops monitoring of the valid state of this form
53373      */
53374     stopMonitoring : function(){
53375         this.bound = false;
53376     },
53377
53378     // private
53379     bindHandler : function(){
53380         if(!this.bound){
53381             return false; // stops binding
53382         }
53383         var valid = true;
53384         this.items.each(function(f){
53385             if(!f.isValid(true)){
53386                 valid = false;
53387                 return false;
53388             }
53389         });
53390         for(var i = 0, len = this.buttons.length; i < len; i++){
53391             var btn = this.buttons[i];
53392             if(btn.formBind === true && btn.disabled === valid){
53393                 btn.setDisabled(!valid);
53394             }
53395         }
53396         this.fireEvent('clientvalidation', this, valid);
53397     }
53398     
53399     
53400     
53401     
53402     
53403     
53404     
53405     
53406 });
53407
53408
53409 // back compat
53410 Roo.Form = Roo.form.Form;
53411 /*
53412  * Based on:
53413  * Ext JS Library 1.1.1
53414  * Copyright(c) 2006-2007, Ext JS, LLC.
53415  *
53416  * Originally Released Under LGPL - original licence link has changed is not relivant.
53417  *
53418  * Fork - LGPL
53419  * <script type="text/javascript">
53420  */
53421
53422 // as we use this in bootstrap.
53423 Roo.namespace('Roo.form');
53424  /**
53425  * @class Roo.form.Action
53426  * Internal Class used to handle form actions
53427  * @constructor
53428  * @param {Roo.form.BasicForm} el The form element or its id
53429  * @param {Object} config Configuration options
53430  */
53431
53432  
53433  
53434 // define the action interface
53435 Roo.form.Action = function(form, options){
53436     this.form = form;
53437     this.options = options || {};
53438 };
53439 /**
53440  * Client Validation Failed
53441  * @const 
53442  */
53443 Roo.form.Action.CLIENT_INVALID = 'client';
53444 /**
53445  * Server Validation Failed
53446  * @const 
53447  */
53448 Roo.form.Action.SERVER_INVALID = 'server';
53449  /**
53450  * Connect to Server Failed
53451  * @const 
53452  */
53453 Roo.form.Action.CONNECT_FAILURE = 'connect';
53454 /**
53455  * Reading Data from Server Failed
53456  * @const 
53457  */
53458 Roo.form.Action.LOAD_FAILURE = 'load';
53459
53460 Roo.form.Action.prototype = {
53461     type : 'default',
53462     failureType : undefined,
53463     response : undefined,
53464     result : undefined,
53465
53466     // interface method
53467     run : function(options){
53468
53469     },
53470
53471     // interface method
53472     success : function(response){
53473
53474     },
53475
53476     // interface method
53477     handleResponse : function(response){
53478
53479     },
53480
53481     // default connection failure
53482     failure : function(response){
53483         
53484         this.response = response;
53485         this.failureType = Roo.form.Action.CONNECT_FAILURE;
53486         this.form.afterAction(this, false);
53487     },
53488
53489     processResponse : function(response){
53490         this.response = response;
53491         if(!response.responseText){
53492             return true;
53493         }
53494         this.result = this.handleResponse(response);
53495         return this.result;
53496     },
53497
53498     // utility functions used internally
53499     getUrl : function(appendParams){
53500         var url = this.options.url || this.form.url || this.form.el.dom.action;
53501         if(appendParams){
53502             var p = this.getParams();
53503             if(p){
53504                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
53505             }
53506         }
53507         return url;
53508     },
53509
53510     getMethod : function(){
53511         return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
53512     },
53513
53514     getParams : function(){
53515         var bp = this.form.baseParams;
53516         var p = this.options.params;
53517         if(p){
53518             if(typeof p == "object"){
53519                 p = Roo.urlEncode(Roo.applyIf(p, bp));
53520             }else if(typeof p == 'string' && bp){
53521                 p += '&' + Roo.urlEncode(bp);
53522             }
53523         }else if(bp){
53524             p = Roo.urlEncode(bp);
53525         }
53526         return p;
53527     },
53528
53529     createCallback : function(){
53530         return {
53531             success: this.success,
53532             failure: this.failure,
53533             scope: this,
53534             timeout: (this.form.timeout*1000),
53535             upload: this.form.fileUpload ? this.success : undefined
53536         };
53537     }
53538 };
53539
53540 Roo.form.Action.Submit = function(form, options){
53541     Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
53542 };
53543
53544 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
53545     type : 'submit',
53546
53547     haveProgress : false,
53548     uploadComplete : false,
53549     
53550     // uploadProgress indicator.
53551     uploadProgress : function()
53552     {
53553         if (!this.form.progressUrl) {
53554             return;
53555         }
53556         
53557         if (!this.haveProgress) {
53558             Roo.MessageBox.progress("Uploading", "Uploading");
53559         }
53560         if (this.uploadComplete) {
53561            Roo.MessageBox.hide();
53562            return;
53563         }
53564         
53565         this.haveProgress = true;
53566    
53567         var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
53568         
53569         var c = new Roo.data.Connection();
53570         c.request({
53571             url : this.form.progressUrl,
53572             params: {
53573                 id : uid
53574             },
53575             method: 'GET',
53576             success : function(req){
53577                //console.log(data);
53578                 var rdata = false;
53579                 var edata;
53580                 try  {
53581                    rdata = Roo.decode(req.responseText)
53582                 } catch (e) {
53583                     Roo.log("Invalid data from server..");
53584                     Roo.log(edata);
53585                     return;
53586                 }
53587                 if (!rdata || !rdata.success) {
53588                     Roo.log(rdata);
53589                     Roo.MessageBox.alert(Roo.encode(rdata));
53590                     return;
53591                 }
53592                 var data = rdata.data;
53593                 
53594                 if (this.uploadComplete) {
53595                    Roo.MessageBox.hide();
53596                    return;
53597                 }
53598                    
53599                 if (data){
53600                     Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
53601                        Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
53602                     );
53603                 }
53604                 this.uploadProgress.defer(2000,this);
53605             },
53606        
53607             failure: function(data) {
53608                 Roo.log('progress url failed ');
53609                 Roo.log(data);
53610             },
53611             scope : this
53612         });
53613            
53614     },
53615     
53616     
53617     run : function()
53618     {
53619         // run get Values on the form, so it syncs any secondary forms.
53620         this.form.getValues();
53621         
53622         var o = this.options;
53623         var method = this.getMethod();
53624         var isPost = method == 'POST';
53625         if(o.clientValidation === false || this.form.isValid()){
53626             
53627             if (this.form.progressUrl) {
53628                 this.form.findField('UPLOAD_IDENTIFIER').setValue(
53629                     (new Date() * 1) + '' + Math.random());
53630                     
53631             } 
53632             
53633             
53634             Roo.Ajax.request(Roo.apply(this.createCallback(), {
53635                 form:this.form.el.dom,
53636                 url:this.getUrl(!isPost),
53637                 method: method,
53638                 params:isPost ? this.getParams() : null,
53639                 isUpload: this.form.fileUpload,
53640                 formData : this.form.formData
53641             }));
53642             
53643             this.uploadProgress();
53644
53645         }else if (o.clientValidation !== false){ // client validation failed
53646             this.failureType = Roo.form.Action.CLIENT_INVALID;
53647             this.form.afterAction(this, false);
53648         }
53649     },
53650
53651     success : function(response)
53652     {
53653         this.uploadComplete= true;
53654         if (this.haveProgress) {
53655             Roo.MessageBox.hide();
53656         }
53657         
53658         
53659         var result = this.processResponse(response);
53660         if(result === true || result.success){
53661             this.form.afterAction(this, true);
53662             return;
53663         }
53664         if(result.errors){
53665             this.form.markInvalid(result.errors);
53666             this.failureType = Roo.form.Action.SERVER_INVALID;
53667         }
53668         this.form.afterAction(this, false);
53669     },
53670     failure : function(response)
53671     {
53672         this.uploadComplete= true;
53673         if (this.haveProgress) {
53674             Roo.MessageBox.hide();
53675         }
53676         
53677         this.response = response;
53678         this.failureType = Roo.form.Action.CONNECT_FAILURE;
53679         this.form.afterAction(this, false);
53680     },
53681     
53682     handleResponse : function(response){
53683         if(this.form.errorReader){
53684             var rs = this.form.errorReader.read(response);
53685             var errors = [];
53686             if(rs.records){
53687                 for(var i = 0, len = rs.records.length; i < len; i++) {
53688                     var r = rs.records[i];
53689                     errors[i] = r.data;
53690                 }
53691             }
53692             if(errors.length < 1){
53693                 errors = null;
53694             }
53695             return {
53696                 success : rs.success,
53697                 errors : errors
53698             };
53699         }
53700         var ret = false;
53701         try {
53702             ret = Roo.decode(response.responseText);
53703         } catch (e) {
53704             ret = {
53705                 success: false,
53706                 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
53707                 errors : []
53708             };
53709         }
53710         return ret;
53711         
53712     }
53713 });
53714
53715
53716 Roo.form.Action.Load = function(form, options){
53717     Roo.form.Action.Load.superclass.constructor.call(this, form, options);
53718     this.reader = this.form.reader;
53719 };
53720
53721 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
53722     type : 'load',
53723
53724     run : function(){
53725         
53726         Roo.Ajax.request(Roo.apply(
53727                 this.createCallback(), {
53728                     method:this.getMethod(),
53729                     url:this.getUrl(false),
53730                     params:this.getParams()
53731         }));
53732     },
53733
53734     success : function(response){
53735         
53736         var result = this.processResponse(response);
53737         if(result === true || !result.success || !result.data){
53738             this.failureType = Roo.form.Action.LOAD_FAILURE;
53739             this.form.afterAction(this, false);
53740             return;
53741         }
53742         this.form.clearInvalid();
53743         this.form.setValues(result.data);
53744         this.form.afterAction(this, true);
53745     },
53746
53747     handleResponse : function(response){
53748         if(this.form.reader){
53749             var rs = this.form.reader.read(response);
53750             var data = rs.records && rs.records[0] ? rs.records[0].data : null;
53751             return {
53752                 success : rs.success,
53753                 data : data
53754             };
53755         }
53756         return Roo.decode(response.responseText);
53757     }
53758 });
53759
53760 Roo.form.Action.ACTION_TYPES = {
53761     'load' : Roo.form.Action.Load,
53762     'submit' : Roo.form.Action.Submit
53763 };/*
53764  * Based on:
53765  * Ext JS Library 1.1.1
53766  * Copyright(c) 2006-2007, Ext JS, LLC.
53767  *
53768  * Originally Released Under LGPL - original licence link has changed is not relivant.
53769  *
53770  * Fork - LGPL
53771  * <script type="text/javascript">
53772  */
53773  
53774 /**
53775  * @class Roo.form.Layout
53776  * @extends Roo.Component
53777  * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
53778  * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
53779  * @constructor
53780  * @param {Object} config Configuration options
53781  */
53782 Roo.form.Layout = function(config){
53783     var xitems = [];
53784     if (config.items) {
53785         xitems = config.items;
53786         delete config.items;
53787     }
53788     Roo.form.Layout.superclass.constructor.call(this, config);
53789     this.stack = [];
53790     Roo.each(xitems, this.addxtype, this);
53791      
53792 };
53793
53794 Roo.extend(Roo.form.Layout, Roo.Component, {
53795     /**
53796      * @cfg {String/Object} autoCreate
53797      * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
53798      */
53799     /**
53800      * @cfg {String/Object/Function} style
53801      * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
53802      * a function which returns such a specification.
53803      */
53804     /**
53805      * @cfg {String} labelAlign
53806      * Valid values are "left," "top" and "right" (defaults to "left")
53807      */
53808     /**
53809      * @cfg {Number} labelWidth
53810      * Fixed width in pixels of all field labels (defaults to undefined)
53811      */
53812     /**
53813      * @cfg {Boolean} clear
53814      * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
53815      */
53816     clear : true,
53817     /**
53818      * @cfg {String} labelSeparator
53819      * The separator to use after field labels (defaults to ':')
53820      */
53821     labelSeparator : ':',
53822     /**
53823      * @cfg {Boolean} hideLabels
53824      * True to suppress the display of field labels in this layout (defaults to false)
53825      */
53826     hideLabels : false,
53827
53828     // private
53829     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
53830     
53831     isLayout : true,
53832     
53833     // private
53834     onRender : function(ct, position){
53835         if(this.el){ // from markup
53836             this.el = Roo.get(this.el);
53837         }else {  // generate
53838             var cfg = this.getAutoCreate();
53839             this.el = ct.createChild(cfg, position);
53840         }
53841         if(this.style){
53842             this.el.applyStyles(this.style);
53843         }
53844         if(this.labelAlign){
53845             this.el.addClass('x-form-label-'+this.labelAlign);
53846         }
53847         if(this.hideLabels){
53848             this.labelStyle = "display:none";
53849             this.elementStyle = "padding-left:0;";
53850         }else{
53851             if(typeof this.labelWidth == 'number'){
53852                 this.labelStyle = "width:"+this.labelWidth+"px;";
53853                 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
53854             }
53855             if(this.labelAlign == 'top'){
53856                 this.labelStyle = "width:auto;";
53857                 this.elementStyle = "padding-left:0;";
53858             }
53859         }
53860         var stack = this.stack;
53861         var slen = stack.length;
53862         if(slen > 0){
53863             if(!this.fieldTpl){
53864                 var t = new Roo.Template(
53865                     '<div class="x-form-item {5}">',
53866                         '<label for="{0}" style="{2}">{1}{4}</label>',
53867                         '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
53868                         '</div>',
53869                     '</div><div class="x-form-clear-left"></div>'
53870                 );
53871                 t.disableFormats = true;
53872                 t.compile();
53873                 Roo.form.Layout.prototype.fieldTpl = t;
53874             }
53875             for(var i = 0; i < slen; i++) {
53876                 if(stack[i].isFormField){
53877                     this.renderField(stack[i]);
53878                 }else{
53879                     this.renderComponent(stack[i]);
53880                 }
53881             }
53882         }
53883         if(this.clear){
53884             this.el.createChild({cls:'x-form-clear'});
53885         }
53886     },
53887
53888     // private
53889     renderField : function(f){
53890         f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
53891                f.id, //0
53892                f.fieldLabel, //1
53893                f.labelStyle||this.labelStyle||'', //2
53894                this.elementStyle||'', //3
53895                typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
53896                f.itemCls||this.itemCls||''  //5
53897        ], true).getPrevSibling());
53898     },
53899
53900     // private
53901     renderComponent : function(c){
53902         c.render(c.isLayout ? this.el : this.el.createChild());    
53903     },
53904     /**
53905      * Adds a object form elements (using the xtype property as the factory method.)
53906      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column
53907      * @param {Object} config 
53908      */
53909     addxtype : function(o)
53910     {
53911         // create the lement.
53912         o.form = this.form;
53913         var fe = Roo.factory(o, Roo.form);
53914         this.form.allItems.push(fe);
53915         this.stack.push(fe);
53916         
53917         if (fe.isFormField) {
53918             this.form.items.add(fe);
53919         }
53920          
53921         return fe;
53922     }
53923 });
53924
53925 /**
53926  * @class Roo.form.Column
53927  * @extends Roo.form.Layout
53928  * @children Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
53929  * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
53930  * @constructor
53931  * @param {Object} config Configuration options
53932  */
53933 Roo.form.Column = function(config){
53934     Roo.form.Column.superclass.constructor.call(this, config);
53935 };
53936
53937 Roo.extend(Roo.form.Column, Roo.form.Layout, {
53938     /**
53939      * @cfg {Number/String} width
53940      * The fixed width of the column in pixels or CSS value (defaults to "auto")
53941      */
53942     /**
53943      * @cfg {String/Object} autoCreate
53944      * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
53945      */
53946
53947     // private
53948     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
53949
53950     // private
53951     onRender : function(ct, position){
53952         Roo.form.Column.superclass.onRender.call(this, ct, position);
53953         if(this.width){
53954             this.el.setWidth(this.width);
53955         }
53956     }
53957 });
53958
53959
53960 /**
53961  * @class Roo.form.Row
53962  * @extends Roo.form.Layout
53963  * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
53964  * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
53965  * @constructor
53966  * @param {Object} config Configuration options
53967  */
53968
53969  
53970 Roo.form.Row = function(config){
53971     Roo.form.Row.superclass.constructor.call(this, config);
53972 };
53973  
53974 Roo.extend(Roo.form.Row, Roo.form.Layout, {
53975       /**
53976      * @cfg {Number/String} width
53977      * The fixed width of the column in pixels or CSS value (defaults to "auto")
53978      */
53979     /**
53980      * @cfg {Number/String} height
53981      * The fixed height of the column in pixels or CSS value (defaults to "auto")
53982      */
53983     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
53984     
53985     padWidth : 20,
53986     // private
53987     onRender : function(ct, position){
53988         //console.log('row render');
53989         if(!this.rowTpl){
53990             var t = new Roo.Template(
53991                 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
53992                     '<label for="{0}" style="{2}">{1}{4}</label>',
53993                     '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
53994                     '</div>',
53995                 '</div>'
53996             );
53997             t.disableFormats = true;
53998             t.compile();
53999             Roo.form.Layout.prototype.rowTpl = t;
54000         }
54001         this.fieldTpl = this.rowTpl;
54002         
54003         //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
54004         var labelWidth = 100;
54005         
54006         if ((this.labelAlign != 'top')) {
54007             if (typeof this.labelWidth == 'number') {
54008                 labelWidth = this.labelWidth
54009             }
54010             this.padWidth =  20 + labelWidth;
54011             
54012         }
54013         
54014         Roo.form.Column.superclass.onRender.call(this, ct, position);
54015         if(this.width){
54016             this.el.setWidth(this.width);
54017         }
54018         if(this.height){
54019             this.el.setHeight(this.height);
54020         }
54021     },
54022     
54023     // private
54024     renderField : function(f){
54025         f.fieldEl = this.fieldTpl.append(this.el, [
54026                f.id, f.fieldLabel,
54027                f.labelStyle||this.labelStyle||'',
54028                this.elementStyle||'',
54029                typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
54030                f.itemCls||this.itemCls||'',
54031                f.width ? f.width + this.padWidth : 160 + this.padWidth
54032        ],true);
54033     }
54034 });
54035  
54036
54037 /**
54038  * @class Roo.form.FieldSet
54039  * @extends Roo.form.Layout
54040  * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
54041  * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
54042  * @constructor
54043  * @param {Object} config Configuration options
54044  */
54045 Roo.form.FieldSet = function(config){
54046     Roo.form.FieldSet.superclass.constructor.call(this, config);
54047 };
54048
54049 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
54050     /**
54051      * @cfg {String} legend
54052      * The text to display as the legend for the FieldSet (defaults to '')
54053      */
54054     /**
54055      * @cfg {String/Object} autoCreate
54056      * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
54057      */
54058
54059     // private
54060     defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
54061
54062     // private
54063     onRender : function(ct, position){
54064         Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
54065         if(this.legend){
54066             this.setLegend(this.legend);
54067         }
54068     },
54069
54070     // private
54071     setLegend : function(text){
54072         if(this.rendered){
54073             this.el.child('legend').update(text);
54074         }
54075     }
54076 });/*
54077  * Based on:
54078  * Ext JS Library 1.1.1
54079  * Copyright(c) 2006-2007, Ext JS, LLC.
54080  *
54081  * Originally Released Under LGPL - original licence link has changed is not relivant.
54082  *
54083  * Fork - LGPL
54084  * <script type="text/javascript">
54085  */
54086 /**
54087  * @class Roo.form.VTypes
54088  * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
54089  * @static
54090  */
54091 Roo.form.VTypes = function(){
54092     // closure these in so they are only created once.
54093     var alpha = /^[a-zA-Z_]+$/;
54094     var alphanum = /^[a-zA-Z0-9_]+$/;
54095     var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
54096     var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
54097
54098     // All these messages and functions are configurable
54099     return {
54100         /**
54101          * The function used to validate email addresses
54102          * @param {String} value The email address
54103          */
54104         'email' : function(v){
54105             return email.test(v);
54106         },
54107         /**
54108          * The error text to display when the email validation function returns false
54109          * @type String
54110          */
54111         'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
54112         /**
54113          * The keystroke filter mask to be applied on email input
54114          * @type RegExp
54115          */
54116         'emailMask' : /[a-z0-9_\.\-@]/i,
54117
54118         /**
54119          * The function used to validate URLs
54120          * @param {String} value The URL
54121          */
54122         'url' : function(v){
54123             return url.test(v);
54124         },
54125         /**
54126          * The error text to display when the url validation function returns false
54127          * @type String
54128          */
54129         'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
54130         
54131         /**
54132          * The function used to validate alpha values
54133          * @param {String} value The value
54134          */
54135         'alpha' : function(v){
54136             return alpha.test(v);
54137         },
54138         /**
54139          * The error text to display when the alpha validation function returns false
54140          * @type String
54141          */
54142         'alphaText' : 'This field should only contain letters and _',
54143         /**
54144          * The keystroke filter mask to be applied on alpha input
54145          * @type RegExp
54146          */
54147         'alphaMask' : /[a-z_]/i,
54148
54149         /**
54150          * The function used to validate alphanumeric values
54151          * @param {String} value The value
54152          */
54153         'alphanum' : function(v){
54154             return alphanum.test(v);
54155         },
54156         /**
54157          * The error text to display when the alphanumeric validation function returns false
54158          * @type String
54159          */
54160         'alphanumText' : 'This field should only contain letters, numbers and _',
54161         /**
54162          * The keystroke filter mask to be applied on alphanumeric input
54163          * @type RegExp
54164          */
54165         'alphanumMask' : /[a-z0-9_]/i
54166     };
54167 }();//<script type="text/javascript">
54168
54169 /**
54170  * @class Roo.form.FCKeditor
54171  * @extends Roo.form.TextArea
54172  * Wrapper around the FCKEditor http://www.fckeditor.net
54173  * @constructor
54174  * Creates a new FCKeditor
54175  * @param {Object} config Configuration options
54176  */
54177 Roo.form.FCKeditor = function(config){
54178     Roo.form.FCKeditor.superclass.constructor.call(this, config);
54179     this.addEvents({
54180          /**
54181          * @event editorinit
54182          * Fired when the editor is initialized - you can add extra handlers here..
54183          * @param {FCKeditor} this
54184          * @param {Object} the FCK object.
54185          */
54186         editorinit : true
54187     });
54188     
54189     
54190 };
54191 Roo.form.FCKeditor.editors = { };
54192 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
54193 {
54194     //defaultAutoCreate : {
54195     //    tag : "textarea",style   : "width:100px;height:60px;" ,autocomplete    : "off"
54196     //},
54197     // private
54198     /**
54199      * @cfg {Object} fck options - see fck manual for details.
54200      */
54201     fckconfig : false,
54202     
54203     /**
54204      * @cfg {Object} fck toolbar set (Basic or Default)
54205      */
54206     toolbarSet : 'Basic',
54207     /**
54208      * @cfg {Object} fck BasePath
54209      */ 
54210     basePath : '/fckeditor/',
54211     
54212     
54213     frame : false,
54214     
54215     value : '',
54216     
54217    
54218     onRender : function(ct, position)
54219     {
54220         if(!this.el){
54221             this.defaultAutoCreate = {
54222                 tag: "textarea",
54223                 style:"width:300px;height:60px;",
54224                 autocomplete: "new-password"
54225             };
54226         }
54227         Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
54228         /*
54229         if(this.grow){
54230             this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
54231             if(this.preventScrollbars){
54232                 this.el.setStyle("overflow", "hidden");
54233             }
54234             this.el.setHeight(this.growMin);
54235         }
54236         */
54237         //console.log('onrender' + this.getId() );
54238         Roo.form.FCKeditor.editors[this.getId()] = this;
54239          
54240
54241         this.replaceTextarea() ;
54242         
54243     },
54244     
54245     getEditor : function() {
54246         return this.fckEditor;
54247     },
54248     /**
54249      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
54250      * @param {Mixed} value The value to set
54251      */
54252     
54253     
54254     setValue : function(value)
54255     {
54256         //console.log('setValue: ' + value);
54257         
54258         if(typeof(value) == 'undefined') { // not sure why this is happending...
54259             return;
54260         }
54261         Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
54262         
54263         //if(!this.el || !this.getEditor()) {
54264         //    this.value = value;
54265             //this.setValue.defer(100,this,[value]);    
54266         //    return;
54267         //} 
54268         
54269         if(!this.getEditor()) {
54270             return;
54271         }
54272         
54273         this.getEditor().SetData(value);
54274         
54275         //
54276
54277     },
54278
54279     /**
54280      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
54281      * @return {Mixed} value The field value
54282      */
54283     getValue : function()
54284     {
54285         
54286         if (this.frame && this.frame.dom.style.display == 'none') {
54287             return Roo.form.FCKeditor.superclass.getValue.call(this);
54288         }
54289         
54290         if(!this.el || !this.getEditor()) {
54291            
54292            // this.getValue.defer(100,this); 
54293             return this.value;
54294         }
54295        
54296         
54297         var value=this.getEditor().GetData();
54298         Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
54299         return Roo.form.FCKeditor.superclass.getValue.call(this);
54300         
54301
54302     },
54303
54304     /**
54305      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
54306      * @return {Mixed} value The field value
54307      */
54308     getRawValue : function()
54309     {
54310         if (this.frame && this.frame.dom.style.display == 'none') {
54311             return Roo.form.FCKeditor.superclass.getRawValue.call(this);
54312         }
54313         
54314         if(!this.el || !this.getEditor()) {
54315             //this.getRawValue.defer(100,this); 
54316             return this.value;
54317             return;
54318         }
54319         
54320         
54321         
54322         var value=this.getEditor().GetData();
54323         Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
54324         return Roo.form.FCKeditor.superclass.getRawValue.call(this);
54325          
54326     },
54327     
54328     setSize : function(w,h) {
54329         
54330         
54331         
54332         //if (this.frame && this.frame.dom.style.display == 'none') {
54333         //    Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
54334         //    return;
54335         //}
54336         //if(!this.el || !this.getEditor()) {
54337         //    this.setSize.defer(100,this, [w,h]); 
54338         //    return;
54339         //}
54340         
54341         
54342         
54343         Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
54344         
54345         this.frame.dom.setAttribute('width', w);
54346         this.frame.dom.setAttribute('height', h);
54347         this.frame.setSize(w,h);
54348         
54349     },
54350     
54351     toggleSourceEdit : function(value) {
54352         
54353       
54354          
54355         this.el.dom.style.display = value ? '' : 'none';
54356         this.frame.dom.style.display = value ?  'none' : '';
54357         
54358     },
54359     
54360     
54361     focus: function(tag)
54362     {
54363         if (this.frame.dom.style.display == 'none') {
54364             return Roo.form.FCKeditor.superclass.focus.call(this);
54365         }
54366         if(!this.el || !this.getEditor()) {
54367             this.focus.defer(100,this, [tag]); 
54368             return;
54369         }
54370         
54371         
54372         
54373         
54374         var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
54375         this.getEditor().Focus();
54376         if (tgs.length) {
54377             if (!this.getEditor().Selection.GetSelection()) {
54378                 this.focus.defer(100,this, [tag]); 
54379                 return;
54380             }
54381             
54382             
54383             var r = this.getEditor().EditorDocument.createRange();
54384             r.setStart(tgs[0],0);
54385             r.setEnd(tgs[0],0);
54386             this.getEditor().Selection.GetSelection().removeAllRanges();
54387             this.getEditor().Selection.GetSelection().addRange(r);
54388             this.getEditor().Focus();
54389         }
54390         
54391     },
54392     
54393     
54394     
54395     replaceTextarea : function()
54396     {
54397         if ( document.getElementById( this.getId() + '___Frame' ) ) {
54398             return ;
54399         }
54400         //if ( !this.checkBrowser || this._isCompatibleBrowser() )
54401         //{
54402             // We must check the elements firstly using the Id and then the name.
54403         var oTextarea = document.getElementById( this.getId() );
54404         
54405         var colElementsByName = document.getElementsByName( this.getId() ) ;
54406          
54407         oTextarea.style.display = 'none' ;
54408
54409         if ( oTextarea.tabIndex ) {            
54410             this.TabIndex = oTextarea.tabIndex ;
54411         }
54412         
54413         this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
54414         this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
54415         this.frame = Roo.get(this.getId() + '___Frame')
54416     },
54417     
54418     _getConfigHtml : function()
54419     {
54420         var sConfig = '' ;
54421
54422         for ( var o in this.fckconfig ) {
54423             sConfig += sConfig.length > 0  ? '&amp;' : '';
54424             sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
54425         }
54426
54427         return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
54428     },
54429     
54430     
54431     _getIFrameHtml : function()
54432     {
54433         var sFile = 'fckeditor.html' ;
54434         /* no idea what this is about..
54435         try
54436         {
54437             if ( (/fcksource=true/i).test( window.top.location.search ) )
54438                 sFile = 'fckeditor.original.html' ;
54439         }
54440         catch (e) { 
54441         */
54442
54443         var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
54444         sLink += this.toolbarSet ? ( '&amp;Toolbar=' + this.toolbarSet)  : '';
54445         
54446         
54447         var html = '<iframe id="' + this.getId() +
54448             '___Frame" src="' + sLink +
54449             '" width="' + this.width +
54450             '" height="' + this.height + '"' +
54451             (this.tabIndex ?  ' tabindex="' + this.tabIndex + '"' :'' ) +
54452             ' frameborder="0" scrolling="no"></iframe>' ;
54453
54454         return html ;
54455     },
54456     
54457     _insertHtmlBefore : function( html, element )
54458     {
54459         if ( element.insertAdjacentHTML )       {
54460             // IE
54461             element.insertAdjacentHTML( 'beforeBegin', html ) ;
54462         } else { // Gecko
54463             var oRange = document.createRange() ;
54464             oRange.setStartBefore( element ) ;
54465             var oFragment = oRange.createContextualFragment( html );
54466             element.parentNode.insertBefore( oFragment, element ) ;
54467         }
54468     }
54469     
54470     
54471   
54472     
54473     
54474     
54475     
54476
54477 });
54478
54479 //Roo.reg('fckeditor', Roo.form.FCKeditor);
54480
54481 function FCKeditor_OnComplete(editorInstance){
54482     var f = Roo.form.FCKeditor.editors[editorInstance.Name];
54483     f.fckEditor = editorInstance;
54484     //console.log("loaded");
54485     f.fireEvent('editorinit', f, editorInstance);
54486
54487   
54488
54489  
54490
54491
54492
54493
54494
54495
54496
54497
54498
54499
54500
54501
54502
54503
54504
54505 //<script type="text/javascript">
54506 /**
54507  * @class Roo.form.GridField
54508  * @extends Roo.form.Field
54509  * Embed a grid (or editable grid into a form)
54510  * STATUS ALPHA
54511  * 
54512  * This embeds a grid in a form, the value of the field should be the json encoded array of rows
54513  * it needs 
54514  * xgrid.store = Roo.data.Store
54515  * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
54516  * xgrid.store.reader = Roo.data.JsonReader 
54517  * 
54518  * 
54519  * @constructor
54520  * Creates a new GridField
54521  * @param {Object} config Configuration options
54522  */
54523 Roo.form.GridField = function(config){
54524     Roo.form.GridField.superclass.constructor.call(this, config);
54525      
54526 };
54527
54528 Roo.extend(Roo.form.GridField, Roo.form.Field,  {
54529     /**
54530      * @cfg {Number} width  - used to restrict width of grid..
54531      */
54532     width : 100,
54533     /**
54534      * @cfg {Number} height - used to restrict height of grid..
54535      */
54536     height : 50,
54537      /**
54538      * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
54539          * 
54540          *}
54541      */
54542     xgrid : false, 
54543     /**
54544      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
54545      * {tag: "input", type: "checkbox", autocomplete: "off"})
54546      */
54547    // defaultAutoCreate : { tag: 'div' },
54548     defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'new-password'},
54549     /**
54550      * @cfg {String} addTitle Text to include for adding a title.
54551      */
54552     addTitle : false,
54553     //
54554     onResize : function(){
54555         Roo.form.Field.superclass.onResize.apply(this, arguments);
54556     },
54557
54558     initEvents : function(){
54559         // Roo.form.Checkbox.superclass.initEvents.call(this);
54560         // has no events...
54561        
54562     },
54563
54564
54565     getResizeEl : function(){
54566         return this.wrap;
54567     },
54568
54569     getPositionEl : function(){
54570         return this.wrap;
54571     },
54572
54573     // private
54574     onRender : function(ct, position){
54575         
54576         this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
54577         var style = this.style;
54578         delete this.style;
54579         
54580         Roo.form.GridField.superclass.onRender.call(this, ct, position);
54581         this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
54582         this.viewEl = this.wrap.createChild({ tag: 'div' });
54583         if (style) {
54584             this.viewEl.applyStyles(style);
54585         }
54586         if (this.width) {
54587             this.viewEl.setWidth(this.width);
54588         }
54589         if (this.height) {
54590             this.viewEl.setHeight(this.height);
54591         }
54592         //if(this.inputValue !== undefined){
54593         //this.setValue(this.value);
54594         
54595         
54596         this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
54597         
54598         
54599         this.grid.render();
54600         this.grid.getDataSource().on('remove', this.refreshValue, this);
54601         this.grid.getDataSource().on('update', this.refreshValue, this);
54602         this.grid.on('afteredit', this.refreshValue, this);
54603  
54604     },
54605      
54606     
54607     /**
54608      * Sets the value of the item. 
54609      * @param {String} either an object  or a string..
54610      */
54611     setValue : function(v){
54612         //this.value = v;
54613         v = v || []; // empty set..
54614         // this does not seem smart - it really only affects memoryproxy grids..
54615         if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
54616             var ds = this.grid.getDataSource();
54617             // assumes a json reader..
54618             var data = {}
54619             data[ds.reader.meta.root ] =  typeof(v) == 'string' ? Roo.decode(v) : v;
54620             ds.loadData( data);
54621         }
54622         // clear selection so it does not get stale.
54623         if (this.grid.sm) { 
54624             this.grid.sm.clearSelections();
54625         }
54626         
54627         Roo.form.GridField.superclass.setValue.call(this, v);
54628         this.refreshValue();
54629         // should load data in the grid really....
54630     },
54631     
54632     // private
54633     refreshValue: function() {
54634          var val = [];
54635         this.grid.getDataSource().each(function(r) {
54636             val.push(r.data);
54637         });
54638         this.el.dom.value = Roo.encode(val);
54639     }
54640     
54641      
54642     
54643     
54644 });/*
54645  * Based on:
54646  * Ext JS Library 1.1.1
54647  * Copyright(c) 2006-2007, Ext JS, LLC.
54648  *
54649  * Originally Released Under LGPL - original licence link has changed is not relivant.
54650  *
54651  * Fork - LGPL
54652  * <script type="text/javascript">
54653  */
54654 /**
54655  * @class Roo.form.DisplayField
54656  * @extends Roo.form.Field
54657  * A generic Field to display non-editable data.
54658  * @cfg {Boolean} closable (true|false) default false
54659  * @constructor
54660  * Creates a new Display Field item.
54661  * @param {Object} config Configuration options
54662  */
54663 Roo.form.DisplayField = function(config){
54664     Roo.form.DisplayField.superclass.constructor.call(this, config);
54665     
54666     this.addEvents({
54667         /**
54668          * @event close
54669          * Fires after the click the close btn
54670              * @param {Roo.form.DisplayField} this
54671              */
54672         close : true
54673     });
54674 };
54675
54676 Roo.extend(Roo.form.DisplayField, Roo.form.TextField,  {
54677     inputType:      'hidden',
54678     allowBlank:     true,
54679     readOnly:         true,
54680     
54681  
54682     /**
54683      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
54684      */
54685     focusClass : undefined,
54686     /**
54687      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
54688      */
54689     fieldClass: 'x-form-field',
54690     
54691      /**
54692      * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
54693      */
54694     valueRenderer: undefined,
54695     
54696     width: 100,
54697     /**
54698      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
54699      * {tag: "input", type: "checkbox", autocomplete: "off"})
54700      */
54701      
54702  //   defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
54703  
54704     closable : false,
54705     
54706     onResize : function(){
54707         Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
54708         
54709     },
54710
54711     initEvents : function(){
54712         // Roo.form.Checkbox.superclass.initEvents.call(this);
54713         // has no events...
54714         
54715         if(this.closable){
54716             this.closeEl.on('click', this.onClose, this);
54717         }
54718        
54719     },
54720
54721
54722     getResizeEl : function(){
54723         return this.wrap;
54724     },
54725
54726     getPositionEl : function(){
54727         return this.wrap;
54728     },
54729
54730     // private
54731     onRender : function(ct, position){
54732         
54733         Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
54734         //if(this.inputValue !== undefined){
54735         this.wrap = this.el.wrap();
54736         
54737         this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
54738         
54739         if(this.closable){
54740             this.closeEl = this.wrap.createChild({ tag: 'div', cls: 'x-dlg-close'});
54741         }
54742         
54743         if (this.bodyStyle) {
54744             this.viewEl.applyStyles(this.bodyStyle);
54745         }
54746         //this.viewEl.setStyle('padding', '2px');
54747         
54748         this.setValue(this.value);
54749         
54750     },
54751 /*
54752     // private
54753     initValue : Roo.emptyFn,
54754
54755   */
54756
54757         // private
54758     onClick : function(){
54759         
54760     },
54761
54762     /**
54763      * Sets the checked state of the checkbox.
54764      * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
54765      */
54766     setValue : function(v){
54767         this.value = v;
54768         var html = this.valueRenderer ?  this.valueRenderer(v) : String.format('{0}', v);
54769         // this might be called before we have a dom element..
54770         if (!this.viewEl) {
54771             return;
54772         }
54773         this.viewEl.dom.innerHTML = html;
54774         Roo.form.DisplayField.superclass.setValue.call(this, v);
54775
54776     },
54777     
54778     onClose : function(e)
54779     {
54780         e.preventDefault();
54781         
54782         this.fireEvent('close', this);
54783     }
54784 });/*
54785  * 
54786  * Licence- LGPL
54787  * 
54788  */
54789
54790 /**
54791  * @class Roo.form.DayPicker
54792  * @extends Roo.form.Field
54793  * A Day picker show [M] [T] [W] ....
54794  * @constructor
54795  * Creates a new Day Picker
54796  * @param {Object} config Configuration options
54797  */
54798 Roo.form.DayPicker= function(config){
54799     Roo.form.DayPicker.superclass.constructor.call(this, config);
54800      
54801 };
54802
54803 Roo.extend(Roo.form.DayPicker, Roo.form.Field,  {
54804     /**
54805      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
54806      */
54807     focusClass : undefined,
54808     /**
54809      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
54810      */
54811     fieldClass: "x-form-field",
54812    
54813     /**
54814      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
54815      * {tag: "input", type: "checkbox", autocomplete: "off"})
54816      */
54817     defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "new-password"},
54818     
54819    
54820     actionMode : 'viewEl', 
54821     //
54822     // private
54823  
54824     inputType : 'hidden',
54825     
54826      
54827     inputElement: false, // real input element?
54828     basedOn: false, // ????
54829     
54830     isFormField: true, // not sure where this is needed!!!!
54831
54832     onResize : function(){
54833         Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
54834         if(!this.boxLabel){
54835             this.el.alignTo(this.wrap, 'c-c');
54836         }
54837     },
54838
54839     initEvents : function(){
54840         Roo.form.Checkbox.superclass.initEvents.call(this);
54841         this.el.on("click", this.onClick,  this);
54842         this.el.on("change", this.onClick,  this);
54843     },
54844
54845
54846     getResizeEl : function(){
54847         return this.wrap;
54848     },
54849
54850     getPositionEl : function(){
54851         return this.wrap;
54852     },
54853
54854     
54855     // private
54856     onRender : function(ct, position){
54857         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
54858        
54859         this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
54860         
54861         var r1 = '<table><tr>';
54862         var r2 = '<tr class="x-form-daypick-icons">';
54863         for (var i=0; i < 7; i++) {
54864             r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
54865             r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL  +'"></td>';
54866         }
54867         
54868         var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
54869         viewEl.select('img').on('click', this.onClick, this);
54870         this.viewEl = viewEl;   
54871         
54872         
54873         // this will not work on Chrome!!!
54874         this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
54875         this.el.on('propertychange', this.setFromHidden,  this);  //ie
54876         
54877         
54878           
54879
54880     },
54881
54882     // private
54883     initValue : Roo.emptyFn,
54884
54885     /**
54886      * Returns the checked state of the checkbox.
54887      * @return {Boolean} True if checked, else false
54888      */
54889     getValue : function(){
54890         return this.el.dom.value;
54891         
54892     },
54893
54894         // private
54895     onClick : function(e){ 
54896         //this.setChecked(!this.checked);
54897         Roo.get(e.target).toggleClass('x-menu-item-checked');
54898         this.refreshValue();
54899         //if(this.el.dom.checked != this.checked){
54900         //    this.setValue(this.el.dom.checked);
54901        // }
54902     },
54903     
54904     // private
54905     refreshValue : function()
54906     {
54907         var val = '';
54908         this.viewEl.select('img',true).each(function(e,i,n)  {
54909             val += e.is(".x-menu-item-checked") ? String(n) : '';
54910         });
54911         this.setValue(val, true);
54912     },
54913
54914     /**
54915      * Sets the checked state of the checkbox.
54916      * On is always based on a string comparison between inputValue and the param.
54917      * @param {Boolean/String} value - the value to set 
54918      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
54919      */
54920     setValue : function(v,suppressEvent){
54921         if (!this.el.dom) {
54922             return;
54923         }
54924         var old = this.el.dom.value ;
54925         this.el.dom.value = v;
54926         if (suppressEvent) {
54927             return ;
54928         }
54929          
54930         // update display..
54931         this.viewEl.select('img',true).each(function(e,i,n)  {
54932             
54933             var on = e.is(".x-menu-item-checked");
54934             var newv = v.indexOf(String(n)) > -1;
54935             if (on != newv) {
54936                 e.toggleClass('x-menu-item-checked');
54937             }
54938             
54939         });
54940         
54941         
54942         this.fireEvent('change', this, v, old);
54943         
54944         
54945     },
54946    
54947     // handle setting of hidden value by some other method!!?!?
54948     setFromHidden: function()
54949     {
54950         if(!this.el){
54951             return;
54952         }
54953         //console.log("SET FROM HIDDEN");
54954         //alert('setFrom hidden');
54955         this.setValue(this.el.dom.value);
54956     },
54957     
54958     onDestroy : function()
54959     {
54960         if(this.viewEl){
54961             Roo.get(this.viewEl).remove();
54962         }
54963          
54964         Roo.form.DayPicker.superclass.onDestroy.call(this);
54965     }
54966
54967 });/*
54968  * RooJS Library 1.1.1
54969  * Copyright(c) 2008-2011  Alan Knowles
54970  *
54971  * License - LGPL
54972  */
54973  
54974
54975 /**
54976  * @class Roo.form.ComboCheck
54977  * @extends Roo.form.ComboBox
54978  * A combobox for multiple select items.
54979  *
54980  * FIXME - could do with a reset button..
54981  * 
54982  * @constructor
54983  * Create a new ComboCheck
54984  * @param {Object} config Configuration options
54985  */
54986 Roo.form.ComboCheck = function(config){
54987     Roo.form.ComboCheck.superclass.constructor.call(this, config);
54988     // should verify some data...
54989     // like
54990     // hiddenName = required..
54991     // displayField = required
54992     // valudField == required
54993     var req= [ 'hiddenName', 'displayField', 'valueField' ];
54994     var _t = this;
54995     Roo.each(req, function(e) {
54996         if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
54997             throw "Roo.form.ComboCheck : missing value for: " + e;
54998         }
54999     });
55000     
55001     
55002 };
55003
55004 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
55005      
55006      
55007     editable : false,
55008      
55009     selectedClass: 'x-menu-item-checked', 
55010     
55011     // private
55012     onRender : function(ct, position){
55013         var _t = this;
55014         
55015         
55016         
55017         if(!this.tpl){
55018             var cls = 'x-combo-list';
55019
55020             
55021             this.tpl =  new Roo.Template({
55022                 html :  '<div class="'+cls+'-item x-menu-check-item">' +
55023                    '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' + 
55024                    '<span>{' + this.displayField + '}</span>' +
55025                     '</div>' 
55026                 
55027             });
55028         }
55029  
55030         
55031         Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
55032         this.view.singleSelect = false;
55033         this.view.multiSelect = true;
55034         this.view.toggleSelect = true;
55035         this.pageTb.add(new Roo.Toolbar.Fill(), {
55036             
55037             text: 'Done',
55038             handler: function()
55039             {
55040                 _t.collapse();
55041             }
55042         });
55043     },
55044     
55045     onViewOver : function(e, t){
55046         // do nothing...
55047         return;
55048         
55049     },
55050     
55051     onViewClick : function(doFocus,index){
55052         return;
55053         
55054     },
55055     select: function () {
55056         //Roo.log("SELECT CALLED");
55057     },
55058      
55059     selectByValue : function(xv, scrollIntoView){
55060         var ar = this.getValueArray();
55061         var sels = [];
55062         
55063         Roo.each(ar, function(v) {
55064             if(v === undefined || v === null){
55065                 return;
55066             }
55067             var r = this.findRecord(this.valueField, v);
55068             if(r){
55069                 sels.push(this.store.indexOf(r))
55070                 
55071             }
55072         },this);
55073         this.view.select(sels);
55074         return false;
55075     },
55076     
55077     
55078     
55079     onSelect : function(record, index){
55080        // Roo.log("onselect Called");
55081        // this is only called by the clear button now..
55082         this.view.clearSelections();
55083         this.setValue('[]');
55084         if (this.value != this.valueBefore) {
55085             this.fireEvent('change', this, this.value, this.valueBefore);
55086             this.valueBefore = this.value;
55087         }
55088     },
55089     getValueArray : function()
55090     {
55091         var ar = [] ;
55092         
55093         try {
55094             //Roo.log(this.value);
55095             if (typeof(this.value) == 'undefined') {
55096                 return [];
55097             }
55098             var ar = Roo.decode(this.value);
55099             return  ar instanceof Array ? ar : []; //?? valid?
55100             
55101         } catch(e) {
55102             Roo.log(e + "\nRoo.form.ComboCheck:getValueArray  invalid data:" + this.getValue());
55103             return [];
55104         }
55105          
55106     },
55107     expand : function ()
55108     {
55109         
55110         Roo.form.ComboCheck.superclass.expand.call(this);
55111         this.valueBefore = typeof(this.value) == 'undefined' ? '' : this.value;
55112         //this.valueBefore = typeof(this.valueBefore) == 'undefined' ? '' : this.valueBefore;
55113         
55114
55115     },
55116     
55117     collapse : function(){
55118         Roo.form.ComboCheck.superclass.collapse.call(this);
55119         var sl = this.view.getSelectedIndexes();
55120         var st = this.store;
55121         var nv = [];
55122         var tv = [];
55123         var r;
55124         Roo.each(sl, function(i) {
55125             r = st.getAt(i);
55126             nv.push(r.get(this.valueField));
55127         },this);
55128         this.setValue(Roo.encode(nv));
55129         if (this.value != this.valueBefore) {
55130
55131             this.fireEvent('change', this, this.value, this.valueBefore);
55132             this.valueBefore = this.value;
55133         }
55134         
55135     },
55136     
55137     setValue : function(v){
55138         // Roo.log(v);
55139         this.value = v;
55140         
55141         var vals = this.getValueArray();
55142         var tv = [];
55143         Roo.each(vals, function(k) {
55144             var r = this.findRecord(this.valueField, k);
55145             if(r){
55146                 tv.push(r.data[this.displayField]);
55147             }else if(this.valueNotFoundText !== undefined){
55148                 tv.push( this.valueNotFoundText );
55149             }
55150         },this);
55151        // Roo.log(tv);
55152         
55153         Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
55154         this.hiddenField.value = v;
55155         this.value = v;
55156     }
55157     
55158 });/*
55159  * Based on:
55160  * Ext JS Library 1.1.1
55161  * Copyright(c) 2006-2007, Ext JS, LLC.
55162  *
55163  * Originally Released Under LGPL - original licence link has changed is not relivant.
55164  *
55165  * Fork - LGPL
55166  * <script type="text/javascript">
55167  */
55168  
55169 /**
55170  * @class Roo.form.Signature
55171  * @extends Roo.form.Field
55172  * Signature field.  
55173  * @constructor
55174  * 
55175  * @param {Object} config Configuration options
55176  */
55177
55178 Roo.form.Signature = function(config){
55179     Roo.form.Signature.superclass.constructor.call(this, config);
55180     
55181     this.addEvents({// not in used??
55182          /**
55183          * @event confirm
55184          * Fires when the 'confirm' icon is pressed (add a listener to enable add button)
55185              * @param {Roo.form.Signature} combo This combo box
55186              */
55187         'confirm' : true,
55188         /**
55189          * @event reset
55190          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
55191              * @param {Roo.form.ComboBox} combo This combo box
55192              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
55193              */
55194         'reset' : true
55195     });
55196 };
55197
55198 Roo.extend(Roo.form.Signature, Roo.form.Field,  {
55199     /**
55200      * @cfg {Object} labels Label to use when rendering a form.
55201      * defaults to 
55202      * labels : { 
55203      *      clear : "Clear",
55204      *      confirm : "Confirm"
55205      *  }
55206      */
55207     labels : { 
55208         clear : "Clear",
55209         confirm : "Confirm"
55210     },
55211     /**
55212      * @cfg {Number} width The signature panel width (defaults to 300)
55213      */
55214     width: 300,
55215     /**
55216      * @cfg {Number} height The signature panel height (defaults to 100)
55217      */
55218     height : 100,
55219     /**
55220      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to false)
55221      */
55222     allowBlank : false,
55223     
55224     //private
55225     // {Object} signPanel The signature SVG panel element (defaults to {})
55226     signPanel : {},
55227     // {Boolean} isMouseDown False to validate that the mouse down event (defaults to false)
55228     isMouseDown : false,
55229     // {Boolean} isConfirmed validate the signature is confirmed or not for submitting form (defaults to false)
55230     isConfirmed : false,
55231     // {String} signatureTmp SVG mapping string (defaults to empty string)
55232     signatureTmp : '',
55233     
55234     
55235     defaultAutoCreate : { // modified by initCompnoent..
55236         tag: "input",
55237         type:"hidden"
55238     },
55239
55240     // private
55241     onRender : function(ct, position){
55242         
55243         Roo.form.Signature.superclass.onRender.call(this, ct, position);
55244         
55245         this.wrap = this.el.wrap({
55246             cls:'x-form-signature-wrap', style : 'width: ' + this.width + 'px', cn:{cls:'x-form-signature'}
55247         });
55248         
55249         this.createToolbar(this);
55250         this.signPanel = this.wrap.createChild({
55251                 tag: 'div',
55252                 style: 'width: ' + this.width + 'px; height: ' + this.height + 'px; border: 0;'
55253             }, this.el
55254         );
55255             
55256         this.svgID = Roo.id();
55257         this.svgEl = this.signPanel.createChild({
55258               xmlns : 'http://www.w3.org/2000/svg',
55259               tag : 'svg',
55260               id : this.svgID + "-svg",
55261               width: this.width,
55262               height: this.height,
55263               viewBox: '0 0 '+this.width+' '+this.height,
55264               cn : [
55265                 {
55266                     tag: "rect",
55267                     id: this.svgID + "-svg-r",
55268                     width: this.width,
55269                     height: this.height,
55270                     fill: "#ffa"
55271                 },
55272                 {
55273                     tag: "line",
55274                     id: this.svgID + "-svg-l",
55275                     x1: "0", // start
55276                     y1: (this.height*0.8), // start set the line in 80% of height
55277                     x2: this.width, // end
55278                     y2: (this.height*0.8), // end set the line in 80% of height
55279                     'stroke': "#666",
55280                     'stroke-width': "1",
55281                     'stroke-dasharray': "3",
55282                     'shape-rendering': "crispEdges",
55283                     'pointer-events': "none"
55284                 },
55285                 {
55286                     tag: "path",
55287                     id: this.svgID + "-svg-p",
55288                     'stroke': "navy",
55289                     'stroke-width': "3",
55290                     'fill': "none",
55291                     'pointer-events': 'none'
55292                 }
55293               ]
55294         });
55295         this.createSVG();
55296         this.svgBox = this.svgEl.dom.getScreenCTM();
55297     },
55298     createSVG : function(){ 
55299         var svg = this.signPanel;
55300         var r = svg.select('#'+ this.svgID + '-svg-r', true).first().dom;
55301         var t = this;
55302
55303         r.addEventListener('mousedown', function(e) { return t.down(e); }, false);
55304         r.addEventListener('mousemove', function(e) { return t.move(e); }, false);
55305         r.addEventListener('mouseup', function(e) { return t.up(e); }, false);
55306         r.addEventListener('mouseout', function(e) { return t.up(e); }, false);
55307         r.addEventListener('touchstart', function(e) { return t.down(e); }, false);
55308         r.addEventListener('touchmove', function(e) { return t.move(e); }, false);
55309         r.addEventListener('touchend', function(e) { return t.up(e); }, false);
55310         
55311     },
55312     isTouchEvent : function(e){
55313         return e.type.match(/^touch/);
55314     },
55315     getCoords : function (e) {
55316         var pt    = this.svgEl.dom.createSVGPoint();
55317         pt.x = e.clientX; 
55318         pt.y = e.clientY;
55319         if (this.isTouchEvent(e)) {
55320             pt.x =  e.targetTouches[0].clientX;
55321             pt.y = e.targetTouches[0].clientY;
55322         }
55323         var a = this.svgEl.dom.getScreenCTM();
55324         var b = a.inverse();
55325         var mx = pt.matrixTransform(b);
55326         return mx.x + ',' + mx.y;
55327     },
55328     //mouse event headler 
55329     down : function (e) {
55330         this.signatureTmp += 'M' + this.getCoords(e) + ' ';
55331         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr('d', this.signatureTmp);
55332         
55333         this.isMouseDown = true;
55334         
55335         e.preventDefault();
55336     },
55337     move : function (e) {
55338         if (this.isMouseDown) {
55339             this.signatureTmp += 'L' + this.getCoords(e) + ' ';
55340             this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', this.signatureTmp);
55341         }
55342         
55343         e.preventDefault();
55344     },
55345     up : function (e) {
55346         this.isMouseDown = false;
55347         var sp = this.signatureTmp.split(' ');
55348         
55349         if(sp.length > 1){
55350             if(!sp[sp.length-2].match(/^L/)){
55351                 sp.pop();
55352                 sp.pop();
55353                 sp.push("");
55354                 this.signatureTmp = sp.join(" ");
55355             }
55356         }
55357         if(this.getValue() != this.signatureTmp){
55358             this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
55359             this.isConfirmed = false;
55360         }
55361         e.preventDefault();
55362     },
55363     
55364     /**
55365      * Protected method that will not generally be called directly. It
55366      * is called when the editor creates its toolbar. Override this method if you need to
55367      * add custom toolbar buttons.
55368      * @param {HtmlEditor} editor
55369      */
55370     createToolbar : function(editor){
55371          function btn(id, toggle, handler){
55372             var xid = fid + '-'+ id ;
55373             return {
55374                 id : xid,
55375                 cmd : id,
55376                 cls : 'x-btn-icon x-edit-'+id,
55377                 enableToggle:toggle !== false,
55378                 scope: editor, // was editor...
55379                 handler:handler||editor.relayBtnCmd,
55380                 clickEvent:'mousedown',
55381                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
55382                 tabIndex:-1
55383             };
55384         }
55385         
55386         
55387         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
55388         this.tb = tb;
55389         this.tb.add(
55390            {
55391                 cls : ' x-signature-btn x-signature-'+id,
55392                 scope: editor, // was editor...
55393                 handler: this.reset,
55394                 clickEvent:'mousedown',
55395                 text: this.labels.clear
55396             },
55397             {
55398                  xtype : 'Fill',
55399                  xns: Roo.Toolbar
55400             }, 
55401             {
55402                 cls : '  x-signature-btn x-signature-'+id,
55403                 scope: editor, // was editor...
55404                 handler: this.confirmHandler,
55405                 clickEvent:'mousedown',
55406                 text: this.labels.confirm
55407             }
55408         );
55409     
55410     },
55411     //public
55412     /**
55413      * when user is clicked confirm then show this image.....
55414      * 
55415      * @return {String} Image Data URI
55416      */
55417     getImageDataURI : function(){
55418         var svg = this.svgEl.dom.parentNode.innerHTML;
55419         var src = 'data:image/svg+xml;base64,'+window.btoa(svg);
55420         return src; 
55421     },
55422     /**
55423      * 
55424      * @return {Boolean} this.isConfirmed
55425      */
55426     getConfirmed : function(){
55427         return this.isConfirmed;
55428     },
55429     /**
55430      * 
55431      * @return {Number} this.width
55432      */
55433     getWidth : function(){
55434         return this.width;
55435     },
55436     /**
55437      * 
55438      * @return {Number} this.height
55439      */
55440     getHeight : function(){
55441         return this.height;
55442     },
55443     // private
55444     getSignature : function(){
55445         return this.signatureTmp;
55446     },
55447     // private
55448     reset : function(){
55449         this.signatureTmp = '';
55450         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
55451         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', '');
55452         this.isConfirmed = false;
55453         Roo.form.Signature.superclass.reset.call(this);
55454     },
55455     setSignature : function(s){
55456         this.signatureTmp = s;
55457         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
55458         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', s);
55459         this.setValue(s);
55460         this.isConfirmed = false;
55461         Roo.form.Signature.superclass.reset.call(this);
55462     }, 
55463     test : function(){
55464 //        Roo.log(this.signPanel.dom.contentWindow.up())
55465     },
55466     //private
55467     setConfirmed : function(){
55468         
55469         
55470         
55471 //        Roo.log(Roo.get(this.signPanel.dom.contentWindow.r).attr('fill', '#cfc'));
55472     },
55473     // private
55474     confirmHandler : function(){
55475         if(!this.getSignature()){
55476             return;
55477         }
55478         
55479         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#cfc');
55480         this.setValue(this.getSignature());
55481         this.isConfirmed = true;
55482         
55483         this.fireEvent('confirm', this);
55484     },
55485     // private
55486     // Subclasses should provide the validation implementation by overriding this
55487     validateValue : function(value){
55488         if(this.allowBlank){
55489             return true;
55490         }
55491         
55492         if(this.isConfirmed){
55493             return true;
55494         }
55495         return false;
55496     }
55497 });/*
55498  * Based on:
55499  * Ext JS Library 1.1.1
55500  * Copyright(c) 2006-2007, Ext JS, LLC.
55501  *
55502  * Originally Released Under LGPL - original licence link has changed is not relivant.
55503  *
55504  * Fork - LGPL
55505  * <script type="text/javascript">
55506  */
55507  
55508
55509 /**
55510  * @class Roo.form.ComboBox
55511  * @extends Roo.form.TriggerField
55512  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
55513  * @constructor
55514  * Create a new ComboBox.
55515  * @param {Object} config Configuration options
55516  */
55517 Roo.form.Select = function(config){
55518     Roo.form.Select.superclass.constructor.call(this, config);
55519      
55520 };
55521
55522 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
55523     /**
55524      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
55525      */
55526     /**
55527      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
55528      * rendering into an Roo.Editor, defaults to false)
55529      */
55530     /**
55531      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
55532      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
55533      */
55534     /**
55535      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
55536      */
55537     /**
55538      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
55539      * the dropdown list (defaults to undefined, with no header element)
55540      */
55541
55542      /**
55543      * @cfg {String/Roo.Template} tpl The template to use to render the output
55544      */
55545      
55546     // private
55547     defaultAutoCreate : {tag: "select"  },
55548     /**
55549      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
55550      */
55551     listWidth: undefined,
55552     /**
55553      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
55554      * mode = 'remote' or 'text' if mode = 'local')
55555      */
55556     displayField: undefined,
55557     /**
55558      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
55559      * mode = 'remote' or 'value' if mode = 'local'). 
55560      * Note: use of a valueField requires the user make a selection
55561      * in order for a value to be mapped.
55562      */
55563     valueField: undefined,
55564     
55565     
55566     /**
55567      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
55568      * field's data value (defaults to the underlying DOM element's name)
55569      */
55570     hiddenName: undefined,
55571     /**
55572      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
55573      */
55574     listClass: '',
55575     /**
55576      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
55577      */
55578     selectedClass: 'x-combo-selected',
55579     /**
55580      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
55581      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
55582      * which displays a downward arrow icon).
55583      */
55584     triggerClass : 'x-form-arrow-trigger',
55585     /**
55586      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
55587      */
55588     shadow:'sides',
55589     /**
55590      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
55591      * anchor positions (defaults to 'tl-bl')
55592      */
55593     listAlign: 'tl-bl?',
55594     /**
55595      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
55596      */
55597     maxHeight: 300,
55598     /**
55599      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
55600      * query specified by the allQuery config option (defaults to 'query')
55601      */
55602     triggerAction: 'query',
55603     /**
55604      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
55605      * (defaults to 4, does not apply if editable = false)
55606      */
55607     minChars : 4,
55608     /**
55609      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
55610      * delay (typeAheadDelay) if it matches a known value (defaults to false)
55611      */
55612     typeAhead: false,
55613     /**
55614      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
55615      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
55616      */
55617     queryDelay: 500,
55618     /**
55619      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
55620      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
55621      */
55622     pageSize: 0,
55623     /**
55624      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
55625      * when editable = true (defaults to false)
55626      */
55627     selectOnFocus:false,
55628     /**
55629      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
55630      */
55631     queryParam: 'query',
55632     /**
55633      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
55634      * when mode = 'remote' (defaults to 'Loading...')
55635      */
55636     loadingText: 'Loading...',
55637     /**
55638      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
55639      */
55640     resizable: false,
55641     /**
55642      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
55643      */
55644     handleHeight : 8,
55645     /**
55646      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
55647      * traditional select (defaults to true)
55648      */
55649     editable: true,
55650     /**
55651      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
55652      */
55653     allQuery: '',
55654     /**
55655      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
55656      */
55657     mode: 'remote',
55658     /**
55659      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
55660      * listWidth has a higher value)
55661      */
55662     minListWidth : 70,
55663     /**
55664      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
55665      * allow the user to set arbitrary text into the field (defaults to false)
55666      */
55667     forceSelection:false,
55668     /**
55669      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
55670      * if typeAhead = true (defaults to 250)
55671      */
55672     typeAheadDelay : 250,
55673     /**
55674      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
55675      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
55676      */
55677     valueNotFoundText : undefined,
55678     
55679     /**
55680      * @cfg {String} defaultValue The value displayed after loading the store.
55681      */
55682     defaultValue: '',
55683     
55684     /**
55685      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
55686      */
55687     blockFocus : false,
55688     
55689     /**
55690      * @cfg {Boolean} disableClear Disable showing of clear button.
55691      */
55692     disableClear : false,
55693     /**
55694      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
55695      */
55696     alwaysQuery : false,
55697     
55698     //private
55699     addicon : false,
55700     editicon: false,
55701     
55702     // element that contains real text value.. (when hidden is used..)
55703      
55704     // private
55705     onRender : function(ct, position){
55706         Roo.form.Field.prototype.onRender.call(this, ct, position);
55707         
55708         if(this.store){
55709             this.store.on('beforeload', this.onBeforeLoad, this);
55710             this.store.on('load', this.onLoad, this);
55711             this.store.on('loadexception', this.onLoadException, this);
55712             this.store.load({});
55713         }
55714         
55715         
55716         
55717     },
55718
55719     // private
55720     initEvents : function(){
55721         //Roo.form.ComboBox.superclass.initEvents.call(this);
55722  
55723     },
55724
55725     onDestroy : function(){
55726        
55727         if(this.store){
55728             this.store.un('beforeload', this.onBeforeLoad, this);
55729             this.store.un('load', this.onLoad, this);
55730             this.store.un('loadexception', this.onLoadException, this);
55731         }
55732         //Roo.form.ComboBox.superclass.onDestroy.call(this);
55733     },
55734
55735     // private
55736     fireKey : function(e){
55737         if(e.isNavKeyPress() && !this.list.isVisible()){
55738             this.fireEvent("specialkey", this, e);
55739         }
55740     },
55741
55742     // private
55743     onResize: function(w, h){
55744         
55745         return; 
55746     
55747         
55748     },
55749
55750     /**
55751      * Allow or prevent the user from directly editing the field text.  If false is passed,
55752      * the user will only be able to select from the items defined in the dropdown list.  This method
55753      * is the runtime equivalent of setting the 'editable' config option at config time.
55754      * @param {Boolean} value True to allow the user to directly edit the field text
55755      */
55756     setEditable : function(value){
55757          
55758     },
55759
55760     // private
55761     onBeforeLoad : function(){
55762         
55763         Roo.log("Select before load");
55764         return;
55765     
55766         this.innerList.update(this.loadingText ?
55767                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
55768         //this.restrictHeight();
55769         this.selectedIndex = -1;
55770     },
55771
55772     // private
55773     onLoad : function(){
55774
55775     
55776         var dom = this.el.dom;
55777         dom.innerHTML = '';
55778          var od = dom.ownerDocument;
55779          
55780         if (this.emptyText) {
55781             var op = od.createElement('option');
55782             op.setAttribute('value', '');
55783             op.innerHTML = String.format('{0}', this.emptyText);
55784             dom.appendChild(op);
55785         }
55786         if(this.store.getCount() > 0){
55787            
55788             var vf = this.valueField;
55789             var df = this.displayField;
55790             this.store.data.each(function(r) {
55791                 // which colmsn to use... testing - cdoe / title..
55792                 var op = od.createElement('option');
55793                 op.setAttribute('value', r.data[vf]);
55794                 op.innerHTML = String.format('{0}', r.data[df]);
55795                 dom.appendChild(op);
55796             });
55797             if (typeof(this.defaultValue != 'undefined')) {
55798                 this.setValue(this.defaultValue);
55799             }
55800             
55801              
55802         }else{
55803             //this.onEmptyResults();
55804         }
55805         //this.el.focus();
55806     },
55807     // private
55808     onLoadException : function()
55809     {
55810         dom.innerHTML = '';
55811             
55812         Roo.log("Select on load exception");
55813         return;
55814     
55815         this.collapse();
55816         Roo.log(this.store.reader.jsonData);
55817         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
55818             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
55819         }
55820         
55821         
55822     },
55823     // private
55824     onTypeAhead : function(){
55825          
55826     },
55827
55828     // private
55829     onSelect : function(record, index){
55830         Roo.log('on select?');
55831         return;
55832         if(this.fireEvent('beforeselect', this, record, index) !== false){
55833             this.setFromData(index > -1 ? record.data : false);
55834             this.collapse();
55835             this.fireEvent('select', this, record, index);
55836         }
55837     },
55838
55839     /**
55840      * Returns the currently selected field value or empty string if no value is set.
55841      * @return {String} value The selected value
55842      */
55843     getValue : function(){
55844         var dom = this.el.dom;
55845         this.value = dom.options[dom.selectedIndex].value;
55846         return this.value;
55847         
55848     },
55849
55850     /**
55851      * Clears any text/value currently set in the field
55852      */
55853     clearValue : function(){
55854         this.value = '';
55855         this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
55856         
55857     },
55858
55859     /**
55860      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
55861      * will be displayed in the field.  If the value does not match the data value of an existing item,
55862      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
55863      * Otherwise the field will be blank (although the value will still be set).
55864      * @param {String} value The value to match
55865      */
55866     setValue : function(v){
55867         var d = this.el.dom;
55868         for (var i =0; i < d.options.length;i++) {
55869             if (v == d.options[i].value) {
55870                 d.selectedIndex = i;
55871                 this.value = v;
55872                 return;
55873             }
55874         }
55875         this.clearValue();
55876     },
55877     /**
55878      * @property {Object} the last set data for the element
55879      */
55880     
55881     lastData : false,
55882     /**
55883      * Sets the value of the field based on a object which is related to the record format for the store.
55884      * @param {Object} value the value to set as. or false on reset?
55885      */
55886     setFromData : function(o){
55887         Roo.log('setfrom data?');
55888          
55889         
55890         
55891     },
55892     // private
55893     reset : function(){
55894         this.clearValue();
55895     },
55896     // private
55897     findRecord : function(prop, value){
55898         
55899         return false;
55900     
55901         var record;
55902         if(this.store.getCount() > 0){
55903             this.store.each(function(r){
55904                 if(r.data[prop] == value){
55905                     record = r;
55906                     return false;
55907                 }
55908                 return true;
55909             });
55910         }
55911         return record;
55912     },
55913     
55914     getName: function()
55915     {
55916         // returns hidden if it's set..
55917         if (!this.rendered) {return ''};
55918         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
55919         
55920     },
55921      
55922
55923     
55924
55925     // private
55926     onEmptyResults : function(){
55927         Roo.log('empty results');
55928         //this.collapse();
55929     },
55930
55931     /**
55932      * Returns true if the dropdown list is expanded, else false.
55933      */
55934     isExpanded : function(){
55935         return false;
55936     },
55937
55938     /**
55939      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
55940      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
55941      * @param {String} value The data value of the item to select
55942      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
55943      * selected item if it is not currently in view (defaults to true)
55944      * @return {Boolean} True if the value matched an item in the list, else false
55945      */
55946     selectByValue : function(v, scrollIntoView){
55947         Roo.log('select By Value');
55948         return false;
55949     
55950         if(v !== undefined && v !== null){
55951             var r = this.findRecord(this.valueField || this.displayField, v);
55952             if(r){
55953                 this.select(this.store.indexOf(r), scrollIntoView);
55954                 return true;
55955             }
55956         }
55957         return false;
55958     },
55959
55960     /**
55961      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
55962      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
55963      * @param {Number} index The zero-based index of the list item to select
55964      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
55965      * selected item if it is not currently in view (defaults to true)
55966      */
55967     select : function(index, scrollIntoView){
55968         Roo.log('select ');
55969         return  ;
55970         
55971         this.selectedIndex = index;
55972         this.view.select(index);
55973         if(scrollIntoView !== false){
55974             var el = this.view.getNode(index);
55975             if(el){
55976                 this.innerList.scrollChildIntoView(el, false);
55977             }
55978         }
55979     },
55980
55981       
55982
55983     // private
55984     validateBlur : function(){
55985         
55986         return;
55987         
55988     },
55989
55990     // private
55991     initQuery : function(){
55992         this.doQuery(this.getRawValue());
55993     },
55994
55995     // private
55996     doForce : function(){
55997         if(this.el.dom.value.length > 0){
55998             this.el.dom.value =
55999                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
56000              
56001         }
56002     },
56003
56004     /**
56005      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
56006      * query allowing the query action to be canceled if needed.
56007      * @param {String} query The SQL query to execute
56008      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
56009      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
56010      * saved in the current store (defaults to false)
56011      */
56012     doQuery : function(q, forceAll){
56013         
56014         Roo.log('doQuery?');
56015         if(q === undefined || q === null){
56016             q = '';
56017         }
56018         var qe = {
56019             query: q,
56020             forceAll: forceAll,
56021             combo: this,
56022             cancel:false
56023         };
56024         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
56025             return false;
56026         }
56027         q = qe.query;
56028         forceAll = qe.forceAll;
56029         if(forceAll === true || (q.length >= this.minChars)){
56030             if(this.lastQuery != q || this.alwaysQuery){
56031                 this.lastQuery = q;
56032                 if(this.mode == 'local'){
56033                     this.selectedIndex = -1;
56034                     if(forceAll){
56035                         this.store.clearFilter();
56036                     }else{
56037                         this.store.filter(this.displayField, q);
56038                     }
56039                     this.onLoad();
56040                 }else{
56041                     this.store.baseParams[this.queryParam] = q;
56042                     this.store.load({
56043                         params: this.getParams(q)
56044                     });
56045                     this.expand();
56046                 }
56047             }else{
56048                 this.selectedIndex = -1;
56049                 this.onLoad();   
56050             }
56051         }
56052     },
56053
56054     // private
56055     getParams : function(q){
56056         var p = {};
56057         //p[this.queryParam] = q;
56058         if(this.pageSize){
56059             p.start = 0;
56060             p.limit = this.pageSize;
56061         }
56062         return p;
56063     },
56064
56065     /**
56066      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
56067      */
56068     collapse : function(){
56069         
56070     },
56071
56072     // private
56073     collapseIf : function(e){
56074         
56075     },
56076
56077     /**
56078      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
56079      */
56080     expand : function(){
56081         
56082     } ,
56083
56084     // private
56085      
56086
56087     /** 
56088     * @cfg {Boolean} grow 
56089     * @hide 
56090     */
56091     /** 
56092     * @cfg {Number} growMin 
56093     * @hide 
56094     */
56095     /** 
56096     * @cfg {Number} growMax 
56097     * @hide 
56098     */
56099     /**
56100      * @hide
56101      * @method autoSize
56102      */
56103     
56104     setWidth : function()
56105     {
56106         
56107     },
56108     getResizeEl : function(){
56109         return this.el;
56110     }
56111 });//<script type="text/javasscript">
56112  
56113
56114 /**
56115  * @class Roo.DDView
56116  * A DnD enabled version of Roo.View.
56117  * @param {Element/String} container The Element in which to create the View.
56118  * @param {String} tpl The template string used to create the markup for each element of the View
56119  * @param {Object} config The configuration properties. These include all the config options of
56120  * {@link Roo.View} plus some specific to this class.<br>
56121  * <p>
56122  * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
56123  * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
56124  * <p>
56125  * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
56126 .x-view-drag-insert-above {
56127         border-top:1px dotted #3366cc;
56128 }
56129 .x-view-drag-insert-below {
56130         border-bottom:1px dotted #3366cc;
56131 }
56132 </code></pre>
56133  * 
56134  */
56135  
56136 Roo.DDView = function(container, tpl, config) {
56137     Roo.DDView.superclass.constructor.apply(this, arguments);
56138     this.getEl().setStyle("outline", "0px none");
56139     this.getEl().unselectable();
56140     if (this.dragGroup) {
56141         this.setDraggable(this.dragGroup.split(","));
56142     }
56143     if (this.dropGroup) {
56144         this.setDroppable(this.dropGroup.split(","));
56145     }
56146     if (this.deletable) {
56147         this.setDeletable();
56148     }
56149     this.isDirtyFlag = false;
56150         this.addEvents({
56151                 "drop" : true
56152         });
56153 };
56154
56155 Roo.extend(Roo.DDView, Roo.View, {
56156 /**     @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
56157 /**     @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
56158 /**     @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
56159 /**     @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
56160
56161         isFormField: true,
56162
56163         reset: Roo.emptyFn,
56164         
56165         clearInvalid: Roo.form.Field.prototype.clearInvalid,
56166
56167         validate: function() {
56168                 return true;
56169         },
56170         
56171         destroy: function() {
56172                 this.purgeListeners();
56173                 this.getEl.removeAllListeners();
56174                 this.getEl().remove();
56175                 if (this.dragZone) {
56176                         if (this.dragZone.destroy) {
56177                                 this.dragZone.destroy();
56178                         }
56179                 }
56180                 if (this.dropZone) {
56181                         if (this.dropZone.destroy) {
56182                                 this.dropZone.destroy();
56183                         }
56184                 }
56185         },
56186
56187 /**     Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
56188         getName: function() {
56189                 return this.name;
56190         },
56191
56192 /**     Loads the View from a JSON string representing the Records to put into the Store. */
56193         setValue: function(v) {
56194                 if (!this.store) {
56195                         throw "DDView.setValue(). DDView must be constructed with a valid Store";
56196                 }
56197                 var data = {};
56198                 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
56199                 this.store.proxy = new Roo.data.MemoryProxy(data);
56200                 this.store.load();
56201         },
56202
56203 /**     @return {String} a parenthesised list of the ids of the Records in the View. */
56204         getValue: function() {
56205                 var result = '(';
56206                 this.store.each(function(rec) {
56207                         result += rec.id + ',';
56208                 });
56209                 return result.substr(0, result.length - 1) + ')';
56210         },
56211         
56212         getIds: function() {
56213                 var i = 0, result = new Array(this.store.getCount());
56214                 this.store.each(function(rec) {
56215                         result[i++] = rec.id;
56216                 });
56217                 return result;
56218         },
56219         
56220         isDirty: function() {
56221                 return this.isDirtyFlag;
56222         },
56223
56224 /**
56225  *      Part of the Roo.dd.DropZone interface. If no target node is found, the
56226  *      whole Element becomes the target, and this causes the drop gesture to append.
56227  */
56228     getTargetFromEvent : function(e) {
56229                 var target = e.getTarget();
56230                 while ((target !== null) && (target.parentNode != this.el.dom)) {
56231                 target = target.parentNode;
56232                 }
56233                 if (!target) {
56234                         target = this.el.dom.lastChild || this.el.dom;
56235                 }
56236                 return target;
56237     },
56238
56239 /**
56240  *      Create the drag data which consists of an object which has the property "ddel" as
56241  *      the drag proxy element. 
56242  */
56243     getDragData : function(e) {
56244         var target = this.findItemFromChild(e.getTarget());
56245                 if(target) {
56246                         this.handleSelection(e);
56247                         var selNodes = this.getSelectedNodes();
56248             var dragData = {
56249                 source: this,
56250                 copy: this.copy || (this.allowCopy && e.ctrlKey),
56251                 nodes: selNodes,
56252                 records: []
56253                         };
56254                         var selectedIndices = this.getSelectedIndexes();
56255                         for (var i = 0; i < selectedIndices.length; i++) {
56256                                 dragData.records.push(this.store.getAt(selectedIndices[i]));
56257                         }
56258                         if (selNodes.length == 1) {
56259                                 dragData.ddel = target.cloneNode(true); // the div element
56260                         } else {
56261                                 var div = document.createElement('div'); // create the multi element drag "ghost"
56262                                 div.className = 'multi-proxy';
56263                                 for (var i = 0, len = selNodes.length; i < len; i++) {
56264                                         div.appendChild(selNodes[i].cloneNode(true));
56265                                 }
56266                                 dragData.ddel = div;
56267                         }
56268             //console.log(dragData)
56269             //console.log(dragData.ddel.innerHTML)
56270                         return dragData;
56271                 }
56272         //console.log('nodragData')
56273                 return false;
56274     },
56275     
56276 /**     Specify to which ddGroup items in this DDView may be dragged. */
56277     setDraggable: function(ddGroup) {
56278         if (ddGroup instanceof Array) {
56279                 Roo.each(ddGroup, this.setDraggable, this);
56280                 return;
56281         }
56282         if (this.dragZone) {
56283                 this.dragZone.addToGroup(ddGroup);
56284         } else {
56285                         this.dragZone = new Roo.dd.DragZone(this.getEl(), {
56286                                 containerScroll: true,
56287                                 ddGroup: ddGroup 
56288
56289                         });
56290 //                      Draggability implies selection. DragZone's mousedown selects the element.
56291                         if (!this.multiSelect) { this.singleSelect = true; }
56292
56293 //                      Wire the DragZone's handlers up to methods in *this*
56294                         this.dragZone.getDragData = this.getDragData.createDelegate(this);
56295                 }
56296     },
56297
56298 /**     Specify from which ddGroup this DDView accepts drops. */
56299     setDroppable: function(ddGroup) {
56300         if (ddGroup instanceof Array) {
56301                 Roo.each(ddGroup, this.setDroppable, this);
56302                 return;
56303         }
56304         if (this.dropZone) {
56305                 this.dropZone.addToGroup(ddGroup);
56306         } else {
56307                         this.dropZone = new Roo.dd.DropZone(this.getEl(), {
56308                                 containerScroll: true,
56309                                 ddGroup: ddGroup
56310                         });
56311
56312 //                      Wire the DropZone's handlers up to methods in *this*
56313                         this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
56314                         this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
56315                         this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
56316                         this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
56317                         this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
56318                 }
56319     },
56320
56321 /**     Decide whether to drop above or below a View node. */
56322     getDropPoint : function(e, n, dd){
56323         if (n == this.el.dom) { return "above"; }
56324                 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
56325                 var c = t + (b - t) / 2;
56326                 var y = Roo.lib.Event.getPageY(e);
56327                 if(y <= c) {
56328                         return "above";
56329                 }else{
56330                         return "below";
56331                 }
56332     },
56333
56334     onNodeEnter : function(n, dd, e, data){
56335                 return false;
56336     },
56337     
56338     onNodeOver : function(n, dd, e, data){
56339                 var pt = this.getDropPoint(e, n, dd);
56340                 // set the insert point style on the target node
56341                 var dragElClass = this.dropNotAllowed;
56342                 if (pt) {
56343                         var targetElClass;
56344                         if (pt == "above"){
56345                                 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
56346                                 targetElClass = "x-view-drag-insert-above";
56347                         } else {
56348                                 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
56349                                 targetElClass = "x-view-drag-insert-below";
56350                         }
56351                         if (this.lastInsertClass != targetElClass){
56352                                 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
56353                                 this.lastInsertClass = targetElClass;
56354                         }
56355                 }
56356                 return dragElClass;
56357         },
56358
56359     onNodeOut : function(n, dd, e, data){
56360                 this.removeDropIndicators(n);
56361     },
56362
56363     onNodeDrop : function(n, dd, e, data){
56364         if (this.fireEvent("drop", this, n, dd, e, data) === false) {
56365                 return false;
56366         }
56367         var pt = this.getDropPoint(e, n, dd);
56368                 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
56369                 if (pt == "below") { insertAt++; }
56370                 for (var i = 0; i < data.records.length; i++) {
56371                         var r = data.records[i];
56372                         var dup = this.store.getById(r.id);
56373                         if (dup && (dd != this.dragZone)) {
56374                                 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
56375                         } else {
56376                                 if (data.copy) {
56377                                         this.store.insert(insertAt++, r.copy());
56378                                 } else {
56379                                         data.source.isDirtyFlag = true;
56380                                         r.store.remove(r);
56381                                         this.store.insert(insertAt++, r);
56382                                 }
56383                                 this.isDirtyFlag = true;
56384                         }
56385                 }
56386                 this.dragZone.cachedTarget = null;
56387                 return true;
56388     },
56389
56390     removeDropIndicators : function(n){
56391                 if(n){
56392                         Roo.fly(n).removeClass([
56393                                 "x-view-drag-insert-above",
56394                                 "x-view-drag-insert-below"]);
56395                         this.lastInsertClass = "_noclass";
56396                 }
56397     },
56398
56399 /**
56400  *      Utility method. Add a delete option to the DDView's context menu.
56401  *      @param {String} imageUrl The URL of the "delete" icon image.
56402  */
56403         setDeletable: function(imageUrl) {
56404                 if (!this.singleSelect && !this.multiSelect) {
56405                         this.singleSelect = true;
56406                 }
56407                 var c = this.getContextMenu();
56408                 this.contextMenu.on("itemclick", function(item) {
56409                         switch (item.id) {
56410                                 case "delete":
56411                                         this.remove(this.getSelectedIndexes());
56412                                         break;
56413                         }
56414                 }, this);
56415                 this.contextMenu.add({
56416                         icon: imageUrl,
56417                         id: "delete",
56418                         text: 'Delete'
56419                 });
56420         },
56421         
56422 /**     Return the context menu for this DDView. */
56423         getContextMenu: function() {
56424                 if (!this.contextMenu) {
56425 //                      Create the View's context menu
56426                         this.contextMenu = new Roo.menu.Menu({
56427                                 id: this.id + "-contextmenu"
56428                         });
56429                         this.el.on("contextmenu", this.showContextMenu, this);
56430                 }
56431                 return this.contextMenu;
56432         },
56433         
56434         disableContextMenu: function() {
56435                 if (this.contextMenu) {
56436                         this.el.un("contextmenu", this.showContextMenu, this);
56437                 }
56438         },
56439
56440         showContextMenu: function(e, item) {
56441         item = this.findItemFromChild(e.getTarget());
56442                 if (item) {
56443                         e.stopEvent();
56444                         this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
56445                         this.contextMenu.showAt(e.getXY());
56446             }
56447     },
56448
56449 /**
56450  *      Remove {@link Roo.data.Record}s at the specified indices.
56451  *      @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
56452  */
56453     remove: function(selectedIndices) {
56454                 selectedIndices = [].concat(selectedIndices);
56455                 for (var i = 0; i < selectedIndices.length; i++) {
56456                         var rec = this.store.getAt(selectedIndices[i]);
56457                         this.store.remove(rec);
56458                 }
56459     },
56460
56461 /**
56462  *      Double click fires the event, but also, if this is draggable, and there is only one other
56463  *      related DropZone, it transfers the selected node.
56464  */
56465     onDblClick : function(e){
56466         var item = this.findItemFromChild(e.getTarget());
56467         if(item){
56468             if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
56469                 return false;
56470             }
56471             if (this.dragGroup) {
56472                     var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
56473                     while (targets.indexOf(this.dropZone) > -1) {
56474                             targets.remove(this.dropZone);
56475                                 }
56476                     if (targets.length == 1) {
56477                                         this.dragZone.cachedTarget = null;
56478                         var el = Roo.get(targets[0].getEl());
56479                         var box = el.getBox(true);
56480                         targets[0].onNodeDrop(el.dom, {
56481                                 target: el.dom,
56482                                 xy: [box.x, box.y + box.height - 1]
56483                         }, null, this.getDragData(e));
56484                     }
56485                 }
56486         }
56487     },
56488     
56489     handleSelection: function(e) {
56490                 this.dragZone.cachedTarget = null;
56491         var item = this.findItemFromChild(e.getTarget());
56492         if (!item) {
56493                 this.clearSelections(true);
56494                 return;
56495         }
56496                 if (item && (this.multiSelect || this.singleSelect)){
56497                         if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
56498                                 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
56499                         }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
56500                                 this.unselect(item);
56501                         } else {
56502                                 this.select(item, this.multiSelect && e.ctrlKey);
56503                                 this.lastSelection = item;
56504                         }
56505                 }
56506     },
56507
56508     onItemClick : function(item, index, e){
56509                 if(this.fireEvent("beforeclick", this, index, item, e) === false){
56510                         return false;
56511                 }
56512                 return true;
56513     },
56514
56515     unselect : function(nodeInfo, suppressEvent){
56516                 var node = this.getNode(nodeInfo);
56517                 if(node && this.isSelected(node)){
56518                         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
56519                                 Roo.fly(node).removeClass(this.selectedClass);
56520                                 this.selections.remove(node);
56521                                 if(!suppressEvent){
56522                                         this.fireEvent("selectionchange", this, this.selections);
56523                                 }
56524                         }
56525                 }
56526     }
56527 });
56528 /*
56529  * Based on:
56530  * Ext JS Library 1.1.1
56531  * Copyright(c) 2006-2007, Ext JS, LLC.
56532  *
56533  * Originally Released Under LGPL - original licence link has changed is not relivant.
56534  *
56535  * Fork - LGPL
56536  * <script type="text/javascript">
56537  */
56538  
56539 /**
56540  * @class Roo.LayoutManager
56541  * @extends Roo.util.Observable
56542  * Base class for layout managers.
56543  */
56544 Roo.LayoutManager = function(container, config){
56545     Roo.LayoutManager.superclass.constructor.call(this);
56546     this.el = Roo.get(container);
56547     // ie scrollbar fix
56548     if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
56549         document.body.scroll = "no";
56550     }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
56551         this.el.position('relative');
56552     }
56553     this.id = this.el.id;
56554     this.el.addClass("x-layout-container");
56555     /** false to disable window resize monitoring @type Boolean */
56556     this.monitorWindowResize = true;
56557     this.regions = {};
56558     this.addEvents({
56559         /**
56560          * @event layout
56561          * Fires when a layout is performed. 
56562          * @param {Roo.LayoutManager} this
56563          */
56564         "layout" : true,
56565         /**
56566          * @event regionresized
56567          * Fires when the user resizes a region. 
56568          * @param {Roo.LayoutRegion} region The resized region
56569          * @param {Number} newSize The new size (width for east/west, height for north/south)
56570          */
56571         "regionresized" : true,
56572         /**
56573          * @event regioncollapsed
56574          * Fires when a region is collapsed. 
56575          * @param {Roo.LayoutRegion} region The collapsed region
56576          */
56577         "regioncollapsed" : true,
56578         /**
56579          * @event regionexpanded
56580          * Fires when a region is expanded.  
56581          * @param {Roo.LayoutRegion} region The expanded region
56582          */
56583         "regionexpanded" : true
56584     });
56585     this.updating = false;
56586     Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
56587 };
56588
56589 Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
56590     /**
56591      * Returns true if this layout is currently being updated
56592      * @return {Boolean}
56593      */
56594     isUpdating : function(){
56595         return this.updating; 
56596     },
56597     
56598     /**
56599      * Suspend the LayoutManager from doing auto-layouts while
56600      * making multiple add or remove calls
56601      */
56602     beginUpdate : function(){
56603         this.updating = true;    
56604     },
56605     
56606     /**
56607      * Restore auto-layouts and optionally disable the manager from performing a layout
56608      * @param {Boolean} noLayout true to disable a layout update 
56609      */
56610     endUpdate : function(noLayout){
56611         this.updating = false;
56612         if(!noLayout){
56613             this.layout();
56614         }    
56615     },
56616     
56617     layout: function(){
56618         
56619     },
56620     
56621     onRegionResized : function(region, newSize){
56622         this.fireEvent("regionresized", region, newSize);
56623         this.layout();
56624     },
56625     
56626     onRegionCollapsed : function(region){
56627         this.fireEvent("regioncollapsed", region);
56628     },
56629     
56630     onRegionExpanded : function(region){
56631         this.fireEvent("regionexpanded", region);
56632     },
56633         
56634     /**
56635      * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
56636      * performs box-model adjustments.
56637      * @return {Object} The size as an object {width: (the width), height: (the height)}
56638      */
56639     getViewSize : function(){
56640         var size;
56641         if(this.el.dom != document.body){
56642             size = this.el.getSize();
56643         }else{
56644             size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
56645         }
56646         size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
56647         size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
56648         return size;
56649     },
56650     
56651     /**
56652      * Returns the Element this layout is bound to.
56653      * @return {Roo.Element}
56654      */
56655     getEl : function(){
56656         return this.el;
56657     },
56658     
56659     /**
56660      * Returns the specified region.
56661      * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
56662      * @return {Roo.LayoutRegion}
56663      */
56664     getRegion : function(target){
56665         return this.regions[target.toLowerCase()];
56666     },
56667     
56668     onWindowResize : function(){
56669         if(this.monitorWindowResize){
56670             this.layout();
56671         }
56672     }
56673 });/*
56674  * Based on:
56675  * Ext JS Library 1.1.1
56676  * Copyright(c) 2006-2007, Ext JS, LLC.
56677  *
56678  * Originally Released Under LGPL - original licence link has changed is not relivant.
56679  *
56680  * Fork - LGPL
56681  * <script type="text/javascript">
56682  */
56683 /**
56684  * @class Roo.BorderLayout
56685  * @extends Roo.LayoutManager
56686  * @children Roo.ContentPanel
56687  * This class represents a common layout manager used in desktop applications. For screenshots and more details,
56688  * please see: <br><br>
56689  * <a href="http://www.jackslocum.com/yui/2006/10/19/cross-browser-web-20-layouts-with-yahoo-ui/">Cross Browser Layouts - Part 1</a><br>
56690  * <a href="http://www.jackslocum.com/yui/2006/10/28/cross-browser-web-20-layouts-part-2-ajax-feed-viewer-20/">Cross Browser Layouts - Part 2</a><br><br>
56691  * Example:
56692  <pre><code>
56693  var layout = new Roo.BorderLayout(document.body, {
56694     north: {
56695         initialSize: 25,
56696         titlebar: false
56697     },
56698     west: {
56699         split:true,
56700         initialSize: 200,
56701         minSize: 175,
56702         maxSize: 400,
56703         titlebar: true,
56704         collapsible: true
56705     },
56706     east: {
56707         split:true,
56708         initialSize: 202,
56709         minSize: 175,
56710         maxSize: 400,
56711         titlebar: true,
56712         collapsible: true
56713     },
56714     south: {
56715         split:true,
56716         initialSize: 100,
56717         minSize: 100,
56718         maxSize: 200,
56719         titlebar: true,
56720         collapsible: true
56721     },
56722     center: {
56723         titlebar: true,
56724         autoScroll:true,
56725         resizeTabs: true,
56726         minTabWidth: 50,
56727         preferredTabWidth: 150
56728     }
56729 });
56730
56731 // shorthand
56732 var CP = Roo.ContentPanel;
56733
56734 layout.beginUpdate();
56735 layout.add("north", new CP("north", "North"));
56736 layout.add("south", new CP("south", {title: "South", closable: true}));
56737 layout.add("west", new CP("west", {title: "West"}));
56738 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
56739 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
56740 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
56741 layout.getRegion("center").showPanel("center1");
56742 layout.endUpdate();
56743 </code></pre>
56744
56745 <b>The container the layout is rendered into can be either the body element or any other element.
56746 If it is not the body element, the container needs to either be an absolute positioned element,
56747 or you will need to add "position:relative" to the css of the container.  You will also need to specify
56748 the container size if it is not the body element.</b>
56749
56750 * @constructor
56751 * Create a new BorderLayout
56752 * @param {String/HTMLElement/Element} container The container this layout is bound to
56753 * @param {Object} config Configuration options
56754  */
56755 Roo.BorderLayout = function(container, config){
56756     config = config || {};
56757     Roo.BorderLayout.superclass.constructor.call(this, container, config);
56758     this.factory = config.factory || Roo.BorderLayout.RegionFactory;
56759     for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
56760         var target = this.factory.validRegions[i];
56761         if(config[target]){
56762             this.addRegion(target, config[target]);
56763         }
56764     }
56765 };
56766
56767 Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
56768         
56769         /**
56770          * @cfg {Roo.LayoutRegion} east
56771          */
56772         /**
56773          * @cfg {Roo.LayoutRegion} west
56774          */
56775         /**
56776          * @cfg {Roo.LayoutRegion} north
56777          */
56778         /**
56779          * @cfg {Roo.LayoutRegion} south
56780          */
56781         /**
56782          * @cfg {Roo.LayoutRegion} center
56783          */
56784     /**
56785      * Creates and adds a new region if it doesn't already exist.
56786      * @param {String} target The target region key (north, south, east, west or center).
56787      * @param {Object} config The regions config object
56788      * @return {BorderLayoutRegion} The new region
56789      */
56790     addRegion : function(target, config){
56791         if(!this.regions[target]){
56792             var r = this.factory.create(target, this, config);
56793             this.bindRegion(target, r);
56794         }
56795         return this.regions[target];
56796     },
56797
56798     // private (kinda)
56799     bindRegion : function(name, r){
56800         this.regions[name] = r;
56801         r.on("visibilitychange", this.layout, this);
56802         r.on("paneladded", this.layout, this);
56803         r.on("panelremoved", this.layout, this);
56804         r.on("invalidated", this.layout, this);
56805         r.on("resized", this.onRegionResized, this);
56806         r.on("collapsed", this.onRegionCollapsed, this);
56807         r.on("expanded", this.onRegionExpanded, this);
56808     },
56809
56810     /**
56811      * Performs a layout update.
56812      */
56813     layout : function(){
56814         if(this.updating) {
56815             return;
56816         }
56817         var size = this.getViewSize();
56818         var w = size.width;
56819         var h = size.height;
56820         var centerW = w;
56821         var centerH = h;
56822         var centerY = 0;
56823         var centerX = 0;
56824         //var x = 0, y = 0;
56825
56826         var rs = this.regions;
56827         var north = rs["north"];
56828         var south = rs["south"]; 
56829         var west = rs["west"];
56830         var east = rs["east"];
56831         var center = rs["center"];
56832         //if(this.hideOnLayout){ // not supported anymore
56833             //c.el.setStyle("display", "none");
56834         //}
56835         if(north && north.isVisible()){
56836             var b = north.getBox();
56837             var m = north.getMargins();
56838             b.width = w - (m.left+m.right);
56839             b.x = m.left;
56840             b.y = m.top;
56841             centerY = b.height + b.y + m.bottom;
56842             centerH -= centerY;
56843             north.updateBox(this.safeBox(b));
56844         }
56845         if(south && south.isVisible()){
56846             var b = south.getBox();
56847             var m = south.getMargins();
56848             b.width = w - (m.left+m.right);
56849             b.x = m.left;
56850             var totalHeight = (b.height + m.top + m.bottom);
56851             b.y = h - totalHeight + m.top;
56852             centerH -= totalHeight;
56853             south.updateBox(this.safeBox(b));
56854         }
56855         if(west && west.isVisible()){
56856             var b = west.getBox();
56857             var m = west.getMargins();
56858             b.height = centerH - (m.top+m.bottom);
56859             b.x = m.left;
56860             b.y = centerY + m.top;
56861             var totalWidth = (b.width + m.left + m.right);
56862             centerX += totalWidth;
56863             centerW -= totalWidth;
56864             west.updateBox(this.safeBox(b));
56865         }
56866         if(east && east.isVisible()){
56867             var b = east.getBox();
56868             var m = east.getMargins();
56869             b.height = centerH - (m.top+m.bottom);
56870             var totalWidth = (b.width + m.left + m.right);
56871             b.x = w - totalWidth + m.left;
56872             b.y = centerY + m.top;
56873             centerW -= totalWidth;
56874             east.updateBox(this.safeBox(b));
56875         }
56876         if(center){
56877             var m = center.getMargins();
56878             var centerBox = {
56879                 x: centerX + m.left,
56880                 y: centerY + m.top,
56881                 width: centerW - (m.left+m.right),
56882                 height: centerH - (m.top+m.bottom)
56883             };
56884             //if(this.hideOnLayout){
56885                 //center.el.setStyle("display", "block");
56886             //}
56887             center.updateBox(this.safeBox(centerBox));
56888         }
56889         this.el.repaint();
56890         this.fireEvent("layout", this);
56891     },
56892
56893     // private
56894     safeBox : function(box){
56895         box.width = Math.max(0, box.width);
56896         box.height = Math.max(0, box.height);
56897         return box;
56898     },
56899
56900     /**
56901      * Adds a ContentPanel (or subclass) to this layout.
56902      * @param {String} target The target region key (north, south, east, west or center).
56903      * @param {Roo.ContentPanel} panel The panel to add
56904      * @return {Roo.ContentPanel} The added panel
56905      */
56906     add : function(target, panel){
56907          
56908         target = target.toLowerCase();
56909         return this.regions[target].add(panel);
56910     },
56911
56912     /**
56913      * Remove a ContentPanel (or subclass) to this layout.
56914      * @param {String} target The target region key (north, south, east, west or center).
56915      * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
56916      * @return {Roo.ContentPanel} The removed panel
56917      */
56918     remove : function(target, panel){
56919         target = target.toLowerCase();
56920         return this.regions[target].remove(panel);
56921     },
56922
56923     /**
56924      * Searches all regions for a panel with the specified id
56925      * @param {String} panelId
56926      * @return {Roo.ContentPanel} The panel or null if it wasn't found
56927      */
56928     findPanel : function(panelId){
56929         var rs = this.regions;
56930         for(var target in rs){
56931             if(typeof rs[target] != "function"){
56932                 var p = rs[target].getPanel(panelId);
56933                 if(p){
56934                     return p;
56935                 }
56936             }
56937         }
56938         return null;
56939     },
56940
56941     /**
56942      * Searches all regions for a panel with the specified id and activates (shows) it.
56943      * @param {String/ContentPanel} panelId The panels id or the panel itself
56944      * @return {Roo.ContentPanel} The shown panel or null
56945      */
56946     showPanel : function(panelId) {
56947       var rs = this.regions;
56948       for(var target in rs){
56949          var r = rs[target];
56950          if(typeof r != "function"){
56951             if(r.hasPanel(panelId)){
56952                return r.showPanel(panelId);
56953             }
56954          }
56955       }
56956       return null;
56957    },
56958
56959    /**
56960      * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
56961      * @param {Roo.state.Provider} provider (optional) An alternate state provider
56962      */
56963     restoreState : function(provider){
56964         if(!provider){
56965             provider = Roo.state.Manager;
56966         }
56967         var sm = new Roo.LayoutStateManager();
56968         sm.init(this, provider);
56969     },
56970
56971     /**
56972      * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object.  This config
56973      * object should contain properties for each region to add ContentPanels to, and each property's value should be
56974      * a valid ContentPanel config object.  Example:
56975      * <pre><code>
56976 // Create the main layout
56977 var layout = new Roo.BorderLayout('main-ct', {
56978     west: {
56979         split:true,
56980         minSize: 175,
56981         titlebar: true
56982     },
56983     center: {
56984         title:'Components'
56985     }
56986 }, 'main-ct');
56987
56988 // Create and add multiple ContentPanels at once via configs
56989 layout.batchAdd({
56990    west: {
56991        id: 'source-files',
56992        autoCreate:true,
56993        title:'Ext Source Files',
56994        autoScroll:true,
56995        fitToFrame:true
56996    },
56997    center : {
56998        el: cview,
56999        autoScroll:true,
57000        fitToFrame:true,
57001        toolbar: tb,
57002        resizeEl:'cbody'
57003    }
57004 });
57005 </code></pre>
57006      * @param {Object} regions An object containing ContentPanel configs by region name
57007      */
57008     batchAdd : function(regions){
57009         this.beginUpdate();
57010         for(var rname in regions){
57011             var lr = this.regions[rname];
57012             if(lr){
57013                 this.addTypedPanels(lr, regions[rname]);
57014             }
57015         }
57016         this.endUpdate();
57017     },
57018
57019     // private
57020     addTypedPanels : function(lr, ps){
57021         if(typeof ps == 'string'){
57022             lr.add(new Roo.ContentPanel(ps));
57023         }
57024         else if(ps instanceof Array){
57025             for(var i =0, len = ps.length; i < len; i++){
57026                 this.addTypedPanels(lr, ps[i]);
57027             }
57028         }
57029         else if(!ps.events){ // raw config?
57030             var el = ps.el;
57031             delete ps.el; // prevent conflict
57032             lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
57033         }
57034         else {  // panel object assumed!
57035             lr.add(ps);
57036         }
57037     },
57038     /**
57039      * Adds a xtype elements to the layout.
57040      * <pre><code>
57041
57042 layout.addxtype({
57043        xtype : 'ContentPanel',
57044        region: 'west',
57045        items: [ .... ]
57046    }
57047 );
57048
57049 layout.addxtype({
57050         xtype : 'NestedLayoutPanel',
57051         region: 'west',
57052         layout: {
57053            center: { },
57054            west: { }   
57055         },
57056         items : [ ... list of content panels or nested layout panels.. ]
57057    }
57058 );
57059 </code></pre>
57060      * @param {Object} cfg Xtype definition of item to add.
57061      */
57062     addxtype : function(cfg)
57063     {
57064         // basically accepts a pannel...
57065         // can accept a layout region..!?!?
57066         //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
57067         
57068         if (!cfg.xtype.match(/Panel$/)) {
57069             return false;
57070         }
57071         var ret = false;
57072         
57073         if (typeof(cfg.region) == 'undefined') {
57074             Roo.log("Failed to add Panel, region was not set");
57075             Roo.log(cfg);
57076             return false;
57077         }
57078         var region = cfg.region;
57079         delete cfg.region;
57080         
57081           
57082         var xitems = [];
57083         if (cfg.items) {
57084             xitems = cfg.items;
57085             delete cfg.items;
57086         }
57087         var nb = false;
57088         
57089         switch(cfg.xtype) 
57090         {
57091             case 'ContentPanel':  // ContentPanel (el, cfg)
57092             case 'ScrollPanel':  // ContentPanel (el, cfg)
57093             case 'ViewPanel': 
57094                 if(cfg.autoCreate) {
57095                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
57096                 } else {
57097                     var el = this.el.createChild();
57098                     ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
57099                 }
57100                 
57101                 this.add(region, ret);
57102                 break;
57103             
57104             
57105             case 'TreePanel': // our new panel!
57106                 cfg.el = this.el.createChild();
57107                 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
57108                 this.add(region, ret);
57109                 break;
57110             
57111             case 'NestedLayoutPanel': 
57112                 // create a new Layout (which is  a Border Layout...
57113                 var el = this.el.createChild();
57114                 var clayout = cfg.layout;
57115                 delete cfg.layout;
57116                 clayout.items   = clayout.items  || [];
57117                 // replace this exitems with the clayout ones..
57118                 xitems = clayout.items;
57119                  
57120                 
57121                 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
57122                     cfg.background = false;
57123                 }
57124                 var layout = new Roo.BorderLayout(el, clayout);
57125                 
57126                 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
57127                 //console.log('adding nested layout panel '  + cfg.toSource());
57128                 this.add(region, ret);
57129                 nb = {}; /// find first...
57130                 break;
57131                 
57132             case 'GridPanel': 
57133             
57134                 // needs grid and region
57135                 
57136                 //var el = this.getRegion(region).el.createChild();
57137                 var el = this.el.createChild();
57138                 // create the grid first...
57139                 
57140                 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
57141                 delete cfg.grid;
57142                 if (region == 'center' && this.active ) {
57143                     cfg.background = false;
57144                 }
57145                 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
57146                 
57147                 this.add(region, ret);
57148                 if (cfg.background) {
57149                     ret.on('activate', function(gp) {
57150                         if (!gp.grid.rendered) {
57151                             gp.grid.render();
57152                         }
57153                     });
57154                 } else {
57155                     grid.render();
57156                 }
57157                 break;
57158            
57159            
57160            
57161                 
57162                 
57163                 
57164             default:
57165                 if (typeof(Roo[cfg.xtype]) != 'undefined') {
57166                     
57167                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
57168                     this.add(region, ret);
57169                 } else {
57170                 
57171                     alert("Can not add '" + cfg.xtype + "' to BorderLayout");
57172                     return null;
57173                 }
57174                 
57175              // GridPanel (grid, cfg)
57176             
57177         }
57178         this.beginUpdate();
57179         // add children..
57180         var region = '';
57181         var abn = {};
57182         Roo.each(xitems, function(i)  {
57183             region = nb && i.region ? i.region : false;
57184             
57185             var add = ret.addxtype(i);
57186            
57187             if (region) {
57188                 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
57189                 if (!i.background) {
57190                     abn[region] = nb[region] ;
57191                 }
57192             }
57193             
57194         });
57195         this.endUpdate();
57196
57197         // make the last non-background panel active..
57198         //if (nb) { Roo.log(abn); }
57199         if (nb) {
57200             
57201             for(var r in abn) {
57202                 region = this.getRegion(r);
57203                 if (region) {
57204                     // tried using nb[r], but it does not work..
57205                      
57206                     region.showPanel(abn[r]);
57207                    
57208                 }
57209             }
57210         }
57211         return ret;
57212         
57213     }
57214 });
57215
57216 /**
57217  * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
57218  * the beginUpdate and endUpdate calls internally.  The key to this method is the <b>panels</b> property that can be
57219  * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
57220  * during creation.  The following code is equivalent to the constructor-based example at the beginning of this class:
57221  * <pre><code>
57222 // shorthand
57223 var CP = Roo.ContentPanel;
57224
57225 var layout = Roo.BorderLayout.create({
57226     north: {
57227         initialSize: 25,
57228         titlebar: false,
57229         panels: [new CP("north", "North")]
57230     },
57231     west: {
57232         split:true,
57233         initialSize: 200,
57234         minSize: 175,
57235         maxSize: 400,
57236         titlebar: true,
57237         collapsible: true,
57238         panels: [new CP("west", {title: "West"})]
57239     },
57240     east: {
57241         split:true,
57242         initialSize: 202,
57243         minSize: 175,
57244         maxSize: 400,
57245         titlebar: true,
57246         collapsible: true,
57247         panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
57248     },
57249     south: {
57250         split:true,
57251         initialSize: 100,
57252         minSize: 100,
57253         maxSize: 200,
57254         titlebar: true,
57255         collapsible: true,
57256         panels: [new CP("south", {title: "South", closable: true})]
57257     },
57258     center: {
57259         titlebar: true,
57260         autoScroll:true,
57261         resizeTabs: true,
57262         minTabWidth: 50,
57263         preferredTabWidth: 150,
57264         panels: [
57265             new CP("center1", {title: "Close Me", closable: true}),
57266             new CP("center2", {title: "Center Panel", closable: false})
57267         ]
57268     }
57269 }, document.body);
57270
57271 layout.getRegion("center").showPanel("center1");
57272 </code></pre>
57273  * @param config
57274  * @param targetEl
57275  */
57276 Roo.BorderLayout.create = function(config, targetEl){
57277     var layout = new Roo.BorderLayout(targetEl || document.body, config);
57278     layout.beginUpdate();
57279     var regions = Roo.BorderLayout.RegionFactory.validRegions;
57280     for(var j = 0, jlen = regions.length; j < jlen; j++){
57281         var lr = regions[j];
57282         if(layout.regions[lr] && config[lr].panels){
57283             var r = layout.regions[lr];
57284             var ps = config[lr].panels;
57285             layout.addTypedPanels(r, ps);
57286         }
57287     }
57288     layout.endUpdate();
57289     return layout;
57290 };
57291
57292 // private
57293 Roo.BorderLayout.RegionFactory = {
57294     // private
57295     validRegions : ["north","south","east","west","center"],
57296
57297     // private
57298     create : function(target, mgr, config){
57299         target = target.toLowerCase();
57300         if(config.lightweight || config.basic){
57301             return new Roo.BasicLayoutRegion(mgr, config, target);
57302         }
57303         switch(target){
57304             case "north":
57305                 return new Roo.NorthLayoutRegion(mgr, config);
57306             case "south":
57307                 return new Roo.SouthLayoutRegion(mgr, config);
57308             case "east":
57309                 return new Roo.EastLayoutRegion(mgr, config);
57310             case "west":
57311                 return new Roo.WestLayoutRegion(mgr, config);
57312             case "center":
57313                 return new Roo.CenterLayoutRegion(mgr, config);
57314         }
57315         throw 'Layout region "'+target+'" not supported.';
57316     }
57317 };/*
57318  * Based on:
57319  * Ext JS Library 1.1.1
57320  * Copyright(c) 2006-2007, Ext JS, LLC.
57321  *
57322  * Originally Released Under LGPL - original licence link has changed is not relivant.
57323  *
57324  * Fork - LGPL
57325  * <script type="text/javascript">
57326  */
57327  
57328 /**
57329  * @class Roo.BasicLayoutRegion
57330  * @extends Roo.util.Observable
57331  * This class represents a lightweight region in a layout manager. This region does not move dom nodes
57332  * and does not have a titlebar, tabs or any other features. All it does is size and position 
57333  * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
57334  */
57335 Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
57336     this.mgr = mgr;
57337     this.position  = pos;
57338     this.events = {
57339         /**
57340          * @scope Roo.BasicLayoutRegion
57341          */
57342         
57343         /**
57344          * @event beforeremove
57345          * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
57346          * @param {Roo.LayoutRegion} this
57347          * @param {Roo.ContentPanel} panel The panel
57348          * @param {Object} e The cancel event object
57349          */
57350         "beforeremove" : true,
57351         /**
57352          * @event invalidated
57353          * Fires when the layout for this region is changed.
57354          * @param {Roo.LayoutRegion} this
57355          */
57356         "invalidated" : true,
57357         /**
57358          * @event visibilitychange
57359          * Fires when this region is shown or hidden 
57360          * @param {Roo.LayoutRegion} this
57361          * @param {Boolean} visibility true or false
57362          */
57363         "visibilitychange" : true,
57364         /**
57365          * @event paneladded
57366          * Fires when a panel is added. 
57367          * @param {Roo.LayoutRegion} this
57368          * @param {Roo.ContentPanel} panel The panel
57369          */
57370         "paneladded" : true,
57371         /**
57372          * @event panelremoved
57373          * Fires when a panel is removed. 
57374          * @param {Roo.LayoutRegion} this
57375          * @param {Roo.ContentPanel} panel The panel
57376          */
57377         "panelremoved" : true,
57378         /**
57379          * @event beforecollapse
57380          * Fires when this region before collapse.
57381          * @param {Roo.LayoutRegion} this
57382          */
57383         "beforecollapse" : true,
57384         /**
57385          * @event collapsed
57386          * Fires when this region is collapsed.
57387          * @param {Roo.LayoutRegion} this
57388          */
57389         "collapsed" : true,
57390         /**
57391          * @event expanded
57392          * Fires when this region is expanded.
57393          * @param {Roo.LayoutRegion} this
57394          */
57395         "expanded" : true,
57396         /**
57397          * @event slideshow
57398          * Fires when this region is slid into view.
57399          * @param {Roo.LayoutRegion} this
57400          */
57401         "slideshow" : true,
57402         /**
57403          * @event slidehide
57404          * Fires when this region slides out of view. 
57405          * @param {Roo.LayoutRegion} this
57406          */
57407         "slidehide" : true,
57408         /**
57409          * @event panelactivated
57410          * Fires when a panel is activated. 
57411          * @param {Roo.LayoutRegion} this
57412          * @param {Roo.ContentPanel} panel The activated panel
57413          */
57414         "panelactivated" : true,
57415         /**
57416          * @event resized
57417          * Fires when the user resizes this region. 
57418          * @param {Roo.LayoutRegion} this
57419          * @param {Number} newSize The new size (width for east/west, height for north/south)
57420          */
57421         "resized" : true
57422     };
57423     /** A collection of panels in this region. @type Roo.util.MixedCollection */
57424     this.panels = new Roo.util.MixedCollection();
57425     this.panels.getKey = this.getPanelId.createDelegate(this);
57426     this.box = null;
57427     this.activePanel = null;
57428     // ensure listeners are added...
57429     
57430     if (config.listeners || config.events) {
57431         Roo.BasicLayoutRegion.superclass.constructor.call(this, {
57432             listeners : config.listeners || {},
57433             events : config.events || {}
57434         });
57435     }
57436     
57437     if(skipConfig !== true){
57438         this.applyConfig(config);
57439     }
57440 };
57441
57442 Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
57443     getPanelId : function(p){
57444         return p.getId();
57445     },
57446     
57447     applyConfig : function(config){
57448         this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
57449         this.config = config;
57450         
57451     },
57452     
57453     /**
57454      * Resizes the region to the specified size. For vertical regions (west, east) this adjusts 
57455      * the width, for horizontal (north, south) the height.
57456      * @param {Number} newSize The new width or height
57457      */
57458     resizeTo : function(newSize){
57459         var el = this.el ? this.el :
57460                  (this.activePanel ? this.activePanel.getEl() : null);
57461         if(el){
57462             switch(this.position){
57463                 case "east":
57464                 case "west":
57465                     el.setWidth(newSize);
57466                     this.fireEvent("resized", this, newSize);
57467                 break;
57468                 case "north":
57469                 case "south":
57470                     el.setHeight(newSize);
57471                     this.fireEvent("resized", this, newSize);
57472                 break;                
57473             }
57474         }
57475     },
57476     
57477     getBox : function(){
57478         return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
57479     },
57480     
57481     getMargins : function(){
57482         return this.margins;
57483     },
57484     
57485     updateBox : function(box){
57486         this.box = box;
57487         var el = this.activePanel.getEl();
57488         el.dom.style.left = box.x + "px";
57489         el.dom.style.top = box.y + "px";
57490         this.activePanel.setSize(box.width, box.height);
57491     },
57492     
57493     /**
57494      * Returns the container element for this region.
57495      * @return {Roo.Element}
57496      */
57497     getEl : function(){
57498         return this.activePanel;
57499     },
57500     
57501     /**
57502      * Returns true if this region is currently visible.
57503      * @return {Boolean}
57504      */
57505     isVisible : function(){
57506         return this.activePanel ? true : false;
57507     },
57508     
57509     setActivePanel : function(panel){
57510         panel = this.getPanel(panel);
57511         if(this.activePanel && this.activePanel != panel){
57512             this.activePanel.setActiveState(false);
57513             this.activePanel.getEl().setLeftTop(-10000,-10000);
57514         }
57515         this.activePanel = panel;
57516         panel.setActiveState(true);
57517         if(this.box){
57518             panel.setSize(this.box.width, this.box.height);
57519         }
57520         this.fireEvent("panelactivated", this, panel);
57521         this.fireEvent("invalidated");
57522     },
57523     
57524     /**
57525      * Show the specified panel.
57526      * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
57527      * @return {Roo.ContentPanel} The shown panel or null
57528      */
57529     showPanel : function(panel){
57530         if(panel = this.getPanel(panel)){
57531             this.setActivePanel(panel);
57532         }
57533         return panel;
57534     },
57535     
57536     /**
57537      * Get the active panel for this region.
57538      * @return {Roo.ContentPanel} The active panel or null
57539      */
57540     getActivePanel : function(){
57541         return this.activePanel;
57542     },
57543     
57544     /**
57545      * Add the passed ContentPanel(s)
57546      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
57547      * @return {Roo.ContentPanel} The panel added (if only one was added)
57548      */
57549     add : function(panel){
57550         if(arguments.length > 1){
57551             for(var i = 0, len = arguments.length; i < len; i++) {
57552                 this.add(arguments[i]);
57553             }
57554             return null;
57555         }
57556         if(this.hasPanel(panel)){
57557             this.showPanel(panel);
57558             return panel;
57559         }
57560         var el = panel.getEl();
57561         if(el.dom.parentNode != this.mgr.el.dom){
57562             this.mgr.el.dom.appendChild(el.dom);
57563         }
57564         if(panel.setRegion){
57565             panel.setRegion(this);
57566         }
57567         this.panels.add(panel);
57568         el.setStyle("position", "absolute");
57569         if(!panel.background){
57570             this.setActivePanel(panel);
57571             if(this.config.initialSize && this.panels.getCount()==1){
57572                 this.resizeTo(this.config.initialSize);
57573             }
57574         }
57575         this.fireEvent("paneladded", this, panel);
57576         return panel;
57577     },
57578     
57579     /**
57580      * Returns true if the panel is in this region.
57581      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
57582      * @return {Boolean}
57583      */
57584     hasPanel : function(panel){
57585         if(typeof panel == "object"){ // must be panel obj
57586             panel = panel.getId();
57587         }
57588         return this.getPanel(panel) ? true : false;
57589     },
57590     
57591     /**
57592      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
57593      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
57594      * @param {Boolean} preservePanel Overrides the config preservePanel option
57595      * @return {Roo.ContentPanel} The panel that was removed
57596      */
57597     remove : function(panel, preservePanel){
57598         panel = this.getPanel(panel);
57599         if(!panel){
57600             return null;
57601         }
57602         var e = {};
57603         this.fireEvent("beforeremove", this, panel, e);
57604         if(e.cancel === true){
57605             return null;
57606         }
57607         var panelId = panel.getId();
57608         this.panels.removeKey(panelId);
57609         return panel;
57610     },
57611     
57612     /**
57613      * Returns the panel specified or null if it's not in this region.
57614      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
57615      * @return {Roo.ContentPanel}
57616      */
57617     getPanel : function(id){
57618         if(typeof id == "object"){ // must be panel obj
57619             return id;
57620         }
57621         return this.panels.get(id);
57622     },
57623     
57624     /**
57625      * Returns this regions position (north/south/east/west/center).
57626      * @return {String} 
57627      */
57628     getPosition: function(){
57629         return this.position;    
57630     }
57631 });/*
57632  * Based on:
57633  * Ext JS Library 1.1.1
57634  * Copyright(c) 2006-2007, Ext JS, LLC.
57635  *
57636  * Originally Released Under LGPL - original licence link has changed is not relivant.
57637  *
57638  * Fork - LGPL
57639  * <script type="text/javascript">
57640  */
57641  
57642 /**
57643  * @class Roo.LayoutRegion
57644  * @extends Roo.BasicLayoutRegion
57645  * This class represents a region in a layout manager.
57646  * @cfg {Boolean}   collapsible     False to disable collapsing (defaults to true)
57647  * @cfg {Boolean}   collapsed       True to set the initial display to collapsed (defaults to false)
57648  * @cfg {Boolean}   floatable       False to disable floating (defaults to true)
57649  * @cfg {Object}    margins         Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
57650  * @cfg {Object}    cmargins        Margins for the element when collapsed (defaults to: north/south {top: 2, left: 0, right:0, bottom: 2} or east/west {top: 0, left: 2, right:2, bottom: 0})
57651  * @cfg {String}    tabPosition     (top|bottom) "top" or "bottom" (defaults to "bottom")
57652  * @cfg {String}    collapsedTitle  Optional string message to display in the collapsed block of a north or south region
57653  * @cfg {Boolean}   alwaysShowTabs  True to always display tabs even when there is only 1 panel (defaults to false)
57654  * @cfg {Boolean}   autoScroll      True to enable overflow scrolling (defaults to false)
57655  * @cfg {Boolean}   titlebar        True to display a title bar (defaults to true)
57656  * @cfg {String}    title           The title for the region (overrides panel titles)
57657  * @cfg {Boolean}   animate         True to animate expand/collapse (defaults to false)
57658  * @cfg {Boolean}   autoHide        False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
57659  * @cfg {Boolean}   preservePanels  True to preserve removed panels so they can be readded later (defaults to false)
57660  * @cfg {Boolean}   closeOnTab      True to place the close icon on the tabs instead of the region titlebar (defaults to false)
57661  * @cfg {Boolean}   hideTabs        True to hide the tab strip (defaults to false)
57662  * @cfg {Boolean}   resizeTabs      True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
57663  *                      the space available, similar to FireFox 1.5 tabs (defaults to false)
57664  * @cfg {Number}    minTabWidth     The minimum tab width (defaults to 40)
57665  * @cfg {Number}    preferredTabWidth The preferred tab width (defaults to 150)
57666  * @cfg {Boolean}   showPin         True to show a pin button
57667  * @cfg {Boolean}   hidden          True to start the region hidden (defaults to false)
57668  * @cfg {Boolean}   hideWhenEmpty   True to hide the region when it has no panels
57669  * @cfg {Boolean}   disableTabTips  True to disable tab tooltips
57670  * @cfg {Number}    width           For East/West panels
57671  * @cfg {Number}    height          For North/South panels
57672  * @cfg {Boolean}   split           To show the splitter
57673  * @cfg {Boolean}   toolbar         xtype configuration for a toolbar - shows on right of tabbar
57674  */
57675 Roo.LayoutRegion = function(mgr, config, pos){
57676     Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
57677     var dh = Roo.DomHelper;
57678     /** This region's container element 
57679     * @type Roo.Element */
57680     this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
57681     /** This region's title element 
57682     * @type Roo.Element */
57683
57684     this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
57685         {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: "&#160;"},
57686         {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
57687     ]}, true);
57688     this.titleEl.enableDisplayMode();
57689     /** This region's title text element 
57690     * @type HTMLElement */
57691     this.titleTextEl = this.titleEl.dom.firstChild;
57692     this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
57693     this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
57694     this.closeBtn.enableDisplayMode();
57695     this.closeBtn.on("click", this.closeClicked, this);
57696     this.closeBtn.hide();
57697
57698     this.createBody(config);
57699     this.visible = true;
57700     this.collapsed = false;
57701
57702     if(config.hideWhenEmpty){
57703         this.hide();
57704         this.on("paneladded", this.validateVisibility, this);
57705         this.on("panelremoved", this.validateVisibility, this);
57706     }
57707     this.applyConfig(config);
57708 };
57709
57710 Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
57711
57712     createBody : function(){
57713         /** This region's body element 
57714         * @type Roo.Element */
57715         this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
57716     },
57717
57718     applyConfig : function(c){
57719         if(c.collapsible && this.position != "center" && !this.collapsedEl){
57720             var dh = Roo.DomHelper;
57721             if(c.titlebar !== false){
57722                 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
57723                 this.collapseBtn.on("click", this.collapse, this);
57724                 this.collapseBtn.enableDisplayMode();
57725
57726                 if(c.showPin === true || this.showPin){
57727                     this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
57728                     this.stickBtn.enableDisplayMode();
57729                     this.stickBtn.on("click", this.expand, this);
57730                     this.stickBtn.hide();
57731                 }
57732             }
57733             /** This region's collapsed element
57734             * @type Roo.Element */
57735             this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
57736                 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
57737             ]}, true);
57738             if(c.floatable !== false){
57739                this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
57740                this.collapsedEl.on("click", this.collapseClick, this);
57741             }
57742
57743             if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
57744                 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
57745                    id: "message", unselectable: "on", style:{"float":"left"}});
57746                this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
57747              }
57748             this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
57749             this.expandBtn.on("click", this.expand, this);
57750         }
57751         if(this.collapseBtn){
57752             this.collapseBtn.setVisible(c.collapsible == true);
57753         }
57754         this.cmargins = c.cmargins || this.cmargins ||
57755                          (this.position == "west" || this.position == "east" ?
57756                              {top: 0, left: 2, right:2, bottom: 0} :
57757                              {top: 2, left: 0, right:0, bottom: 2});
57758         this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
57759         this.bottomTabs = c.tabPosition != "top";
57760         this.autoScroll = c.autoScroll || false;
57761         if(this.autoScroll){
57762             this.bodyEl.setStyle("overflow", "auto");
57763         }else{
57764             this.bodyEl.setStyle("overflow", "hidden");
57765         }
57766         //if(c.titlebar !== false){
57767             if((!c.titlebar && !c.title) || c.titlebar === false){
57768                 this.titleEl.hide();
57769             }else{
57770                 this.titleEl.show();
57771                 if(c.title){
57772                     this.titleTextEl.innerHTML = c.title;
57773                 }
57774             }
57775         //}
57776         this.duration = c.duration || .30;
57777         this.slideDuration = c.slideDuration || .45;
57778         this.config = c;
57779         if(c.collapsed){
57780             this.collapse(true);
57781         }
57782         if(c.hidden){
57783             this.hide();
57784         }
57785     },
57786     /**
57787      * Returns true if this region is currently visible.
57788      * @return {Boolean}
57789      */
57790     isVisible : function(){
57791         return this.visible;
57792     },
57793
57794     /**
57795      * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
57796      * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&amp;#160;")
57797      */
57798     setCollapsedTitle : function(title){
57799         title = title || "&#160;";
57800         if(this.collapsedTitleTextEl){
57801             this.collapsedTitleTextEl.innerHTML = title;
57802         }
57803     },
57804
57805     getBox : function(){
57806         var b;
57807         if(!this.collapsed){
57808             b = this.el.getBox(false, true);
57809         }else{
57810             b = this.collapsedEl.getBox(false, true);
57811         }
57812         return b;
57813     },
57814
57815     getMargins : function(){
57816         return this.collapsed ? this.cmargins : this.margins;
57817     },
57818
57819     highlight : function(){
57820         this.el.addClass("x-layout-panel-dragover");
57821     },
57822
57823     unhighlight : function(){
57824         this.el.removeClass("x-layout-panel-dragover");
57825     },
57826
57827     updateBox : function(box){
57828         this.box = box;
57829         if(!this.collapsed){
57830             this.el.dom.style.left = box.x + "px";
57831             this.el.dom.style.top = box.y + "px";
57832             this.updateBody(box.width, box.height);
57833         }else{
57834             this.collapsedEl.dom.style.left = box.x + "px";
57835             this.collapsedEl.dom.style.top = box.y + "px";
57836             this.collapsedEl.setSize(box.width, box.height);
57837         }
57838         if(this.tabs){
57839             this.tabs.autoSizeTabs();
57840         }
57841     },
57842
57843     updateBody : function(w, h){
57844         if(w !== null){
57845             this.el.setWidth(w);
57846             w -= this.el.getBorderWidth("rl");
57847             if(this.config.adjustments){
57848                 w += this.config.adjustments[0];
57849             }
57850         }
57851         if(h !== null){
57852             this.el.setHeight(h);
57853             h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
57854             h -= this.el.getBorderWidth("tb");
57855             if(this.config.adjustments){
57856                 h += this.config.adjustments[1];
57857             }
57858             this.bodyEl.setHeight(h);
57859             if(this.tabs){
57860                 h = this.tabs.syncHeight(h);
57861             }
57862         }
57863         if(this.panelSize){
57864             w = w !== null ? w : this.panelSize.width;
57865             h = h !== null ? h : this.panelSize.height;
57866         }
57867         if(this.activePanel){
57868             var el = this.activePanel.getEl();
57869             w = w !== null ? w : el.getWidth();
57870             h = h !== null ? h : el.getHeight();
57871             this.panelSize = {width: w, height: h};
57872             this.activePanel.setSize(w, h);
57873         }
57874         if(Roo.isIE && this.tabs){
57875             this.tabs.el.repaint();
57876         }
57877     },
57878
57879     /**
57880      * Returns the container element for this region.
57881      * @return {Roo.Element}
57882      */
57883     getEl : function(){
57884         return this.el;
57885     },
57886
57887     /**
57888      * Hides this region.
57889      */
57890     hide : function(){
57891         if(!this.collapsed){
57892             this.el.dom.style.left = "-2000px";
57893             this.el.hide();
57894         }else{
57895             this.collapsedEl.dom.style.left = "-2000px";
57896             this.collapsedEl.hide();
57897         }
57898         this.visible = false;
57899         this.fireEvent("visibilitychange", this, false);
57900     },
57901
57902     /**
57903      * Shows this region if it was previously hidden.
57904      */
57905     show : function(){
57906         if(!this.collapsed){
57907             this.el.show();
57908         }else{
57909             this.collapsedEl.show();
57910         }
57911         this.visible = true;
57912         this.fireEvent("visibilitychange", this, true);
57913     },
57914
57915     closeClicked : function(){
57916         if(this.activePanel){
57917             this.remove(this.activePanel);
57918         }
57919     },
57920
57921     collapseClick : function(e){
57922         if(this.isSlid){
57923            e.stopPropagation();
57924            this.slideIn();
57925         }else{
57926            e.stopPropagation();
57927            this.slideOut();
57928         }
57929     },
57930
57931     /**
57932      * Collapses this region.
57933      * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
57934      */
57935     collapse : function(skipAnim, skipCheck){
57936         if(this.collapsed) {
57937             return;
57938         }
57939         
57940         if(skipCheck || this.fireEvent("beforecollapse", this) != false){
57941             
57942             this.collapsed = true;
57943             if(this.split){
57944                 this.split.el.hide();
57945             }
57946             if(this.config.animate && skipAnim !== true){
57947                 this.fireEvent("invalidated", this);
57948                 this.animateCollapse();
57949             }else{
57950                 this.el.setLocation(-20000,-20000);
57951                 this.el.hide();
57952                 this.collapsedEl.show();
57953                 this.fireEvent("collapsed", this);
57954                 this.fireEvent("invalidated", this);
57955             }
57956         }
57957         
57958     },
57959
57960     animateCollapse : function(){
57961         // overridden
57962     },
57963
57964     /**
57965      * Expands this region if it was previously collapsed.
57966      * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
57967      * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
57968      */
57969     expand : function(e, skipAnim){
57970         if(e) {
57971             e.stopPropagation();
57972         }
57973         if(!this.collapsed || this.el.hasActiveFx()) {
57974             return;
57975         }
57976         if(this.isSlid){
57977             this.afterSlideIn();
57978             skipAnim = true;
57979         }
57980         this.collapsed = false;
57981         if(this.config.animate && skipAnim !== true){
57982             this.animateExpand();
57983         }else{
57984             this.el.show();
57985             if(this.split){
57986                 this.split.el.show();
57987             }
57988             this.collapsedEl.setLocation(-2000,-2000);
57989             this.collapsedEl.hide();
57990             this.fireEvent("invalidated", this);
57991             this.fireEvent("expanded", this);
57992         }
57993     },
57994
57995     animateExpand : function(){
57996         // overridden
57997     },
57998
57999     initTabs : function()
58000     {
58001         this.bodyEl.setStyle("overflow", "hidden");
58002         var ts = new Roo.TabPanel(
58003                 this.bodyEl.dom,
58004                 {
58005                     tabPosition: this.bottomTabs ? 'bottom' : 'top',
58006                     disableTooltips: this.config.disableTabTips,
58007                     toolbar : this.config.toolbar
58008                 }
58009         );
58010         if(this.config.hideTabs){
58011             ts.stripWrap.setDisplayed(false);
58012         }
58013         this.tabs = ts;
58014         ts.resizeTabs = this.config.resizeTabs === true;
58015         ts.minTabWidth = this.config.minTabWidth || 40;
58016         ts.maxTabWidth = this.config.maxTabWidth || 250;
58017         ts.preferredTabWidth = this.config.preferredTabWidth || 150;
58018         ts.monitorResize = false;
58019         ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
58020         ts.bodyEl.addClass('x-layout-tabs-body');
58021         this.panels.each(this.initPanelAsTab, this);
58022     },
58023
58024     initPanelAsTab : function(panel){
58025         var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
58026                     this.config.closeOnTab && panel.isClosable());
58027         if(panel.tabTip !== undefined){
58028             ti.setTooltip(panel.tabTip);
58029         }
58030         ti.on("activate", function(){
58031               this.setActivePanel(panel);
58032         }, this);
58033         if(this.config.closeOnTab){
58034             ti.on("beforeclose", function(t, e){
58035                 e.cancel = true;
58036                 this.remove(panel);
58037             }, this);
58038         }
58039         return ti;
58040     },
58041
58042     updatePanelTitle : function(panel, title){
58043         if(this.activePanel == panel){
58044             this.updateTitle(title);
58045         }
58046         if(this.tabs){
58047             var ti = this.tabs.getTab(panel.getEl().id);
58048             ti.setText(title);
58049             if(panel.tabTip !== undefined){
58050                 ti.setTooltip(panel.tabTip);
58051             }
58052         }
58053     },
58054
58055     updateTitle : function(title){
58056         if(this.titleTextEl && !this.config.title){
58057             this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : "&#160;");
58058         }
58059     },
58060
58061     setActivePanel : function(panel){
58062         panel = this.getPanel(panel);
58063         if(this.activePanel && this.activePanel != panel){
58064             this.activePanel.setActiveState(false);
58065         }
58066         this.activePanel = panel;
58067         panel.setActiveState(true);
58068         if(this.panelSize){
58069             panel.setSize(this.panelSize.width, this.panelSize.height);
58070         }
58071         if(this.closeBtn){
58072             this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
58073         }
58074         this.updateTitle(panel.getTitle());
58075         if(this.tabs){
58076             this.fireEvent("invalidated", this);
58077         }
58078         this.fireEvent("panelactivated", this, panel);
58079     },
58080
58081     /**
58082      * Shows the specified panel.
58083      * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
58084      * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
58085      */
58086     showPanel : function(panel)
58087     {
58088         panel = this.getPanel(panel);
58089         if(panel){
58090             if(this.tabs){
58091                 var tab = this.tabs.getTab(panel.getEl().id);
58092                 if(tab.isHidden()){
58093                     this.tabs.unhideTab(tab.id);
58094                 }
58095                 tab.activate();
58096             }else{
58097                 this.setActivePanel(panel);
58098             }
58099         }
58100         return panel;
58101     },
58102
58103     /**
58104      * Get the active panel for this region.
58105      * @return {Roo.ContentPanel} The active panel or null
58106      */
58107     getActivePanel : function(){
58108         return this.activePanel;
58109     },
58110
58111     validateVisibility : function(){
58112         if(this.panels.getCount() < 1){
58113             this.updateTitle("&#160;");
58114             this.closeBtn.hide();
58115             this.hide();
58116         }else{
58117             if(!this.isVisible()){
58118                 this.show();
58119             }
58120         }
58121     },
58122
58123     /**
58124      * Adds the passed ContentPanel(s) to this region.
58125      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
58126      * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
58127      */
58128     add : function(panel){
58129         if(arguments.length > 1){
58130             for(var i = 0, len = arguments.length; i < len; i++) {
58131                 this.add(arguments[i]);
58132             }
58133             return null;
58134         }
58135         if(this.hasPanel(panel)){
58136             this.showPanel(panel);
58137             return panel;
58138         }
58139         panel.setRegion(this);
58140         this.panels.add(panel);
58141         if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
58142             this.bodyEl.dom.appendChild(panel.getEl().dom);
58143             if(panel.background !== true){
58144                 this.setActivePanel(panel);
58145             }
58146             this.fireEvent("paneladded", this, panel);
58147             return panel;
58148         }
58149         if(!this.tabs){
58150             this.initTabs();
58151         }else{
58152             this.initPanelAsTab(panel);
58153         }
58154         if(panel.background !== true){
58155             this.tabs.activate(panel.getEl().id);
58156         }
58157         this.fireEvent("paneladded", this, panel);
58158         return panel;
58159     },
58160
58161     /**
58162      * Hides the tab for the specified panel.
58163      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
58164      */
58165     hidePanel : function(panel){
58166         if(this.tabs && (panel = this.getPanel(panel))){
58167             this.tabs.hideTab(panel.getEl().id);
58168         }
58169     },
58170
58171     /**
58172      * Unhides the tab for a previously hidden panel.
58173      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
58174      */
58175     unhidePanel : function(panel){
58176         if(this.tabs && (panel = this.getPanel(panel))){
58177             this.tabs.unhideTab(panel.getEl().id);
58178         }
58179     },
58180
58181     clearPanels : function(){
58182         while(this.panels.getCount() > 0){
58183              this.remove(this.panels.first());
58184         }
58185     },
58186
58187     /**
58188      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
58189      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
58190      * @param {Boolean} preservePanel Overrides the config preservePanel option
58191      * @return {Roo.ContentPanel} The panel that was removed
58192      */
58193     remove : function(panel, preservePanel){
58194         panel = this.getPanel(panel);
58195         if(!panel){
58196             return null;
58197         }
58198         var e = {};
58199         this.fireEvent("beforeremove", this, panel, e);
58200         if(e.cancel === true){
58201             return null;
58202         }
58203         preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
58204         var panelId = panel.getId();
58205         this.panels.removeKey(panelId);
58206         if(preservePanel){
58207             document.body.appendChild(panel.getEl().dom);
58208         }
58209         if(this.tabs){
58210             this.tabs.removeTab(panel.getEl().id);
58211         }else if (!preservePanel){
58212             this.bodyEl.dom.removeChild(panel.getEl().dom);
58213         }
58214         if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
58215             var p = this.panels.first();
58216             var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
58217             tempEl.appendChild(p.getEl().dom);
58218             this.bodyEl.update("");
58219             this.bodyEl.dom.appendChild(p.getEl().dom);
58220             tempEl = null;
58221             this.updateTitle(p.getTitle());
58222             this.tabs = null;
58223             this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
58224             this.setActivePanel(p);
58225         }
58226         panel.setRegion(null);
58227         if(this.activePanel == panel){
58228             this.activePanel = null;
58229         }
58230         if(this.config.autoDestroy !== false && preservePanel !== true){
58231             try{panel.destroy();}catch(e){}
58232         }
58233         this.fireEvent("panelremoved", this, panel);
58234         return panel;
58235     },
58236
58237     /**
58238      * Returns the TabPanel component used by this region
58239      * @return {Roo.TabPanel}
58240      */
58241     getTabs : function(){
58242         return this.tabs;
58243     },
58244
58245     createTool : function(parentEl, className){
58246         var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
58247             children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: "&#160;"}]}, true);
58248         btn.addClassOnOver("x-layout-tools-button-over");
58249         return btn;
58250     }
58251 });/*
58252  * Based on:
58253  * Ext JS Library 1.1.1
58254  * Copyright(c) 2006-2007, Ext JS, LLC.
58255  *
58256  * Originally Released Under LGPL - original licence link has changed is not relivant.
58257  *
58258  * Fork - LGPL
58259  * <script type="text/javascript">
58260  */
58261  
58262
58263
58264 /**
58265  * @class Roo.SplitLayoutRegion
58266  * @extends Roo.LayoutRegion
58267  * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
58268  */
58269 Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
58270     this.cursor = cursor;
58271     Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
58272 };
58273
58274 Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
58275     splitTip : "Drag to resize.",
58276     collapsibleSplitTip : "Drag to resize. Double click to hide.",
58277     useSplitTips : false,
58278
58279     applyConfig : function(config){
58280         Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
58281         if(config.split){
58282             if(!this.split){
58283                 var splitEl = Roo.DomHelper.append(this.mgr.el.dom, 
58284                         {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: "&#160;"});
58285                 /** The SplitBar for this region 
58286                 * @type Roo.SplitBar */
58287                 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
58288                 this.split.on("moved", this.onSplitMove, this);
58289                 this.split.useShim = config.useShim === true;
58290                 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
58291                 if(this.useSplitTips){
58292                     this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
58293                 }
58294                 if(config.collapsible){
58295                     this.split.el.on("dblclick", this.collapse,  this);
58296                 }
58297             }
58298             if(typeof config.minSize != "undefined"){
58299                 this.split.minSize = config.minSize;
58300             }
58301             if(typeof config.maxSize != "undefined"){
58302                 this.split.maxSize = config.maxSize;
58303             }
58304             if(config.hideWhenEmpty || config.hidden || config.collapsed){
58305                 this.hideSplitter();
58306             }
58307         }
58308     },
58309
58310     getHMaxSize : function(){
58311          var cmax = this.config.maxSize || 10000;
58312          var center = this.mgr.getRegion("center");
58313          return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
58314     },
58315
58316     getVMaxSize : function(){
58317          var cmax = this.config.maxSize || 10000;
58318          var center = this.mgr.getRegion("center");
58319          return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
58320     },
58321
58322     onSplitMove : function(split, newSize){
58323         this.fireEvent("resized", this, newSize);
58324     },
58325     
58326     /** 
58327      * Returns the {@link Roo.SplitBar} for this region.
58328      * @return {Roo.SplitBar}
58329      */
58330     getSplitBar : function(){
58331         return this.split;
58332     },
58333     
58334     hide : function(){
58335         this.hideSplitter();
58336         Roo.SplitLayoutRegion.superclass.hide.call(this);
58337     },
58338
58339     hideSplitter : function(){
58340         if(this.split){
58341             this.split.el.setLocation(-2000,-2000);
58342             this.split.el.hide();
58343         }
58344     },
58345
58346     show : function(){
58347         if(this.split){
58348             this.split.el.show();
58349         }
58350         Roo.SplitLayoutRegion.superclass.show.call(this);
58351     },
58352     
58353     beforeSlide: function(){
58354         if(Roo.isGecko){// firefox overflow auto bug workaround
58355             this.bodyEl.clip();
58356             if(this.tabs) {
58357                 this.tabs.bodyEl.clip();
58358             }
58359             if(this.activePanel){
58360                 this.activePanel.getEl().clip();
58361                 
58362                 if(this.activePanel.beforeSlide){
58363                     this.activePanel.beforeSlide();
58364                 }
58365             }
58366         }
58367     },
58368     
58369     afterSlide : function(){
58370         if(Roo.isGecko){// firefox overflow auto bug workaround
58371             this.bodyEl.unclip();
58372             if(this.tabs) {
58373                 this.tabs.bodyEl.unclip();
58374             }
58375             if(this.activePanel){
58376                 this.activePanel.getEl().unclip();
58377                 if(this.activePanel.afterSlide){
58378                     this.activePanel.afterSlide();
58379                 }
58380             }
58381         }
58382     },
58383
58384     initAutoHide : function(){
58385         if(this.autoHide !== false){
58386             if(!this.autoHideHd){
58387                 var st = new Roo.util.DelayedTask(this.slideIn, this);
58388                 this.autoHideHd = {
58389                     "mouseout": function(e){
58390                         if(!e.within(this.el, true)){
58391                             st.delay(500);
58392                         }
58393                     },
58394                     "mouseover" : function(e){
58395                         st.cancel();
58396                     },
58397                     scope : this
58398                 };
58399             }
58400             this.el.on(this.autoHideHd);
58401         }
58402     },
58403
58404     clearAutoHide : function(){
58405         if(this.autoHide !== false){
58406             this.el.un("mouseout", this.autoHideHd.mouseout);
58407             this.el.un("mouseover", this.autoHideHd.mouseover);
58408         }
58409     },
58410
58411     clearMonitor : function(){
58412         Roo.get(document).un("click", this.slideInIf, this);
58413     },
58414
58415     // these names are backwards but not changed for compat
58416     slideOut : function(){
58417         if(this.isSlid || this.el.hasActiveFx()){
58418             return;
58419         }
58420         this.isSlid = true;
58421         if(this.collapseBtn){
58422             this.collapseBtn.hide();
58423         }
58424         this.closeBtnState = this.closeBtn.getStyle('display');
58425         this.closeBtn.hide();
58426         if(this.stickBtn){
58427             this.stickBtn.show();
58428         }
58429         this.el.show();
58430         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
58431         this.beforeSlide();
58432         this.el.setStyle("z-index", 10001);
58433         this.el.slideIn(this.getSlideAnchor(), {
58434             callback: function(){
58435                 this.afterSlide();
58436                 this.initAutoHide();
58437                 Roo.get(document).on("click", this.slideInIf, this);
58438                 this.fireEvent("slideshow", this);
58439             },
58440             scope: this,
58441             block: true
58442         });
58443     },
58444
58445     afterSlideIn : function(){
58446         this.clearAutoHide();
58447         this.isSlid = false;
58448         this.clearMonitor();
58449         this.el.setStyle("z-index", "");
58450         if(this.collapseBtn){
58451             this.collapseBtn.show();
58452         }
58453         this.closeBtn.setStyle('display', this.closeBtnState);
58454         if(this.stickBtn){
58455             this.stickBtn.hide();
58456         }
58457         this.fireEvent("slidehide", this);
58458     },
58459
58460     slideIn : function(cb){
58461         if(!this.isSlid || this.el.hasActiveFx()){
58462             Roo.callback(cb);
58463             return;
58464         }
58465         this.isSlid = false;
58466         this.beforeSlide();
58467         this.el.slideOut(this.getSlideAnchor(), {
58468             callback: function(){
58469                 this.el.setLeftTop(-10000, -10000);
58470                 this.afterSlide();
58471                 this.afterSlideIn();
58472                 Roo.callback(cb);
58473             },
58474             scope: this,
58475             block: true
58476         });
58477     },
58478     
58479     slideInIf : function(e){
58480         if(!e.within(this.el)){
58481             this.slideIn();
58482         }
58483     },
58484
58485     animateCollapse : function(){
58486         this.beforeSlide();
58487         this.el.setStyle("z-index", 20000);
58488         var anchor = this.getSlideAnchor();
58489         this.el.slideOut(anchor, {
58490             callback : function(){
58491                 this.el.setStyle("z-index", "");
58492                 this.collapsedEl.slideIn(anchor, {duration:.3});
58493                 this.afterSlide();
58494                 this.el.setLocation(-10000,-10000);
58495                 this.el.hide();
58496                 this.fireEvent("collapsed", this);
58497             },
58498             scope: this,
58499             block: true
58500         });
58501     },
58502
58503     animateExpand : function(){
58504         this.beforeSlide();
58505         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
58506         this.el.setStyle("z-index", 20000);
58507         this.collapsedEl.hide({
58508             duration:.1
58509         });
58510         this.el.slideIn(this.getSlideAnchor(), {
58511             callback : function(){
58512                 this.el.setStyle("z-index", "");
58513                 this.afterSlide();
58514                 if(this.split){
58515                     this.split.el.show();
58516                 }
58517                 this.fireEvent("invalidated", this);
58518                 this.fireEvent("expanded", this);
58519             },
58520             scope: this,
58521             block: true
58522         });
58523     },
58524
58525     anchors : {
58526         "west" : "left",
58527         "east" : "right",
58528         "north" : "top",
58529         "south" : "bottom"
58530     },
58531
58532     sanchors : {
58533         "west" : "l",
58534         "east" : "r",
58535         "north" : "t",
58536         "south" : "b"
58537     },
58538
58539     canchors : {
58540         "west" : "tl-tr",
58541         "east" : "tr-tl",
58542         "north" : "tl-bl",
58543         "south" : "bl-tl"
58544     },
58545
58546     getAnchor : function(){
58547         return this.anchors[this.position];
58548     },
58549
58550     getCollapseAnchor : function(){
58551         return this.canchors[this.position];
58552     },
58553
58554     getSlideAnchor : function(){
58555         return this.sanchors[this.position];
58556     },
58557
58558     getAlignAdj : function(){
58559         var cm = this.cmargins;
58560         switch(this.position){
58561             case "west":
58562                 return [0, 0];
58563             break;
58564             case "east":
58565                 return [0, 0];
58566             break;
58567             case "north":
58568                 return [0, 0];
58569             break;
58570             case "south":
58571                 return [0, 0];
58572             break;
58573         }
58574     },
58575
58576     getExpandAdj : function(){
58577         var c = this.collapsedEl, cm = this.cmargins;
58578         switch(this.position){
58579             case "west":
58580                 return [-(cm.right+c.getWidth()+cm.left), 0];
58581             break;
58582             case "east":
58583                 return [cm.right+c.getWidth()+cm.left, 0];
58584             break;
58585             case "north":
58586                 return [0, -(cm.top+cm.bottom+c.getHeight())];
58587             break;
58588             case "south":
58589                 return [0, cm.top+cm.bottom+c.getHeight()];
58590             break;
58591         }
58592     }
58593 });/*
58594  * Based on:
58595  * Ext JS Library 1.1.1
58596  * Copyright(c) 2006-2007, Ext JS, LLC.
58597  *
58598  * Originally Released Under LGPL - original licence link has changed is not relivant.
58599  *
58600  * Fork - LGPL
58601  * <script type="text/javascript">
58602  */
58603 /*
58604  * These classes are private internal classes
58605  */
58606 Roo.CenterLayoutRegion = function(mgr, config){
58607     Roo.LayoutRegion.call(this, mgr, config, "center");
58608     this.visible = true;
58609     this.minWidth = config.minWidth || 20;
58610     this.minHeight = config.minHeight || 20;
58611 };
58612
58613 Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
58614     hide : function(){
58615         // center panel can't be hidden
58616     },
58617     
58618     show : function(){
58619         // center panel can't be hidden
58620     },
58621     
58622     getMinWidth: function(){
58623         return this.minWidth;
58624     },
58625     
58626     getMinHeight: function(){
58627         return this.minHeight;
58628     }
58629 });
58630
58631
58632 Roo.NorthLayoutRegion = function(mgr, config){
58633     Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
58634     if(this.split){
58635         this.split.placement = Roo.SplitBar.TOP;
58636         this.split.orientation = Roo.SplitBar.VERTICAL;
58637         this.split.el.addClass("x-layout-split-v");
58638     }
58639     var size = config.initialSize || config.height;
58640     if(typeof size != "undefined"){
58641         this.el.setHeight(size);
58642     }
58643 };
58644 Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
58645     orientation: Roo.SplitBar.VERTICAL,
58646     getBox : function(){
58647         if(this.collapsed){
58648             return this.collapsedEl.getBox();
58649         }
58650         var box = this.el.getBox();
58651         if(this.split){
58652             box.height += this.split.el.getHeight();
58653         }
58654         return box;
58655     },
58656     
58657     updateBox : function(box){
58658         if(this.split && !this.collapsed){
58659             box.height -= this.split.el.getHeight();
58660             this.split.el.setLeft(box.x);
58661             this.split.el.setTop(box.y+box.height);
58662             this.split.el.setWidth(box.width);
58663         }
58664         if(this.collapsed){
58665             this.updateBody(box.width, null);
58666         }
58667         Roo.LayoutRegion.prototype.updateBox.call(this, box);
58668     }
58669 });
58670
58671 Roo.SouthLayoutRegion = function(mgr, config){
58672     Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
58673     if(this.split){
58674         this.split.placement = Roo.SplitBar.BOTTOM;
58675         this.split.orientation = Roo.SplitBar.VERTICAL;
58676         this.split.el.addClass("x-layout-split-v");
58677     }
58678     var size = config.initialSize || config.height;
58679     if(typeof size != "undefined"){
58680         this.el.setHeight(size);
58681     }
58682 };
58683 Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
58684     orientation: Roo.SplitBar.VERTICAL,
58685     getBox : function(){
58686         if(this.collapsed){
58687             return this.collapsedEl.getBox();
58688         }
58689         var box = this.el.getBox();
58690         if(this.split){
58691             var sh = this.split.el.getHeight();
58692             box.height += sh;
58693             box.y -= sh;
58694         }
58695         return box;
58696     },
58697     
58698     updateBox : function(box){
58699         if(this.split && !this.collapsed){
58700             var sh = this.split.el.getHeight();
58701             box.height -= sh;
58702             box.y += sh;
58703             this.split.el.setLeft(box.x);
58704             this.split.el.setTop(box.y-sh);
58705             this.split.el.setWidth(box.width);
58706         }
58707         if(this.collapsed){
58708             this.updateBody(box.width, null);
58709         }
58710         Roo.LayoutRegion.prototype.updateBox.call(this, box);
58711     }
58712 });
58713
58714 Roo.EastLayoutRegion = function(mgr, config){
58715     Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
58716     if(this.split){
58717         this.split.placement = Roo.SplitBar.RIGHT;
58718         this.split.orientation = Roo.SplitBar.HORIZONTAL;
58719         this.split.el.addClass("x-layout-split-h");
58720     }
58721     var size = config.initialSize || config.width;
58722     if(typeof size != "undefined"){
58723         this.el.setWidth(size);
58724     }
58725 };
58726 Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
58727     orientation: Roo.SplitBar.HORIZONTAL,
58728     getBox : function(){
58729         if(this.collapsed){
58730             return this.collapsedEl.getBox();
58731         }
58732         var box = this.el.getBox();
58733         if(this.split){
58734             var sw = this.split.el.getWidth();
58735             box.width += sw;
58736             box.x -= sw;
58737         }
58738         return box;
58739     },
58740
58741     updateBox : function(box){
58742         if(this.split && !this.collapsed){
58743             var sw = this.split.el.getWidth();
58744             box.width -= sw;
58745             this.split.el.setLeft(box.x);
58746             this.split.el.setTop(box.y);
58747             this.split.el.setHeight(box.height);
58748             box.x += sw;
58749         }
58750         if(this.collapsed){
58751             this.updateBody(null, box.height);
58752         }
58753         Roo.LayoutRegion.prototype.updateBox.call(this, box);
58754     }
58755 });
58756
58757 Roo.WestLayoutRegion = function(mgr, config){
58758     Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
58759     if(this.split){
58760         this.split.placement = Roo.SplitBar.LEFT;
58761         this.split.orientation = Roo.SplitBar.HORIZONTAL;
58762         this.split.el.addClass("x-layout-split-h");
58763     }
58764     var size = config.initialSize || config.width;
58765     if(typeof size != "undefined"){
58766         this.el.setWidth(size);
58767     }
58768 };
58769 Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
58770     orientation: Roo.SplitBar.HORIZONTAL,
58771     getBox : function(){
58772         if(this.collapsed){
58773             return this.collapsedEl.getBox();
58774         }
58775         var box = this.el.getBox();
58776         if(this.split){
58777             box.width += this.split.el.getWidth();
58778         }
58779         return box;
58780     },
58781     
58782     updateBox : function(box){
58783         if(this.split && !this.collapsed){
58784             var sw = this.split.el.getWidth();
58785             box.width -= sw;
58786             this.split.el.setLeft(box.x+box.width);
58787             this.split.el.setTop(box.y);
58788             this.split.el.setHeight(box.height);
58789         }
58790         if(this.collapsed){
58791             this.updateBody(null, box.height);
58792         }
58793         Roo.LayoutRegion.prototype.updateBox.call(this, box);
58794     }
58795 });
58796 /*
58797  * Based on:
58798  * Ext JS Library 1.1.1
58799  * Copyright(c) 2006-2007, Ext JS, LLC.
58800  *
58801  * Originally Released Under LGPL - original licence link has changed is not relivant.
58802  *
58803  * Fork - LGPL
58804  * <script type="text/javascript">
58805  */
58806  
58807  
58808 /*
58809  * Private internal class for reading and applying state
58810  */
58811 Roo.LayoutStateManager = function(layout){
58812      // default empty state
58813      this.state = {
58814         north: {},
58815         south: {},
58816         east: {},
58817         west: {}       
58818     };
58819 };
58820
58821 Roo.LayoutStateManager.prototype = {
58822     init : function(layout, provider){
58823         this.provider = provider;
58824         var state = provider.get(layout.id+"-layout-state");
58825         if(state){
58826             var wasUpdating = layout.isUpdating();
58827             if(!wasUpdating){
58828                 layout.beginUpdate();
58829             }
58830             for(var key in state){
58831                 if(typeof state[key] != "function"){
58832                     var rstate = state[key];
58833                     var r = layout.getRegion(key);
58834                     if(r && rstate){
58835                         if(rstate.size){
58836                             r.resizeTo(rstate.size);
58837                         }
58838                         if(rstate.collapsed == true){
58839                             r.collapse(true);
58840                         }else{
58841                             r.expand(null, true);
58842                         }
58843                     }
58844                 }
58845             }
58846             if(!wasUpdating){
58847                 layout.endUpdate();
58848             }
58849             this.state = state; 
58850         }
58851         this.layout = layout;
58852         layout.on("regionresized", this.onRegionResized, this);
58853         layout.on("regioncollapsed", this.onRegionCollapsed, this);
58854         layout.on("regionexpanded", this.onRegionExpanded, this);
58855     },
58856     
58857     storeState : function(){
58858         this.provider.set(this.layout.id+"-layout-state", this.state);
58859     },
58860     
58861     onRegionResized : function(region, newSize){
58862         this.state[region.getPosition()].size = newSize;
58863         this.storeState();
58864     },
58865     
58866     onRegionCollapsed : function(region){
58867         this.state[region.getPosition()].collapsed = true;
58868         this.storeState();
58869     },
58870     
58871     onRegionExpanded : function(region){
58872         this.state[region.getPosition()].collapsed = false;
58873         this.storeState();
58874     }
58875 };/*
58876  * Based on:
58877  * Ext JS Library 1.1.1
58878  * Copyright(c) 2006-2007, Ext JS, LLC.
58879  *
58880  * Originally Released Under LGPL - original licence link has changed is not relivant.
58881  *
58882  * Fork - LGPL
58883  * <script type="text/javascript">
58884  */
58885 /**
58886  * @class Roo.ContentPanel
58887  * @extends Roo.util.Observable
58888  * @children Roo.form.Form Roo.JsonView Roo.View
58889  * @parent Roo.BorderLayout Roo.LayoutDialog builder
58890  * A basic ContentPanel element.
58891  * @cfg {Boolean}   fitToFrame    True for this panel to adjust its size to fit when the region resizes  (defaults to false)
58892  * @cfg {Boolean}   fitContainer   When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container  (defaults to false)
58893  * @cfg {Boolean|Object} autoCreate True to auto generate the DOM element for this panel, or a {@link Roo.DomHelper} config of the element to create
58894  * @cfg {Boolean}   closable      True if the panel can be closed/removed
58895  * @cfg {Boolean}   background    True if the panel should not be activated when it is added (defaults to false)
58896  * @cfg {String|HTMLElement|Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
58897  * @cfg {Roo.Toolbar}   toolbar       A toolbar for this panel
58898  * @cfg {Boolean} autoScroll    True to scroll overflow in this panel (use with {@link #fitToFrame})
58899  * @cfg {String} title          The title for this panel
58900  * @cfg {Array} adjustments     Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
58901  * @cfg {String} url            Calls {@link #setUrl} with this value
58902  * @cfg {String} region (center|north|south|east|west) [required] which region to put this panel on (when used with xtype constructors)
58903  * @cfg {String|Object} params  When used with {@link #url}, calls {@link #setUrl} with this value
58904  * @cfg {Boolean} loadOnce      When used with {@link #url}, calls {@link #setUrl} with this value
58905  * @cfg {String}    content        Raw content to fill content panel with (uses setContent on construction.)
58906  * @cfg {String}    style  Extra style to add to the content panel
58907  * @cfg {Roo.menu.Menu} menu  popup menu
58908
58909  * @constructor
58910  * Create a new ContentPanel.
58911  * @param {String/HTMLElement/Roo.Element} el The container element for this panel
58912  * @param {String/Object} config A string to set only the title or a config object
58913  * @param {String} content (optional) Set the HTML content for this panel
58914  * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
58915  */
58916 Roo.ContentPanel = function(el, config, content){
58917     
58918      
58919     /*
58920     if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
58921         config = el;
58922         el = Roo.id();
58923     }
58924     if (config && config.parentLayout) { 
58925         el = config.parentLayout.el.createChild(); 
58926     }
58927     */
58928     if(el.autoCreate){ // xtype is available if this is called from factory
58929         config = el;
58930         el = Roo.id();
58931     }
58932     this.el = Roo.get(el);
58933     if(!this.el && config && config.autoCreate){
58934         if(typeof config.autoCreate == "object"){
58935             if(!config.autoCreate.id){
58936                 config.autoCreate.id = config.id||el;
58937             }
58938             this.el = Roo.DomHelper.append(document.body,
58939                         config.autoCreate, true);
58940         }else{
58941             this.el = Roo.DomHelper.append(document.body,
58942                         {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
58943         }
58944     }
58945     
58946     
58947     this.closable = false;
58948     this.loaded = false;
58949     this.active = false;
58950     if(typeof config == "string"){
58951         this.title = config;
58952     }else{
58953         Roo.apply(this, config);
58954     }
58955     
58956     if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
58957         this.wrapEl = this.el.wrap();
58958         this.toolbar.container = this.el.insertSibling(false, 'before');
58959         this.toolbar = new Roo.Toolbar(this.toolbar);
58960     }
58961     
58962     // xtype created footer. - not sure if will work as we normally have to render first..
58963     if (this.footer && !this.footer.el && this.footer.xtype) {
58964         if (!this.wrapEl) {
58965             this.wrapEl = this.el.wrap();
58966         }
58967     
58968         this.footer.container = this.wrapEl.createChild();
58969          
58970         this.footer = Roo.factory(this.footer, Roo);
58971         
58972     }
58973     
58974     if(this.resizeEl){
58975         this.resizeEl = Roo.get(this.resizeEl, true);
58976     }else{
58977         this.resizeEl = this.el;
58978     }
58979     // handle view.xtype
58980     
58981  
58982     
58983     
58984     this.addEvents({
58985         /**
58986          * @event activate
58987          * Fires when this panel is activated. 
58988          * @param {Roo.ContentPanel} this
58989          */
58990         "activate" : true,
58991         /**
58992          * @event deactivate
58993          * Fires when this panel is activated. 
58994          * @param {Roo.ContentPanel} this
58995          */
58996         "deactivate" : true,
58997
58998         /**
58999          * @event resize
59000          * Fires when this panel is resized if fitToFrame is true.
59001          * @param {Roo.ContentPanel} this
59002          * @param {Number} width The width after any component adjustments
59003          * @param {Number} height The height after any component adjustments
59004          */
59005         "resize" : true,
59006         
59007          /**
59008          * @event render
59009          * Fires when this tab is created
59010          * @param {Roo.ContentPanel} this
59011          */
59012         "render" : true
59013          
59014         
59015     });
59016     
59017
59018     
59019     
59020     if(this.autoScroll){
59021         this.resizeEl.setStyle("overflow", "auto");
59022     } else {
59023         // fix randome scrolling
59024         this.el.on('scroll', function() {
59025             Roo.log('fix random scolling');
59026             this.scrollTo('top',0); 
59027         });
59028     }
59029     content = content || this.content;
59030     if(content){
59031         this.setContent(content);
59032     }
59033     if(config && config.url){
59034         this.setUrl(this.url, this.params, this.loadOnce);
59035     }
59036     
59037     
59038     
59039     Roo.ContentPanel.superclass.constructor.call(this);
59040     
59041     if (this.view && typeof(this.view.xtype) != 'undefined') {
59042         this.view.el = this.el.appendChild(document.createElement("div"));
59043         this.view = Roo.factory(this.view); 
59044         this.view.render  &&  this.view.render(false, '');  
59045     }
59046     
59047     
59048     this.fireEvent('render', this);
59049 };
59050
59051 Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
59052     tabTip:'',
59053     setRegion : function(region){
59054         this.region = region;
59055         if(region){
59056            this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
59057         }else{
59058            this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
59059         } 
59060     },
59061     
59062     /**
59063      * Returns the toolbar for this Panel if one was configured. 
59064      * @return {Roo.Toolbar} 
59065      */
59066     getToolbar : function(){
59067         return this.toolbar;
59068     },
59069     
59070     setActiveState : function(active){
59071         this.active = active;
59072         if(!active){
59073             this.fireEvent("deactivate", this);
59074         }else{
59075             this.fireEvent("activate", this);
59076         }
59077     },
59078     /**
59079      * Updates this panel's element
59080      * @param {String} content The new content
59081      * @param {Boolean} loadScripts (optional) true to look for and process scripts
59082     */
59083     setContent : function(content, loadScripts){
59084         this.el.update(content, loadScripts);
59085     },
59086
59087     ignoreResize : function(w, h){
59088         if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
59089             return true;
59090         }else{
59091             this.lastSize = {width: w, height: h};
59092             return false;
59093         }
59094     },
59095     /**
59096      * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
59097      * @return {Roo.UpdateManager} The UpdateManager
59098      */
59099     getUpdateManager : function(){
59100         return this.el.getUpdateManager();
59101     },
59102      /**
59103      * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
59104      * @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:
59105 <pre><code>
59106 panel.load({
59107     url: "your-url.php",
59108     params: {param1: "foo", param2: "bar"}, // or a URL encoded string
59109     callback: yourFunction,
59110     scope: yourObject, //(optional scope)
59111     discardUrl: false,
59112     nocache: false,
59113     text: "Loading...",
59114     timeout: 30,
59115     scripts: false
59116 });
59117 </code></pre>
59118      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
59119      * are shorthand for <i>disableCaching</i>, <i>indicatorText</i> and <i>loadScripts</i> and are used to set their associated property on this panel UpdateManager instance.
59120      * @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}
59121      * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
59122      * @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.
59123      * @return {Roo.ContentPanel} this
59124      */
59125     load : function(){
59126         var um = this.el.getUpdateManager();
59127         um.update.apply(um, arguments);
59128         return this;
59129     },
59130
59131
59132     /**
59133      * Set a URL to be used to load the content for this panel. When this panel is activated, the content will be loaded from that URL.
59134      * @param {String/Function} url The URL to load the content from or a function to call to get the URL
59135      * @param {String/Object} params (optional) The string params for the update call or an object of the params. See {@link Roo.UpdateManager#update} for more details. (Defaults to null)
59136      * @param {Boolean} loadOnce (optional) Whether to only load the content once. If this is false it makes the Ajax call every time this panel is activated. (Defaults to false)
59137      * @return {Roo.UpdateManager} The UpdateManager
59138      */
59139     setUrl : function(url, params, loadOnce){
59140         if(this.refreshDelegate){
59141             this.removeListener("activate", this.refreshDelegate);
59142         }
59143         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
59144         this.on("activate", this.refreshDelegate);
59145         return this.el.getUpdateManager();
59146     },
59147     
59148     _handleRefresh : function(url, params, loadOnce){
59149         if(!loadOnce || !this.loaded){
59150             var updater = this.el.getUpdateManager();
59151             updater.update(url, params, this._setLoaded.createDelegate(this));
59152         }
59153     },
59154     
59155     _setLoaded : function(){
59156         this.loaded = true;
59157     }, 
59158     
59159     /**
59160      * Returns this panel's id
59161      * @return {String} 
59162      */
59163     getId : function(){
59164         return this.el.id;
59165     },
59166     
59167     /** 
59168      * Returns this panel's element - used by regiosn to add.
59169      * @return {Roo.Element} 
59170      */
59171     getEl : function(){
59172         return this.wrapEl || this.el;
59173     },
59174     
59175     adjustForComponents : function(width, height)
59176     {
59177         //Roo.log('adjustForComponents ');
59178         if(this.resizeEl != this.el){
59179             width -= this.el.getFrameWidth('lr');
59180             height -= this.el.getFrameWidth('tb');
59181         }
59182         if(this.toolbar){
59183             var te = this.toolbar.getEl();
59184             height -= te.getHeight();
59185             te.setWidth(width);
59186         }
59187         if(this.footer){
59188             var te = this.footer.getEl();
59189             //Roo.log("footer:" + te.getHeight());
59190             
59191             height -= te.getHeight();
59192             te.setWidth(width);
59193         }
59194         
59195         
59196         if(this.adjustments){
59197             width += this.adjustments[0];
59198             height += this.adjustments[1];
59199         }
59200         return {"width": width, "height": height};
59201     },
59202     
59203     setSize : function(width, height){
59204         if(this.fitToFrame && !this.ignoreResize(width, height)){
59205             if(this.fitContainer && this.resizeEl != this.el){
59206                 this.el.setSize(width, height);
59207             }
59208             var size = this.adjustForComponents(width, height);
59209             this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
59210             this.fireEvent('resize', this, size.width, size.height);
59211         }
59212     },
59213     
59214     /**
59215      * Returns this panel's title
59216      * @return {String} 
59217      */
59218     getTitle : function(){
59219         return this.title;
59220     },
59221     
59222     /**
59223      * Set this panel's title
59224      * @param {String} title
59225      */
59226     setTitle : function(title){
59227         this.title = title;
59228         if(this.region){
59229             this.region.updatePanelTitle(this, title);
59230         }
59231     },
59232     
59233     /**
59234      * Returns true is this panel was configured to be closable
59235      * @return {Boolean} 
59236      */
59237     isClosable : function(){
59238         return this.closable;
59239     },
59240     
59241     beforeSlide : function(){
59242         this.el.clip();
59243         this.resizeEl.clip();
59244     },
59245     
59246     afterSlide : function(){
59247         this.el.unclip();
59248         this.resizeEl.unclip();
59249     },
59250     
59251     /**
59252      *   Force a content refresh from the URL specified in the {@link #setUrl} method.
59253      *   Will fail silently if the {@link #setUrl} method has not been called.
59254      *   This does not activate the panel, just updates its content.
59255      */
59256     refresh : function(){
59257         if(this.refreshDelegate){
59258            this.loaded = false;
59259            this.refreshDelegate();
59260         }
59261     },
59262     
59263     /**
59264      * Destroys this panel
59265      */
59266     destroy : function(){
59267         this.el.removeAllListeners();
59268         var tempEl = document.createElement("span");
59269         tempEl.appendChild(this.el.dom);
59270         tempEl.innerHTML = "";
59271         this.el.remove();
59272         this.el = null;
59273     },
59274     
59275     /**
59276      * form - if the content panel contains a form - this is a reference to it.
59277      * @type {Roo.form.Form}
59278      */
59279     form : false,
59280     /**
59281      * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
59282      *    This contains a reference to it.
59283      * @type {Roo.View}
59284      */
59285     view : false,
59286     
59287       /**
59288      * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
59289      * <pre><code>
59290
59291 layout.addxtype({
59292        xtype : 'Form',
59293        items: [ .... ]
59294    }
59295 );
59296
59297 </code></pre>
59298      * @param {Object} cfg Xtype definition of item to add.
59299      */
59300     
59301     addxtype : function(cfg) {
59302         // add form..
59303         if (cfg.xtype.match(/^Form$/)) {
59304             
59305             var el;
59306             //if (this.footer) {
59307             //    el = this.footer.container.insertSibling(false, 'before');
59308             //} else {
59309                 el = this.el.createChild();
59310             //}
59311
59312             this.form = new  Roo.form.Form(cfg);
59313             
59314             
59315             if ( this.form.allItems.length) {
59316                 this.form.render(el.dom);
59317             }
59318             return this.form;
59319         }
59320         // should only have one of theses..
59321         if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
59322             // views.. should not be just added - used named prop 'view''
59323             
59324             cfg.el = this.el.appendChild(document.createElement("div"));
59325             // factory?
59326             
59327             var ret = new Roo.factory(cfg);
59328              
59329              ret.render && ret.render(false, ''); // render blank..
59330             this.view = ret;
59331             return ret;
59332         }
59333         return false;
59334     }
59335 });
59336
59337 /**
59338  * @class Roo.GridPanel
59339  * @extends Roo.ContentPanel
59340  * @parent Roo.BorderLayout Roo.LayoutDialog builder
59341  * @constructor
59342  * Create a new GridPanel.
59343  * @cfg {Roo.grid.Grid} grid The grid for this panel
59344  */
59345 Roo.GridPanel = function(grid, config){
59346     
59347     // universal ctor...
59348     if (typeof(grid.grid) != 'undefined') {
59349         config = grid;
59350         grid = config.grid;
59351     }
59352     this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
59353         {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
59354         
59355     this.wrapper.dom.appendChild(grid.getGridEl().dom);
59356     
59357     Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
59358     
59359     if(this.toolbar){
59360         this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
59361     }
59362     // xtype created footer. - not sure if will work as we normally have to render first..
59363     if (this.footer && !this.footer.el && this.footer.xtype) {
59364         
59365         this.footer.container = this.grid.getView().getFooterPanel(true);
59366         this.footer.dataSource = this.grid.dataSource;
59367         this.footer = Roo.factory(this.footer, Roo);
59368         
59369     }
59370     
59371     grid.monitorWindowResize = false; // turn off autosizing
59372     grid.autoHeight = false;
59373     grid.autoWidth = false;
59374     this.grid = grid;
59375     this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
59376 };
59377
59378 Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
59379     getId : function(){
59380         return this.grid.id;
59381     },
59382     
59383     /**
59384      * Returns the grid for this panel
59385      * @return {Roo.grid.Grid} 
59386      */
59387     getGrid : function(){
59388         return this.grid;    
59389     },
59390     
59391     setSize : function(width, height){
59392         if(!this.ignoreResize(width, height)){
59393             var grid = this.grid;
59394             var size = this.adjustForComponents(width, height);
59395             grid.getGridEl().setSize(size.width, size.height);
59396             grid.autoSize();
59397         }
59398     },
59399     
59400     beforeSlide : function(){
59401         this.grid.getView().scroller.clip();
59402     },
59403     
59404     afterSlide : function(){
59405         this.grid.getView().scroller.unclip();
59406     },
59407     
59408     destroy : function(){
59409         this.grid.destroy();
59410         delete this.grid;
59411         Roo.GridPanel.superclass.destroy.call(this); 
59412     }
59413 });
59414
59415
59416 /**
59417  * @class Roo.NestedLayoutPanel
59418  * @extends Roo.ContentPanel
59419  * @parent Roo.BorderLayout Roo.LayoutDialog builder
59420  * @cfg Roo.BorderLayout} layout   [required] The layout for this panel
59421  *
59422  * 
59423  * @constructor
59424  * Create a new NestedLayoutPanel.
59425  * 
59426  * 
59427  * @param {Roo.BorderLayout} layout [required] The layout for this panel
59428  * @param {String/Object} config A string to set only the title or a config object
59429  */
59430 Roo.NestedLayoutPanel = function(layout, config)
59431 {
59432     // construct with only one argument..
59433     /* FIXME - implement nicer consturctors
59434     if (layout.layout) {
59435         config = layout;
59436         layout = config.layout;
59437         delete config.layout;
59438     }
59439     if (layout.xtype && !layout.getEl) {
59440         // then layout needs constructing..
59441         layout = Roo.factory(layout, Roo);
59442     }
59443     */
59444     
59445     
59446     Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
59447     
59448     layout.monitorWindowResize = false; // turn off autosizing
59449     this.layout = layout;
59450     this.layout.getEl().addClass("x-layout-nested-layout");
59451     
59452     
59453     
59454     
59455 };
59456
59457 Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
59458
59459     setSize : function(width, height){
59460         if(!this.ignoreResize(width, height)){
59461             var size = this.adjustForComponents(width, height);
59462             var el = this.layout.getEl();
59463             el.setSize(size.width, size.height);
59464             var touch = el.dom.offsetWidth;
59465             this.layout.layout();
59466             // ie requires a double layout on the first pass
59467             if(Roo.isIE && !this.initialized){
59468                 this.initialized = true;
59469                 this.layout.layout();
59470             }
59471         }
59472     },
59473     
59474     // activate all subpanels if not currently active..
59475     
59476     setActiveState : function(active){
59477         this.active = active;
59478         if(!active){
59479             this.fireEvent("deactivate", this);
59480             return;
59481         }
59482         
59483         this.fireEvent("activate", this);
59484         // not sure if this should happen before or after..
59485         if (!this.layout) {
59486             return; // should not happen..
59487         }
59488         var reg = false;
59489         for (var r in this.layout.regions) {
59490             reg = this.layout.getRegion(r);
59491             if (reg.getActivePanel()) {
59492                 //reg.showPanel(reg.getActivePanel()); // force it to activate.. 
59493                 reg.setActivePanel(reg.getActivePanel());
59494                 continue;
59495             }
59496             if (!reg.panels.length) {
59497                 continue;
59498             }
59499             reg.showPanel(reg.getPanel(0));
59500         }
59501         
59502         
59503         
59504         
59505     },
59506     
59507     /**
59508      * Returns the nested BorderLayout for this panel
59509      * @return {Roo.BorderLayout} 
59510      */
59511     getLayout : function(){
59512         return this.layout;
59513     },
59514     
59515      /**
59516      * Adds a xtype elements to the layout of the nested panel
59517      * <pre><code>
59518
59519 panel.addxtype({
59520        xtype : 'ContentPanel',
59521        region: 'west',
59522        items: [ .... ]
59523    }
59524 );
59525
59526 panel.addxtype({
59527         xtype : 'NestedLayoutPanel',
59528         region: 'west',
59529         layout: {
59530            center: { },
59531            west: { }   
59532         },
59533         items : [ ... list of content panels or nested layout panels.. ]
59534    }
59535 );
59536 </code></pre>
59537      * @param {Object} cfg Xtype definition of item to add.
59538      */
59539     addxtype : function(cfg) {
59540         return this.layout.addxtype(cfg);
59541     
59542     }
59543 });
59544
59545 Roo.ScrollPanel = function(el, config, content){
59546     config = config || {};
59547     config.fitToFrame = true;
59548     Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
59549     
59550     this.el.dom.style.overflow = "hidden";
59551     var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
59552     this.el.removeClass("x-layout-inactive-content");
59553     this.el.on("mousewheel", this.onWheel, this);
59554
59555     var up = wrap.createChild({cls: "x-scroller-up", html: "&#160;"}, this.el.dom);
59556     var down = wrap.createChild({cls: "x-scroller-down", html: "&#160;"});
59557     up.unselectable(); down.unselectable();
59558     up.on("click", this.scrollUp, this);
59559     down.on("click", this.scrollDown, this);
59560     up.addClassOnOver("x-scroller-btn-over");
59561     down.addClassOnOver("x-scroller-btn-over");
59562     up.addClassOnClick("x-scroller-btn-click");
59563     down.addClassOnClick("x-scroller-btn-click");
59564     this.adjustments = [0, -(up.getHeight() + down.getHeight())];
59565
59566     this.resizeEl = this.el;
59567     this.el = wrap; this.up = up; this.down = down;
59568 };
59569
59570 Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
59571     increment : 100,
59572     wheelIncrement : 5,
59573     scrollUp : function(){
59574         this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
59575     },
59576
59577     scrollDown : function(){
59578         this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
59579     },
59580
59581     afterScroll : function(){
59582         var el = this.resizeEl;
59583         var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
59584         this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
59585         this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
59586     },
59587
59588     setSize : function(){
59589         Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
59590         this.afterScroll();
59591     },
59592
59593     onWheel : function(e){
59594         var d = e.getWheelDelta();
59595         this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
59596         this.afterScroll();
59597         e.stopEvent();
59598     },
59599
59600     setContent : function(content, loadScripts){
59601         this.resizeEl.update(content, loadScripts);
59602     }
59603
59604 });
59605
59606
59607
59608 /**
59609  * @class Roo.TreePanel
59610  * @extends Roo.ContentPanel
59611  * @parent Roo.BorderLayout Roo.LayoutDialog builder
59612  * Treepanel component
59613  * 
59614  * @constructor
59615  * Create a new TreePanel. - defaults to fit/scoll contents.
59616  * @param {String/Object} config A string to set only the panel's title, or a config object
59617  */
59618 Roo.TreePanel = function(config){
59619     var el = config.el;
59620     var tree = config.tree;
59621     delete config.tree; 
59622     delete config.el; // hopefull!
59623     
59624     // wrapper for IE7 strict & safari scroll issue
59625     
59626     var treeEl = el.createChild();
59627     config.resizeEl = treeEl;
59628     
59629     
59630     
59631     Roo.TreePanel.superclass.constructor.call(this, el, config);
59632  
59633  
59634     this.tree = new Roo.tree.TreePanel(treeEl , tree);
59635     //console.log(tree);
59636     this.on('activate', function()
59637     {
59638         if (this.tree.rendered) {
59639             return;
59640         }
59641         //console.log('render tree');
59642         this.tree.render();
59643     });
59644     // this should not be needed.. - it's actually the 'el' that resizes?
59645     // actuall it breaks the containerScroll - dragging nodes auto scroll at top
59646     
59647     //this.on('resize',  function (cp, w, h) {
59648     //        this.tree.innerCt.setWidth(w);
59649     //        this.tree.innerCt.setHeight(h);
59650     //        //this.tree.innerCt.setStyle('overflow-y', 'auto');
59651     //});
59652
59653         
59654     
59655 };
59656
59657 Roo.extend(Roo.TreePanel, Roo.ContentPanel, {   
59658     fitToFrame : true,
59659     autoScroll : true,
59660     /*
59661      * @cfg {Roo.tree.TreePanel} tree [required] The tree TreePanel, with config etc.
59662      */
59663     tree : false
59664
59665 });
59666
59667
59668
59669
59670
59671
59672
59673
59674
59675
59676
59677 /*
59678  * Based on:
59679  * Ext JS Library 1.1.1
59680  * Copyright(c) 2006-2007, Ext JS, LLC.
59681  *
59682  * Originally Released Under LGPL - original licence link has changed is not relivant.
59683  *
59684  * Fork - LGPL
59685  * <script type="text/javascript">
59686  */
59687  
59688
59689 /**
59690  * @class Roo.ReaderLayout
59691  * @extends Roo.BorderLayout
59692  * This is a pre-built layout that represents a classic, 5-pane application.  It consists of a header, a primary
59693  * center region containing two nested regions (a top one for a list view and one for item preview below),
59694  * and regions on either side that can be used for navigation, application commands, informational displays, etc.
59695  * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
59696  * expedites the setup of the overall layout and regions for this common application style.
59697  * Example:
59698  <pre><code>
59699 var reader = new Roo.ReaderLayout();
59700 var CP = Roo.ContentPanel;  // shortcut for adding
59701
59702 reader.beginUpdate();
59703 reader.add("north", new CP("north", "North"));
59704 reader.add("west", new CP("west", {title: "West"}));
59705 reader.add("east", new CP("east", {title: "East"}));
59706
59707 reader.regions.listView.add(new CP("listView", "List"));
59708 reader.regions.preview.add(new CP("preview", "Preview"));
59709 reader.endUpdate();
59710 </code></pre>
59711 * @constructor
59712 * Create a new ReaderLayout
59713 * @param {Object} config Configuration options
59714 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
59715 * document.body if omitted)
59716 */
59717 Roo.ReaderLayout = function(config, renderTo){
59718     var c = config || {size:{}};
59719     Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
59720         north: c.north !== false ? Roo.apply({
59721             split:false,
59722             initialSize: 32,
59723             titlebar: false
59724         }, c.north) : false,
59725         west: c.west !== false ? Roo.apply({
59726             split:true,
59727             initialSize: 200,
59728             minSize: 175,
59729             maxSize: 400,
59730             titlebar: true,
59731             collapsible: true,
59732             animate: true,
59733             margins:{left:5,right:0,bottom:5,top:5},
59734             cmargins:{left:5,right:5,bottom:5,top:5}
59735         }, c.west) : false,
59736         east: c.east !== false ? Roo.apply({
59737             split:true,
59738             initialSize: 200,
59739             minSize: 175,
59740             maxSize: 400,
59741             titlebar: true,
59742             collapsible: true,
59743             animate: true,
59744             margins:{left:0,right:5,bottom:5,top:5},
59745             cmargins:{left:5,right:5,bottom:5,top:5}
59746         }, c.east) : false,
59747         center: Roo.apply({
59748             tabPosition: 'top',
59749             autoScroll:false,
59750             closeOnTab: true,
59751             titlebar:false,
59752             margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
59753         }, c.center)
59754     });
59755
59756     this.el.addClass('x-reader');
59757
59758     this.beginUpdate();
59759
59760     var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
59761         south: c.preview !== false ? Roo.apply({
59762             split:true,
59763             initialSize: 200,
59764             minSize: 100,
59765             autoScroll:true,
59766             collapsible:true,
59767             titlebar: true,
59768             cmargins:{top:5,left:0, right:0, bottom:0}
59769         }, c.preview) : false,
59770         center: Roo.apply({
59771             autoScroll:false,
59772             titlebar:false,
59773             minHeight:200
59774         }, c.listView)
59775     });
59776     this.add('center', new Roo.NestedLayoutPanel(inner,
59777             Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
59778
59779     this.endUpdate();
59780
59781     this.regions.preview = inner.getRegion('south');
59782     this.regions.listView = inner.getRegion('center');
59783 };
59784
59785 Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
59786  * Based on:
59787  * Ext JS Library 1.1.1
59788  * Copyright(c) 2006-2007, Ext JS, LLC.
59789  *
59790  * Originally Released Under LGPL - original licence link has changed is not relivant.
59791  *
59792  * Fork - LGPL
59793  * <script type="text/javascript">
59794  */
59795  
59796 /**
59797  * @class Roo.grid.Grid
59798  * @extends Roo.util.Observable
59799  * This class represents the primary interface of a component based grid control.
59800  * <br><br>Usage:<pre><code>
59801  var grid = new Roo.grid.Grid("my-container-id", {
59802      ds: myDataStore,
59803      cm: myColModel,
59804      selModel: mySelectionModel,
59805      autoSizeColumns: true,
59806      monitorWindowResize: false,
59807      trackMouseOver: true
59808  });
59809  // set any options
59810  grid.render();
59811  * </code></pre>
59812  * <b>Common Problems:</b><br/>
59813  * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
59814  * element will correct this<br/>
59815  * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
59816  * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
59817  * are unpredictable.<br/>
59818  * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
59819  * grid to calculate dimensions/offsets.<br/>
59820   * @constructor
59821  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
59822  * The container MUST have some type of size defined for the grid to fill. The container will be
59823  * automatically set to position relative if it isn't already.
59824  * @param {Object} config A config object that sets properties on this grid.
59825  */
59826 Roo.grid.Grid = function(container, config){
59827         // initialize the container
59828         this.container = Roo.get(container);
59829         this.container.update("");
59830         this.container.setStyle("overflow", "hidden");
59831     this.container.addClass('x-grid-container');
59832
59833     this.id = this.container.id;
59834
59835     Roo.apply(this, config);
59836     // check and correct shorthanded configs
59837     if(this.ds){
59838         this.dataSource = this.ds;
59839         delete this.ds;
59840     }
59841     if(this.cm){
59842         this.colModel = this.cm;
59843         delete this.cm;
59844     }
59845     if(this.sm){
59846         this.selModel = this.sm;
59847         delete this.sm;
59848     }
59849
59850     if (this.selModel) {
59851         this.selModel = Roo.factory(this.selModel, Roo.grid);
59852         this.sm = this.selModel;
59853         this.sm.xmodule = this.xmodule || false;
59854     }
59855     if (typeof(this.colModel.config) == 'undefined') {
59856         this.colModel = new Roo.grid.ColumnModel(this.colModel);
59857         this.cm = this.colModel;
59858         this.cm.xmodule = this.xmodule || false;
59859     }
59860     if (this.dataSource) {
59861         this.dataSource= Roo.factory(this.dataSource, Roo.data);
59862         this.ds = this.dataSource;
59863         this.ds.xmodule = this.xmodule || false;
59864          
59865     }
59866     
59867     
59868     
59869     if(this.width){
59870         this.container.setWidth(this.width);
59871     }
59872
59873     if(this.height){
59874         this.container.setHeight(this.height);
59875     }
59876     /** @private */
59877         this.addEvents({
59878         // raw events
59879         /**
59880          * @event click
59881          * The raw click event for the entire grid.
59882          * @param {Roo.EventObject} e
59883          */
59884         "click" : true,
59885         /**
59886          * @event dblclick
59887          * The raw dblclick event for the entire grid.
59888          * @param {Roo.EventObject} e
59889          */
59890         "dblclick" : true,
59891         /**
59892          * @event contextmenu
59893          * The raw contextmenu event for the entire grid.
59894          * @param {Roo.EventObject} e
59895          */
59896         "contextmenu" : true,
59897         /**
59898          * @event mousedown
59899          * The raw mousedown event for the entire grid.
59900          * @param {Roo.EventObject} e
59901          */
59902         "mousedown" : true,
59903         /**
59904          * @event mouseup
59905          * The raw mouseup event for the entire grid.
59906          * @param {Roo.EventObject} e
59907          */
59908         "mouseup" : true,
59909         /**
59910          * @event mouseover
59911          * The raw mouseover event for the entire grid.
59912          * @param {Roo.EventObject} e
59913          */
59914         "mouseover" : true,
59915         /**
59916          * @event mouseout
59917          * The raw mouseout event for the entire grid.
59918          * @param {Roo.EventObject} e
59919          */
59920         "mouseout" : true,
59921         /**
59922          * @event keypress
59923          * The raw keypress event for the entire grid.
59924          * @param {Roo.EventObject} e
59925          */
59926         "keypress" : true,
59927         /**
59928          * @event keydown
59929          * The raw keydown event for the entire grid.
59930          * @param {Roo.EventObject} e
59931          */
59932         "keydown" : true,
59933
59934         // custom events
59935
59936         /**
59937          * @event cellclick
59938          * Fires when a cell is clicked
59939          * @param {Grid} this
59940          * @param {Number} rowIndex
59941          * @param {Number} columnIndex
59942          * @param {Roo.EventObject} e
59943          */
59944         "cellclick" : true,
59945         /**
59946          * @event celldblclick
59947          * Fires when a cell is double clicked
59948          * @param {Grid} this
59949          * @param {Number} rowIndex
59950          * @param {Number} columnIndex
59951          * @param {Roo.EventObject} e
59952          */
59953         "celldblclick" : true,
59954         /**
59955          * @event rowclick
59956          * Fires when a row is clicked
59957          * @param {Grid} this
59958          * @param {Number} rowIndex
59959          * @param {Roo.EventObject} e
59960          */
59961         "rowclick" : true,
59962         /**
59963          * @event rowdblclick
59964          * Fires when a row is double clicked
59965          * @param {Grid} this
59966          * @param {Number} rowIndex
59967          * @param {Roo.EventObject} e
59968          */
59969         "rowdblclick" : true,
59970         /**
59971          * @event headerclick
59972          * Fires when a header is clicked
59973          * @param {Grid} this
59974          * @param {Number} columnIndex
59975          * @param {Roo.EventObject} e
59976          */
59977         "headerclick" : true,
59978         /**
59979          * @event headerdblclick
59980          * Fires when a header cell is double clicked
59981          * @param {Grid} this
59982          * @param {Number} columnIndex
59983          * @param {Roo.EventObject} e
59984          */
59985         "headerdblclick" : true,
59986         /**
59987          * @event rowcontextmenu
59988          * Fires when a row is right clicked
59989          * @param {Grid} this
59990          * @param {Number} rowIndex
59991          * @param {Roo.EventObject} e
59992          */
59993         "rowcontextmenu" : true,
59994         /**
59995          * @event cellcontextmenu
59996          * Fires when a cell is right clicked
59997          * @param {Grid} this
59998          * @param {Number} rowIndex
59999          * @param {Number} cellIndex
60000          * @param {Roo.EventObject} e
60001          */
60002          "cellcontextmenu" : true,
60003         /**
60004          * @event headercontextmenu
60005          * Fires when a header is right clicked
60006          * @param {Grid} this
60007          * @param {Number} columnIndex
60008          * @param {Roo.EventObject} e
60009          */
60010         "headercontextmenu" : true,
60011         /**
60012          * @event bodyscroll
60013          * Fires when the body element is scrolled
60014          * @param {Number} scrollLeft
60015          * @param {Number} scrollTop
60016          */
60017         "bodyscroll" : true,
60018         /**
60019          * @event columnresize
60020          * Fires when the user resizes a column
60021          * @param {Number} columnIndex
60022          * @param {Number} newSize
60023          */
60024         "columnresize" : true,
60025         /**
60026          * @event columnmove
60027          * Fires when the user moves a column
60028          * @param {Number} oldIndex
60029          * @param {Number} newIndex
60030          */
60031         "columnmove" : true,
60032         /**
60033          * @event startdrag
60034          * Fires when row(s) start being dragged
60035          * @param {Grid} this
60036          * @param {Roo.GridDD} dd The drag drop object
60037          * @param {event} e The raw browser event
60038          */
60039         "startdrag" : true,
60040         /**
60041          * @event enddrag
60042          * Fires when a drag operation is complete
60043          * @param {Grid} this
60044          * @param {Roo.GridDD} dd The drag drop object
60045          * @param {event} e The raw browser event
60046          */
60047         "enddrag" : true,
60048         /**
60049          * @event dragdrop
60050          * Fires when dragged row(s) are dropped on a valid DD target
60051          * @param {Grid} this
60052          * @param {Roo.GridDD} dd The drag drop object
60053          * @param {String} targetId The target drag drop object
60054          * @param {event} e The raw browser event
60055          */
60056         "dragdrop" : true,
60057         /**
60058          * @event dragover
60059          * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
60060          * @param {Grid} this
60061          * @param {Roo.GridDD} dd The drag drop object
60062          * @param {String} targetId The target drag drop object
60063          * @param {event} e The raw browser event
60064          */
60065         "dragover" : true,
60066         /**
60067          * @event dragenter
60068          *  Fires when the dragged row(s) first cross another DD target while being dragged
60069          * @param {Grid} this
60070          * @param {Roo.GridDD} dd The drag drop object
60071          * @param {String} targetId The target drag drop object
60072          * @param {event} e The raw browser event
60073          */
60074         "dragenter" : true,
60075         /**
60076          * @event dragout
60077          * Fires when the dragged row(s) leave another DD target while being dragged
60078          * @param {Grid} this
60079          * @param {Roo.GridDD} dd The drag drop object
60080          * @param {String} targetId The target drag drop object
60081          * @param {event} e The raw browser event
60082          */
60083         "dragout" : true,
60084         /**
60085          * @event rowclass
60086          * Fires when a row is rendered, so you can change add a style to it.
60087          * @param {GridView} gridview   The grid view
60088          * @param {Object} rowcfg   contains record  rowIndex and rowClass - set rowClass to add a style.
60089          */
60090         'rowclass' : true,
60091
60092         /**
60093          * @event render
60094          * Fires when the grid is rendered
60095          * @param {Grid} grid
60096          */
60097         'render' : true
60098     });
60099
60100     Roo.grid.Grid.superclass.constructor.call(this);
60101 };
60102 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
60103     
60104     /**
60105          * @cfg {Roo.grid.AbstractSelectionModel} sm The selection Model (default = Roo.grid.RowSelectionModel)
60106          */
60107         /**
60108          * @cfg {Roo.grid.GridView} view  The view that renders the grid (default = Roo.grid.GridView)
60109          */
60110         /**
60111          * @cfg {Roo.grid.ColumnModel} cm[] The columns of the grid
60112          */
60113         /**
60114          * @cfg {Roo.grid.Store} ds The data store for the grid
60115          */
60116         /**
60117          * @cfg {Roo.Toolbar} toolbar a toolbar for buttons etc.
60118          */
60119         /**
60120      * @cfg {String} ddGroup - drag drop group.
60121      */
60122       /**
60123      * @cfg {String} dragGroup - drag group (?? not sure if needed.)
60124      */
60125
60126     /**
60127      * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
60128      */
60129     minColumnWidth : 25,
60130
60131     /**
60132      * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
60133      * <b>on initial render.</b> It is more efficient to explicitly size the columns
60134      * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option.  Default is false.
60135      */
60136     autoSizeColumns : false,
60137
60138     /**
60139      * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
60140      */
60141     autoSizeHeaders : true,
60142
60143     /**
60144      * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
60145      */
60146     monitorWindowResize : true,
60147
60148     /**
60149      * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
60150      * rows measured to get a columns size. Default is 0 (all rows).
60151      */
60152     maxRowsToMeasure : 0,
60153
60154     /**
60155      * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
60156      */
60157     trackMouseOver : true,
60158
60159     /**
60160     * @cfg {Boolean} enableDrag  True to enable drag of rows. Default is false. (double check if this is needed?)
60161     */
60162       /**
60163     * @cfg {Boolean} enableDrop  True to enable drop of elements. Default is false. (double check if this is needed?)
60164     */
60165     
60166     /**
60167     * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
60168     */
60169     enableDragDrop : false,
60170     
60171     /**
60172     * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
60173     */
60174     enableColumnMove : true,
60175     
60176     /**
60177     * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
60178     */
60179     enableColumnHide : true,
60180     
60181     /**
60182     * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
60183     */
60184     enableRowHeightSync : false,
60185     
60186     /**
60187     * @cfg {Boolean} stripeRows True to stripe the rows.  Default is true.
60188     */
60189     stripeRows : true,
60190     
60191     /**
60192     * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
60193     */
60194     autoHeight : false,
60195
60196     /**
60197      * @cfg {String} autoExpandColumn The id (or dataIndex) of a column in this grid that should expand to fill unused space. This id can not be 0. Default is false.
60198      */
60199     autoExpandColumn : false,
60200
60201     /**
60202     * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
60203     * Default is 50.
60204     */
60205     autoExpandMin : 50,
60206
60207     /**
60208     * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
60209     */
60210     autoExpandMax : 1000,
60211
60212     /**
60213     * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
60214     */
60215     view : null,
60216
60217     /**
60218     * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
60219     */
60220     loadMask : false,
60221     /**
60222     * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
60223     */
60224     dropTarget: false,
60225      /**
60226     * @cfg {boolean} sortColMenu Sort the column order menu when it shows (usefull for long lists..) default false
60227     */ 
60228     sortColMenu : false,
60229     
60230     // private
60231     rendered : false,
60232
60233     /**
60234     * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
60235     * of a fixed width. Default is false.
60236     */
60237     /**
60238     * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
60239     */
60240     
60241     
60242     /**
60243     * @cfg {String} ddText Configures the text is the drag proxy (defaults to "%0 selected row(s)").
60244     * %0 is replaced with the number of selected rows.
60245     */
60246     ddText : "{0} selected row{1}",
60247     
60248     
60249     /**
60250      * Called once after all setup has been completed and the grid is ready to be rendered.
60251      * @return {Roo.grid.Grid} this
60252      */
60253     render : function()
60254     {
60255         var c = this.container;
60256         // try to detect autoHeight/width mode
60257         if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
60258             this.autoHeight = true;
60259         }
60260         var view = this.getView();
60261         view.init(this);
60262
60263         c.on("click", this.onClick, this);
60264         c.on("dblclick", this.onDblClick, this);
60265         c.on("contextmenu", this.onContextMenu, this);
60266         c.on("keydown", this.onKeyDown, this);
60267         if (Roo.isTouch) {
60268             c.on("touchstart", this.onTouchStart, this);
60269         }
60270
60271         this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
60272
60273         this.getSelectionModel().init(this);
60274
60275         view.render();
60276
60277         if(this.loadMask){
60278             this.loadMask = new Roo.LoadMask(this.container,
60279                     Roo.apply({store:this.dataSource}, this.loadMask));
60280         }
60281         
60282         
60283         if (this.toolbar && this.toolbar.xtype) {
60284             this.toolbar.container = this.getView().getHeaderPanel(true);
60285             this.toolbar = new Roo.Toolbar(this.toolbar);
60286         }
60287         if (this.footer && this.footer.xtype) {
60288             this.footer.dataSource = this.getDataSource();
60289             this.footer.container = this.getView().getFooterPanel(true);
60290             this.footer = Roo.factory(this.footer, Roo);
60291         }
60292         if (this.dropTarget && this.dropTarget.xtype) {
60293             delete this.dropTarget.xtype;
60294             this.dropTarget =  new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
60295         }
60296         
60297         
60298         this.rendered = true;
60299         this.fireEvent('render', this);
60300         return this;
60301     },
60302
60303     /**
60304      * Reconfigures the grid to use a different Store and Column Model.
60305      * The View will be bound to the new objects and refreshed.
60306      * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
60307      * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
60308      */
60309     reconfigure : function(dataSource, colModel){
60310         if(this.loadMask){
60311             this.loadMask.destroy();
60312             this.loadMask = new Roo.LoadMask(this.container,
60313                     Roo.apply({store:dataSource}, this.loadMask));
60314         }
60315         this.view.bind(dataSource, colModel);
60316         this.dataSource = dataSource;
60317         this.colModel = colModel;
60318         this.view.refresh(true);
60319     },
60320     /**
60321      * addColumns
60322      * Add's a column, default at the end..
60323      
60324      * @param {int} position to add (default end)
60325      * @param {Array} of objects of column configuration see {@link Roo.grid.ColumnModel} 
60326      */
60327     addColumns : function(pos, ar)
60328     {
60329         
60330         for (var i =0;i< ar.length;i++) {
60331             var cfg = ar[i];
60332             cfg.id = typeof(cfg.id) == 'undefined' ? Roo.id() : cfg.id; // don't normally use this..
60333             this.cm.lookup[cfg.id] = cfg;
60334         }
60335         
60336         
60337         if (typeof(pos) == 'undefined' || pos >= this.cm.config.length) {
60338             pos = this.cm.config.length; //this.cm.config.push(cfg);
60339         } 
60340         pos = Math.max(0,pos);
60341         ar.unshift(0);
60342         ar.unshift(pos);
60343         this.cm.config.splice.apply(this.cm.config, ar);
60344         
60345         
60346         
60347         this.view.generateRules(this.cm);
60348         this.view.refresh(true);
60349         
60350     },
60351     
60352     
60353     
60354     
60355     // private
60356     onKeyDown : function(e){
60357         this.fireEvent("keydown", e);
60358     },
60359
60360     /**
60361      * Destroy this grid.
60362      * @param {Boolean} removeEl True to remove the element
60363      */
60364     destroy : function(removeEl, keepListeners){
60365         if(this.loadMask){
60366             this.loadMask.destroy();
60367         }
60368         var c = this.container;
60369         c.removeAllListeners();
60370         this.view.destroy();
60371         this.colModel.purgeListeners();
60372         if(!keepListeners){
60373             this.purgeListeners();
60374         }
60375         c.update("");
60376         if(removeEl === true){
60377             c.remove();
60378         }
60379     },
60380
60381     // private
60382     processEvent : function(name, e){
60383         // does this fire select???
60384         //Roo.log('grid:processEvent '  + name);
60385         
60386         if (name != 'touchstart' ) {
60387             this.fireEvent(name, e);    
60388         }
60389         
60390         var t = e.getTarget();
60391         var v = this.view;
60392         var header = v.findHeaderIndex(t);
60393         if(header !== false){
60394             var ename = name == 'touchstart' ? 'click' : name;
60395              
60396             this.fireEvent("header" + ename, this, header, e);
60397         }else{
60398             var row = v.findRowIndex(t);
60399             var cell = v.findCellIndex(t);
60400             if (name == 'touchstart') {
60401                 // first touch is always a click.
60402                 // hopefull this happens after selection is updated.?
60403                 name = false;
60404                 
60405                 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
60406                     var cs = this.selModel.getSelectedCell();
60407                     if (row == cs[0] && cell == cs[1]){
60408                         name = 'dblclick';
60409                     }
60410                 }
60411                 if (typeof(this.selModel.getSelections) != 'undefined') {
60412                     var cs = this.selModel.getSelections();
60413                     var ds = this.dataSource;
60414                     if (cs.length == 1 && ds.getAt(row) == cs[0]){
60415                         name = 'dblclick';
60416                     }
60417                 }
60418                 if (!name) {
60419                     return;
60420                 }
60421             }
60422             
60423             
60424             if(row !== false){
60425                 this.fireEvent("row" + name, this, row, e);
60426                 if(cell !== false){
60427                     this.fireEvent("cell" + name, this, row, cell, e);
60428                 }
60429             }
60430         }
60431     },
60432
60433     // private
60434     onClick : function(e){
60435         this.processEvent("click", e);
60436     },
60437    // private
60438     onTouchStart : function(e){
60439         this.processEvent("touchstart", e);
60440     },
60441
60442     // private
60443     onContextMenu : function(e, t){
60444         this.processEvent("contextmenu", e);
60445     },
60446
60447     // private
60448     onDblClick : function(e){
60449         this.processEvent("dblclick", e);
60450     },
60451
60452     // private
60453     walkCells : function(row, col, step, fn, scope){
60454         var cm = this.colModel, clen = cm.getColumnCount();
60455         var ds = this.dataSource, rlen = ds.getCount(), first = true;
60456         if(step < 0){
60457             if(col < 0){
60458                 row--;
60459                 first = false;
60460             }
60461             while(row >= 0){
60462                 if(!first){
60463                     col = clen-1;
60464                 }
60465                 first = false;
60466                 while(col >= 0){
60467                     if(fn.call(scope || this, row, col, cm) === true){
60468                         return [row, col];
60469                     }
60470                     col--;
60471                 }
60472                 row--;
60473             }
60474         } else {
60475             if(col >= clen){
60476                 row++;
60477                 first = false;
60478             }
60479             while(row < rlen){
60480                 if(!first){
60481                     col = 0;
60482                 }
60483                 first = false;
60484                 while(col < clen){
60485                     if(fn.call(scope || this, row, col, cm) === true){
60486                         return [row, col];
60487                     }
60488                     col++;
60489                 }
60490                 row++;
60491             }
60492         }
60493         return null;
60494     },
60495
60496     // private
60497     getSelections : function(){
60498         return this.selModel.getSelections();
60499     },
60500
60501     /**
60502      * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
60503      * but if manual update is required this method will initiate it.
60504      */
60505     autoSize : function(){
60506         if(this.rendered){
60507             this.view.layout();
60508             if(this.view.adjustForScroll){
60509                 this.view.adjustForScroll();
60510             }
60511         }
60512     },
60513
60514     /**
60515      * Returns the grid's underlying element.
60516      * @return {Element} The element
60517      */
60518     getGridEl : function(){
60519         return this.container;
60520     },
60521
60522     // private for compatibility, overridden by editor grid
60523     stopEditing : function(){},
60524
60525     /**
60526      * Returns the grid's SelectionModel.
60527      * @return {SelectionModel}
60528      */
60529     getSelectionModel : function(){
60530         if(!this.selModel){
60531             this.selModel = new Roo.grid.RowSelectionModel();
60532         }
60533         return this.selModel;
60534     },
60535
60536     /**
60537      * Returns the grid's DataSource.
60538      * @return {DataSource}
60539      */
60540     getDataSource : function(){
60541         return this.dataSource;
60542     },
60543
60544     /**
60545      * Returns the grid's ColumnModel.
60546      * @return {ColumnModel}
60547      */
60548     getColumnModel : function(){
60549         return this.colModel;
60550     },
60551
60552     /**
60553      * Returns the grid's GridView object.
60554      * @return {GridView}
60555      */
60556     getView : function(){
60557         if(!this.view){
60558             this.view = new Roo.grid.GridView(this.viewConfig);
60559             this.relayEvents(this.view, [
60560                 "beforerowremoved", "beforerowsinserted",
60561                 "beforerefresh", "rowremoved",
60562                 "rowsinserted", "rowupdated" ,"refresh"
60563             ]);
60564         }
60565         return this.view;
60566     },
60567     /**
60568      * Called to get grid's drag proxy text, by default returns this.ddText.
60569      * Override this to put something different in the dragged text.
60570      * @return {String}
60571      */
60572     getDragDropText : function(){
60573         var count = this.selModel.getCount();
60574         return String.format(this.ddText, count, count == 1 ? '' : 's');
60575     }
60576 });
60577 /*
60578  * Based on:
60579  * Ext JS Library 1.1.1
60580  * Copyright(c) 2006-2007, Ext JS, LLC.
60581  *
60582  * Originally Released Under LGPL - original licence link has changed is not relivant.
60583  *
60584  * Fork - LGPL
60585  * <script type="text/javascript">
60586  */
60587  /**
60588  * @class Roo.grid.AbstractGridView
60589  * @extends Roo.util.Observable
60590  * @abstract
60591  * Abstract base class for grid Views
60592  * @constructor
60593  */
60594 Roo.grid.AbstractGridView = function(){
60595         this.grid = null;
60596         
60597         this.events = {
60598             "beforerowremoved" : true,
60599             "beforerowsinserted" : true,
60600             "beforerefresh" : true,
60601             "rowremoved" : true,
60602             "rowsinserted" : true,
60603             "rowupdated" : true,
60604             "refresh" : true
60605         };
60606     Roo.grid.AbstractGridView.superclass.constructor.call(this);
60607 };
60608
60609 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
60610     rowClass : "x-grid-row",
60611     cellClass : "x-grid-cell",
60612     tdClass : "x-grid-td",
60613     hdClass : "x-grid-hd",
60614     splitClass : "x-grid-hd-split",
60615     
60616     init: function(grid){
60617         this.grid = grid;
60618                 var cid = this.grid.getGridEl().id;
60619         this.colSelector = "#" + cid + " ." + this.cellClass + "-";
60620         this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
60621         this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
60622         this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
60623         },
60624         
60625     getColumnRenderers : function(){
60626         var renderers = [];
60627         var cm = this.grid.colModel;
60628         var colCount = cm.getColumnCount();
60629         for(var i = 0; i < colCount; i++){
60630             renderers[i] = cm.getRenderer(i);
60631         }
60632         return renderers;
60633     },
60634     
60635     getColumnIds : function(){
60636         var ids = [];
60637         var cm = this.grid.colModel;
60638         var colCount = cm.getColumnCount();
60639         for(var i = 0; i < colCount; i++){
60640             ids[i] = cm.getColumnId(i);
60641         }
60642         return ids;
60643     },
60644     
60645     getDataIndexes : function(){
60646         if(!this.indexMap){
60647             this.indexMap = this.buildIndexMap();
60648         }
60649         return this.indexMap.colToData;
60650     },
60651     
60652     getColumnIndexByDataIndex : function(dataIndex){
60653         if(!this.indexMap){
60654             this.indexMap = this.buildIndexMap();
60655         }
60656         return this.indexMap.dataToCol[dataIndex];
60657     },
60658     
60659     /**
60660      * Set a css style for a column dynamically. 
60661      * @param {Number} colIndex The index of the column
60662      * @param {String} name The css property name
60663      * @param {String} value The css value
60664      */
60665     setCSSStyle : function(colIndex, name, value){
60666         var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
60667         Roo.util.CSS.updateRule(selector, name, value);
60668     },
60669     
60670     generateRules : function(cm){
60671         var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
60672         Roo.util.CSS.removeStyleSheet(rulesId);
60673         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
60674             var cid = cm.getColumnId(i);
60675             ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
60676                          this.tdSelector, cid, " {\n}\n",
60677                          this.hdSelector, cid, " {\n}\n",
60678                          this.splitSelector, cid, " {\n}\n");
60679         }
60680         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
60681     }
60682 });/*
60683  * Based on:
60684  * Ext JS Library 1.1.1
60685  * Copyright(c) 2006-2007, Ext JS, LLC.
60686  *
60687  * Originally Released Under LGPL - original licence link has changed is not relivant.
60688  *
60689  * Fork - LGPL
60690  * <script type="text/javascript">
60691  */
60692
60693 // private
60694 // This is a support class used internally by the Grid components
60695 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
60696     this.grid = grid;
60697     this.view = grid.getView();
60698     this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
60699     Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
60700     if(hd2){
60701         this.setHandleElId(Roo.id(hd));
60702         this.setOuterHandleElId(Roo.id(hd2));
60703     }
60704     this.scroll = false;
60705 };
60706 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
60707     maxDragWidth: 120,
60708     getDragData : function(e){
60709         var t = Roo.lib.Event.getTarget(e);
60710         var h = this.view.findHeaderCell(t);
60711         if(h){
60712             return {ddel: h.firstChild, header:h};
60713         }
60714         return false;
60715     },
60716
60717     onInitDrag : function(e){
60718         this.view.headersDisabled = true;
60719         var clone = this.dragData.ddel.cloneNode(true);
60720         clone.id = Roo.id();
60721         clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
60722         this.proxy.update(clone);
60723         return true;
60724     },
60725
60726     afterValidDrop : function(){
60727         var v = this.view;
60728         setTimeout(function(){
60729             v.headersDisabled = false;
60730         }, 50);
60731     },
60732
60733     afterInvalidDrop : function(){
60734         var v = this.view;
60735         setTimeout(function(){
60736             v.headersDisabled = false;
60737         }, 50);
60738     }
60739 });
60740 /*
60741  * Based on:
60742  * Ext JS Library 1.1.1
60743  * Copyright(c) 2006-2007, Ext JS, LLC.
60744  *
60745  * Originally Released Under LGPL - original licence link has changed is not relivant.
60746  *
60747  * Fork - LGPL
60748  * <script type="text/javascript">
60749  */
60750 // private
60751 // This is a support class used internally by the Grid components
60752 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
60753     this.grid = grid;
60754     this.view = grid.getView();
60755     // split the proxies so they don't interfere with mouse events
60756     this.proxyTop = Roo.DomHelper.append(document.body, {
60757         cls:"col-move-top", html:"&#160;"
60758     }, true);
60759     this.proxyBottom = Roo.DomHelper.append(document.body, {
60760         cls:"col-move-bottom", html:"&#160;"
60761     }, true);
60762     this.proxyTop.hide = this.proxyBottom.hide = function(){
60763         this.setLeftTop(-100,-100);
60764         this.setStyle("visibility", "hidden");
60765     };
60766     this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
60767     // temporarily disabled
60768     //Roo.dd.ScrollManager.register(this.view.scroller.dom);
60769     Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
60770 };
60771 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
60772     proxyOffsets : [-4, -9],
60773     fly: Roo.Element.fly,
60774
60775     getTargetFromEvent : function(e){
60776         var t = Roo.lib.Event.getTarget(e);
60777         var cindex = this.view.findCellIndex(t);
60778         if(cindex !== false){
60779             return this.view.getHeaderCell(cindex);
60780         }
60781         return null;
60782     },
60783
60784     nextVisible : function(h){
60785         var v = this.view, cm = this.grid.colModel;
60786         h = h.nextSibling;
60787         while(h){
60788             if(!cm.isHidden(v.getCellIndex(h))){
60789                 return h;
60790             }
60791             h = h.nextSibling;
60792         }
60793         return null;
60794     },
60795
60796     prevVisible : function(h){
60797         var v = this.view, cm = this.grid.colModel;
60798         h = h.prevSibling;
60799         while(h){
60800             if(!cm.isHidden(v.getCellIndex(h))){
60801                 return h;
60802             }
60803             h = h.prevSibling;
60804         }
60805         return null;
60806     },
60807
60808     positionIndicator : function(h, n, e){
60809         var x = Roo.lib.Event.getPageX(e);
60810         var r = Roo.lib.Dom.getRegion(n.firstChild);
60811         var px, pt, py = r.top + this.proxyOffsets[1];
60812         if((r.right - x) <= (r.right-r.left)/2){
60813             px = r.right+this.view.borderWidth;
60814             pt = "after";
60815         }else{
60816             px = r.left;
60817             pt = "before";
60818         }
60819         var oldIndex = this.view.getCellIndex(h);
60820         var newIndex = this.view.getCellIndex(n);
60821
60822         if(this.grid.colModel.isFixed(newIndex)){
60823             return false;
60824         }
60825
60826         var locked = this.grid.colModel.isLocked(newIndex);
60827
60828         if(pt == "after"){
60829             newIndex++;
60830         }
60831         if(oldIndex < newIndex){
60832             newIndex--;
60833         }
60834         if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
60835             return false;
60836         }
60837         px +=  this.proxyOffsets[0];
60838         this.proxyTop.setLeftTop(px, py);
60839         this.proxyTop.show();
60840         if(!this.bottomOffset){
60841             this.bottomOffset = this.view.mainHd.getHeight();
60842         }
60843         this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
60844         this.proxyBottom.show();
60845         return pt;
60846     },
60847
60848     onNodeEnter : function(n, dd, e, data){
60849         if(data.header != n){
60850             this.positionIndicator(data.header, n, e);
60851         }
60852     },
60853
60854     onNodeOver : function(n, dd, e, data){
60855         var result = false;
60856         if(data.header != n){
60857             result = this.positionIndicator(data.header, n, e);
60858         }
60859         if(!result){
60860             this.proxyTop.hide();
60861             this.proxyBottom.hide();
60862         }
60863         return result ? this.dropAllowed : this.dropNotAllowed;
60864     },
60865
60866     onNodeOut : function(n, dd, e, data){
60867         this.proxyTop.hide();
60868         this.proxyBottom.hide();
60869     },
60870
60871     onNodeDrop : function(n, dd, e, data){
60872         var h = data.header;
60873         if(h != n){
60874             var cm = this.grid.colModel;
60875             var x = Roo.lib.Event.getPageX(e);
60876             var r = Roo.lib.Dom.getRegion(n.firstChild);
60877             var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
60878             var oldIndex = this.view.getCellIndex(h);
60879             var newIndex = this.view.getCellIndex(n);
60880             var locked = cm.isLocked(newIndex);
60881             if(pt == "after"){
60882                 newIndex++;
60883             }
60884             if(oldIndex < newIndex){
60885                 newIndex--;
60886             }
60887             if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
60888                 return false;
60889             }
60890             cm.setLocked(oldIndex, locked, true);
60891             cm.moveColumn(oldIndex, newIndex);
60892             this.grid.fireEvent("columnmove", oldIndex, newIndex);
60893             return true;
60894         }
60895         return false;
60896     }
60897 });
60898 /*
60899  * Based on:
60900  * Ext JS Library 1.1.1
60901  * Copyright(c) 2006-2007, Ext JS, LLC.
60902  *
60903  * Originally Released Under LGPL - original licence link has changed is not relivant.
60904  *
60905  * Fork - LGPL
60906  * <script type="text/javascript">
60907  */
60908   
60909 /**
60910  * @class Roo.grid.GridView
60911  * @extends Roo.util.Observable
60912  *
60913  * @constructor
60914  * @param {Object} config
60915  */
60916 Roo.grid.GridView = function(config){
60917     Roo.grid.GridView.superclass.constructor.call(this);
60918     this.el = null;
60919
60920     Roo.apply(this, config);
60921 };
60922
60923 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
60924
60925     unselectable :  'unselectable="on"',
60926     unselectableCls :  'x-unselectable',
60927     
60928     
60929     rowClass : "x-grid-row",
60930
60931     cellClass : "x-grid-col",
60932
60933     tdClass : "x-grid-td",
60934
60935     hdClass : "x-grid-hd",
60936
60937     splitClass : "x-grid-split",
60938
60939     sortClasses : ["sort-asc", "sort-desc"],
60940
60941     enableMoveAnim : false,
60942
60943     hlColor: "C3DAF9",
60944
60945     dh : Roo.DomHelper,
60946
60947     fly : Roo.Element.fly,
60948
60949     css : Roo.util.CSS,
60950
60951     borderWidth: 1,
60952
60953     splitOffset: 3,
60954
60955     scrollIncrement : 22,
60956
60957     cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
60958
60959     findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
60960
60961     bind : function(ds, cm){
60962         if(this.ds){
60963             this.ds.un("load", this.onLoad, this);
60964             this.ds.un("datachanged", this.onDataChange, this);
60965             this.ds.un("add", this.onAdd, this);
60966             this.ds.un("remove", this.onRemove, this);
60967             this.ds.un("update", this.onUpdate, this);
60968             this.ds.un("clear", this.onClear, this);
60969         }
60970         if(ds){
60971             ds.on("load", this.onLoad, this);
60972             ds.on("datachanged", this.onDataChange, this);
60973             ds.on("add", this.onAdd, this);
60974             ds.on("remove", this.onRemove, this);
60975             ds.on("update", this.onUpdate, this);
60976             ds.on("clear", this.onClear, this);
60977         }
60978         this.ds = ds;
60979
60980         if(this.cm){
60981             this.cm.un("widthchange", this.onColWidthChange, this);
60982             this.cm.un("headerchange", this.onHeaderChange, this);
60983             this.cm.un("hiddenchange", this.onHiddenChange, this);
60984             this.cm.un("columnmoved", this.onColumnMove, this);
60985             this.cm.un("columnlockchange", this.onColumnLock, this);
60986         }
60987         if(cm){
60988             this.generateRules(cm);
60989             cm.on("widthchange", this.onColWidthChange, this);
60990             cm.on("headerchange", this.onHeaderChange, this);
60991             cm.on("hiddenchange", this.onHiddenChange, this);
60992             cm.on("columnmoved", this.onColumnMove, this);
60993             cm.on("columnlockchange", this.onColumnLock, this);
60994         }
60995         this.cm = cm;
60996     },
60997
60998     init: function(grid){
60999         Roo.grid.GridView.superclass.init.call(this, grid);
61000
61001         this.bind(grid.dataSource, grid.colModel);
61002
61003         grid.on("headerclick", this.handleHeaderClick, this);
61004
61005         if(grid.trackMouseOver){
61006             grid.on("mouseover", this.onRowOver, this);
61007             grid.on("mouseout", this.onRowOut, this);
61008         }
61009         grid.cancelTextSelection = function(){};
61010         this.gridId = grid.id;
61011
61012         var tpls = this.templates || {};
61013
61014         if(!tpls.master){
61015             tpls.master = new Roo.Template(
61016                '<div class="x-grid" hidefocus="true">',
61017                 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
61018                   '<div class="x-grid-topbar"></div>',
61019                   '<div class="x-grid-scroller"><div></div></div>',
61020                   '<div class="x-grid-locked">',
61021                       '<div class="x-grid-header">{lockedHeader}</div>',
61022                       '<div class="x-grid-body">{lockedBody}</div>',
61023                   "</div>",
61024                   '<div class="x-grid-viewport">',
61025                       '<div class="x-grid-header">{header}</div>',
61026                       '<div class="x-grid-body">{body}</div>',
61027                   "</div>",
61028                   '<div class="x-grid-bottombar"></div>',
61029                  
61030                   '<div class="x-grid-resize-proxy">&#160;</div>',
61031                "</div>"
61032             );
61033             tpls.master.disableformats = true;
61034         }
61035
61036         if(!tpls.header){
61037             tpls.header = new Roo.Template(
61038                '<table border="0" cellspacing="0" cellpadding="0">',
61039                '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
61040                "</table>{splits}"
61041             );
61042             tpls.header.disableformats = true;
61043         }
61044         tpls.header.compile();
61045
61046         if(!tpls.hcell){
61047             tpls.hcell = new Roo.Template(
61048                 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
61049                 '<div class="x-grid-hd-text ' + this.unselectableCls +  '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
61050                 "</div></td>"
61051              );
61052              tpls.hcell.disableFormats = true;
61053         }
61054         tpls.hcell.compile();
61055
61056         if(!tpls.hsplit){
61057             tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
61058                                             this.unselectableCls +  '" ' + this.unselectable +'>&#160;</div>');
61059             tpls.hsplit.disableFormats = true;
61060         }
61061         tpls.hsplit.compile();
61062
61063         if(!tpls.body){
61064             tpls.body = new Roo.Template(
61065                '<table border="0" cellspacing="0" cellpadding="0">',
61066                "<tbody>{rows}</tbody>",
61067                "</table>"
61068             );
61069             tpls.body.disableFormats = true;
61070         }
61071         tpls.body.compile();
61072
61073         if(!tpls.row){
61074             tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
61075             tpls.row.disableFormats = true;
61076         }
61077         tpls.row.compile();
61078
61079         if(!tpls.cell){
61080             tpls.cell = new Roo.Template(
61081                 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
61082                 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
61083                     this.unselectableCls +  '" ' + this.unselectable +'" {attr}>{value}</div></div>',
61084                 "</td>"
61085             );
61086             tpls.cell.disableFormats = true;
61087         }
61088         tpls.cell.compile();
61089
61090         this.templates = tpls;
61091     },
61092
61093     // remap these for backwards compat
61094     onColWidthChange : function(){
61095         this.updateColumns.apply(this, arguments);
61096     },
61097     onHeaderChange : function(){
61098         this.updateHeaders.apply(this, arguments);
61099     }, 
61100     onHiddenChange : function(){
61101         this.handleHiddenChange.apply(this, arguments);
61102     },
61103     onColumnMove : function(){
61104         this.handleColumnMove.apply(this, arguments);
61105     },
61106     onColumnLock : function(){
61107         this.handleLockChange.apply(this, arguments);
61108     },
61109
61110     onDataChange : function(){
61111         this.refresh();
61112         this.updateHeaderSortState();
61113     },
61114
61115     onClear : function(){
61116         this.refresh();
61117     },
61118
61119     onUpdate : function(ds, record){
61120         this.refreshRow(record);
61121     },
61122
61123     refreshRow : function(record){
61124         var ds = this.ds, index;
61125         if(typeof record == 'number'){
61126             index = record;
61127             record = ds.getAt(index);
61128         }else{
61129             index = ds.indexOf(record);
61130         }
61131         this.insertRows(ds, index, index, true);
61132         this.onRemove(ds, record, index+1, true);
61133         this.syncRowHeights(index, index);
61134         this.layout();
61135         this.fireEvent("rowupdated", this, index, record);
61136     },
61137
61138     onAdd : function(ds, records, index){
61139         this.insertRows(ds, index, index + (records.length-1));
61140     },
61141
61142     onRemove : function(ds, record, index, isUpdate){
61143         if(isUpdate !== true){
61144             this.fireEvent("beforerowremoved", this, index, record);
61145         }
61146         var bt = this.getBodyTable(), lt = this.getLockedTable();
61147         if(bt.rows[index]){
61148             bt.firstChild.removeChild(bt.rows[index]);
61149         }
61150         if(lt.rows[index]){
61151             lt.firstChild.removeChild(lt.rows[index]);
61152         }
61153         if(isUpdate !== true){
61154             this.stripeRows(index);
61155             this.syncRowHeights(index, index);
61156             this.layout();
61157             this.fireEvent("rowremoved", this, index, record);
61158         }
61159     },
61160
61161     onLoad : function(){
61162         this.scrollToTop();
61163     },
61164
61165     /**
61166      * Scrolls the grid to the top
61167      */
61168     scrollToTop : function(){
61169         if(this.scroller){
61170             this.scroller.dom.scrollTop = 0;
61171             this.syncScroll();
61172         }
61173     },
61174
61175     /**
61176      * Gets a panel in the header of the grid that can be used for toolbars etc.
61177      * After modifying the contents of this panel a call to grid.autoSize() may be
61178      * required to register any changes in size.
61179      * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
61180      * @return Roo.Element
61181      */
61182     getHeaderPanel : function(doShow){
61183         if(doShow){
61184             this.headerPanel.show();
61185         }
61186         return this.headerPanel;
61187     },
61188
61189     /**
61190      * Gets a panel in the footer of the grid that can be used for toolbars etc.
61191      * After modifying the contents of this panel a call to grid.autoSize() may be
61192      * required to register any changes in size.
61193      * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
61194      * @return Roo.Element
61195      */
61196     getFooterPanel : function(doShow){
61197         if(doShow){
61198             this.footerPanel.show();
61199         }
61200         return this.footerPanel;
61201     },
61202
61203     initElements : function(){
61204         var E = Roo.Element;
61205         var el = this.grid.getGridEl().dom.firstChild;
61206         var cs = el.childNodes;
61207
61208         this.el = new E(el);
61209         
61210          this.focusEl = new E(el.firstChild);
61211         this.focusEl.swallowEvent("click", true);
61212         
61213         this.headerPanel = new E(cs[1]);
61214         this.headerPanel.enableDisplayMode("block");
61215
61216         this.scroller = new E(cs[2]);
61217         this.scrollSizer = new E(this.scroller.dom.firstChild);
61218
61219         this.lockedWrap = new E(cs[3]);
61220         this.lockedHd = new E(this.lockedWrap.dom.firstChild);
61221         this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
61222
61223         this.mainWrap = new E(cs[4]);
61224         this.mainHd = new E(this.mainWrap.dom.firstChild);
61225         this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
61226
61227         this.footerPanel = new E(cs[5]);
61228         this.footerPanel.enableDisplayMode("block");
61229
61230         this.resizeProxy = new E(cs[6]);
61231
61232         this.headerSelector = String.format(
61233            '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
61234            this.lockedHd.id, this.mainHd.id
61235         );
61236
61237         this.splitterSelector = String.format(
61238            '#{0} div.x-grid-split, #{1} div.x-grid-split',
61239            this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
61240         );
61241     },
61242     idToCssName : function(s)
61243     {
61244         return s.replace(/[^a-z0-9]+/ig, '-');
61245     },
61246
61247     getHeaderCell : function(index){
61248         return Roo.DomQuery.select(this.headerSelector)[index];
61249     },
61250
61251     getHeaderCellMeasure : function(index){
61252         return this.getHeaderCell(index).firstChild;
61253     },
61254
61255     getHeaderCellText : function(index){
61256         return this.getHeaderCell(index).firstChild.firstChild;
61257     },
61258
61259     getLockedTable : function(){
61260         return this.lockedBody.dom.firstChild;
61261     },
61262
61263     getBodyTable : function(){
61264         return this.mainBody.dom.firstChild;
61265     },
61266
61267     getLockedRow : function(index){
61268         return this.getLockedTable().rows[index];
61269     },
61270
61271     getRow : function(index){
61272         return this.getBodyTable().rows[index];
61273     },
61274
61275     getRowComposite : function(index){
61276         if(!this.rowEl){
61277             this.rowEl = new Roo.CompositeElementLite();
61278         }
61279         var els = [], lrow, mrow;
61280         if(lrow = this.getLockedRow(index)){
61281             els.push(lrow);
61282         }
61283         if(mrow = this.getRow(index)){
61284             els.push(mrow);
61285         }
61286         this.rowEl.elements = els;
61287         return this.rowEl;
61288     },
61289     /**
61290      * Gets the 'td' of the cell
61291      * 
61292      * @param {Integer} rowIndex row to select
61293      * @param {Integer} colIndex column to select
61294      * 
61295      * @return {Object} 
61296      */
61297     getCell : function(rowIndex, colIndex){
61298         var locked = this.cm.getLockedCount();
61299         var source;
61300         if(colIndex < locked){
61301             source = this.lockedBody.dom.firstChild;
61302         }else{
61303             source = this.mainBody.dom.firstChild;
61304             colIndex -= locked;
61305         }
61306         return source.rows[rowIndex].childNodes[colIndex];
61307     },
61308
61309     getCellText : function(rowIndex, colIndex){
61310         return this.getCell(rowIndex, colIndex).firstChild.firstChild;
61311     },
61312
61313     getCellBox : function(cell){
61314         var b = this.fly(cell).getBox();
61315         if(Roo.isOpera){ // opera fails to report the Y
61316             b.y = cell.offsetTop + this.mainBody.getY();
61317         }
61318         return b;
61319     },
61320
61321     getCellIndex : function(cell){
61322         var id = String(cell.className).match(this.cellRE);
61323         if(id){
61324             return parseInt(id[1], 10);
61325         }
61326         return 0;
61327     },
61328
61329     findHeaderIndex : function(n){
61330         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
61331         return r ? this.getCellIndex(r) : false;
61332     },
61333
61334     findHeaderCell : function(n){
61335         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
61336         return r ? r : false;
61337     },
61338
61339     findRowIndex : function(n){
61340         if(!n){
61341             return false;
61342         }
61343         var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
61344         return r ? r.rowIndex : false;
61345     },
61346
61347     findCellIndex : function(node){
61348         var stop = this.el.dom;
61349         while(node && node != stop){
61350             if(this.findRE.test(node.className)){
61351                 return this.getCellIndex(node);
61352             }
61353             node = node.parentNode;
61354         }
61355         return false;
61356     },
61357
61358     getColumnId : function(index){
61359         return this.cm.getColumnId(index);
61360     },
61361
61362     getSplitters : function()
61363     {
61364         if(this.splitterSelector){
61365            return Roo.DomQuery.select(this.splitterSelector);
61366         }else{
61367             return null;
61368       }
61369     },
61370
61371     getSplitter : function(index){
61372         return this.getSplitters()[index];
61373     },
61374
61375     onRowOver : function(e, t){
61376         var row;
61377         if((row = this.findRowIndex(t)) !== false){
61378             this.getRowComposite(row).addClass("x-grid-row-over");
61379         }
61380     },
61381
61382     onRowOut : function(e, t){
61383         var row;
61384         if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
61385             this.getRowComposite(row).removeClass("x-grid-row-over");
61386         }
61387     },
61388
61389     renderHeaders : function(){
61390         var cm = this.cm;
61391         var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
61392         var cb = [], lb = [], sb = [], lsb = [], p = {};
61393         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
61394             p.cellId = "x-grid-hd-0-" + i;
61395             p.splitId = "x-grid-csplit-0-" + i;
61396             p.id = cm.getColumnId(i);
61397             p.value = cm.getColumnHeader(i) || "";
61398             p.title = cm.getColumnTooltip(i) || (''+p.value).match(/\</)  ? '' :  p.value  || "";
61399             p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
61400             if(!cm.isLocked(i)){
61401                 cb[cb.length] = ct.apply(p);
61402                 sb[sb.length] = st.apply(p);
61403             }else{
61404                 lb[lb.length] = ct.apply(p);
61405                 lsb[lsb.length] = st.apply(p);
61406             }
61407         }
61408         return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
61409                 ht.apply({cells: cb.join(""), splits:sb.join("")})];
61410     },
61411
61412     updateHeaders : function(){
61413         var html = this.renderHeaders();
61414         this.lockedHd.update(html[0]);
61415         this.mainHd.update(html[1]);
61416     },
61417
61418     /**
61419      * Focuses the specified row.
61420      * @param {Number} row The row index
61421      */
61422     focusRow : function(row)
61423     {
61424         //Roo.log('GridView.focusRow');
61425         var x = this.scroller.dom.scrollLeft;
61426         this.focusCell(row, 0, false);
61427         this.scroller.dom.scrollLeft = x;
61428     },
61429
61430     /**
61431      * Focuses the specified cell.
61432      * @param {Number} row The row index
61433      * @param {Number} col The column index
61434      * @param {Boolean} hscroll false to disable horizontal scrolling
61435      */
61436     focusCell : function(row, col, hscroll)
61437     {
61438         //Roo.log('GridView.focusCell');
61439         var el = this.ensureVisible(row, col, hscroll);
61440         this.focusEl.alignTo(el, "tl-tl");
61441         if(Roo.isGecko){
61442             this.focusEl.focus();
61443         }else{
61444             this.focusEl.focus.defer(1, this.focusEl);
61445         }
61446     },
61447
61448     /**
61449      * Scrolls the specified cell into view
61450      * @param {Number} row The row index
61451      * @param {Number} col The column index
61452      * @param {Boolean} hscroll false to disable horizontal scrolling
61453      */
61454     ensureVisible : function(row, col, hscroll)
61455     {
61456         //Roo.log('GridView.ensureVisible,' + row + ',' + col);
61457         //return null; //disable for testing.
61458         if(typeof row != "number"){
61459             row = row.rowIndex;
61460         }
61461         if(row < 0 && row >= this.ds.getCount()){
61462             return  null;
61463         }
61464         col = (col !== undefined ? col : 0);
61465         var cm = this.grid.colModel;
61466         while(cm.isHidden(col)){
61467             col++;
61468         }
61469
61470         var el = this.getCell(row, col);
61471         if(!el){
61472             return null;
61473         }
61474         var c = this.scroller.dom;
61475
61476         var ctop = parseInt(el.offsetTop, 10);
61477         var cleft = parseInt(el.offsetLeft, 10);
61478         var cbot = ctop + el.offsetHeight;
61479         var cright = cleft + el.offsetWidth;
61480         
61481         var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
61482         var stop = parseInt(c.scrollTop, 10);
61483         var sleft = parseInt(c.scrollLeft, 10);
61484         var sbot = stop + ch;
61485         var sright = sleft + c.clientWidth;
61486         /*
61487         Roo.log('GridView.ensureVisible:' +
61488                 ' ctop:' + ctop +
61489                 ' c.clientHeight:' + c.clientHeight +
61490                 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
61491                 ' stop:' + stop +
61492                 ' cbot:' + cbot +
61493                 ' sbot:' + sbot +
61494                 ' ch:' + ch  
61495                 );
61496         */
61497         if(ctop < stop){
61498             c.scrollTop = ctop;
61499             //Roo.log("set scrolltop to ctop DISABLE?");
61500         }else if(cbot > sbot){
61501             //Roo.log("set scrolltop to cbot-ch");
61502             c.scrollTop = cbot-ch;
61503         }
61504         
61505         if(hscroll !== false){
61506             if(cleft < sleft){
61507                 c.scrollLeft = cleft;
61508             }else if(cright > sright){
61509                 c.scrollLeft = cright-c.clientWidth;
61510             }
61511         }
61512          
61513         return el;
61514     },
61515
61516     updateColumns : function(){
61517         this.grid.stopEditing();
61518         var cm = this.grid.colModel, colIds = this.getColumnIds();
61519         //var totalWidth = cm.getTotalWidth();
61520         var pos = 0;
61521         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
61522             //if(cm.isHidden(i)) continue;
61523             var w = cm.getColumnWidth(i);
61524             this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
61525             this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
61526         }
61527         this.updateSplitters();
61528     },
61529
61530     generateRules : function(cm){
61531         var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
61532         Roo.util.CSS.removeStyleSheet(rulesId);
61533         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
61534             var cid = cm.getColumnId(i);
61535             var align = '';
61536             if(cm.config[i].align){
61537                 align = 'text-align:'+cm.config[i].align+';';
61538             }
61539             var hidden = '';
61540             if(cm.isHidden(i)){
61541                 hidden = 'display:none;';
61542             }
61543             var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
61544             ruleBuf.push(
61545                     this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
61546                     this.hdSelector, cid, " {\n", align, width, "}\n",
61547                     this.tdSelector, cid, " {\n",hidden,"\n}\n",
61548                     this.splitSelector, cid, " {\n", hidden , "\n}\n");
61549         }
61550         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
61551     },
61552
61553     updateSplitters : function(){
61554         var cm = this.cm, s = this.getSplitters();
61555         if(s){ // splitters not created yet
61556             var pos = 0, locked = true;
61557             for(var i = 0, len = cm.getColumnCount(); i < len; i++){
61558                 if(cm.isHidden(i)) {
61559                     continue;
61560                 }
61561                 var w = cm.getColumnWidth(i); // make sure it's a number
61562                 if(!cm.isLocked(i) && locked){
61563                     pos = 0;
61564                     locked = false;
61565                 }
61566                 pos += w;
61567                 s[i].style.left = (pos-this.splitOffset) + "px";
61568             }
61569         }
61570     },
61571
61572     handleHiddenChange : function(colModel, colIndex, hidden){
61573         if(hidden){
61574             this.hideColumn(colIndex);
61575         }else{
61576             this.unhideColumn(colIndex);
61577         }
61578     },
61579
61580     hideColumn : function(colIndex){
61581         var cid = this.getColumnId(colIndex);
61582         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
61583         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
61584         if(Roo.isSafari){
61585             this.updateHeaders();
61586         }
61587         this.updateSplitters();
61588         this.layout();
61589     },
61590
61591     unhideColumn : function(colIndex){
61592         var cid = this.getColumnId(colIndex);
61593         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
61594         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
61595
61596         if(Roo.isSafari){
61597             this.updateHeaders();
61598         }
61599         this.updateSplitters();
61600         this.layout();
61601     },
61602
61603     insertRows : function(dm, firstRow, lastRow, isUpdate){
61604         if(firstRow == 0 && lastRow == dm.getCount()-1){
61605             this.refresh();
61606         }else{
61607             if(!isUpdate){
61608                 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
61609             }
61610             var s = this.getScrollState();
61611             var markup = this.renderRows(firstRow, lastRow);
61612             this.bufferRows(markup[0], this.getLockedTable(), firstRow);
61613             this.bufferRows(markup[1], this.getBodyTable(), firstRow);
61614             this.restoreScroll(s);
61615             if(!isUpdate){
61616                 this.fireEvent("rowsinserted", this, firstRow, lastRow);
61617                 this.syncRowHeights(firstRow, lastRow);
61618                 this.stripeRows(firstRow);
61619                 this.layout();
61620             }
61621         }
61622     },
61623
61624     bufferRows : function(markup, target, index){
61625         var before = null, trows = target.rows, tbody = target.tBodies[0];
61626         if(index < trows.length){
61627             before = trows[index];
61628         }
61629         var b = document.createElement("div");
61630         b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
61631         var rows = b.firstChild.rows;
61632         for(var i = 0, len = rows.length; i < len; i++){
61633             if(before){
61634                 tbody.insertBefore(rows[0], before);
61635             }else{
61636                 tbody.appendChild(rows[0]);
61637             }
61638         }
61639         b.innerHTML = "";
61640         b = null;
61641     },
61642
61643     deleteRows : function(dm, firstRow, lastRow){
61644         if(dm.getRowCount()<1){
61645             this.fireEvent("beforerefresh", this);
61646             this.mainBody.update("");
61647             this.lockedBody.update("");
61648             this.fireEvent("refresh", this);
61649         }else{
61650             this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
61651             var bt = this.getBodyTable();
61652             var tbody = bt.firstChild;
61653             var rows = bt.rows;
61654             for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
61655                 tbody.removeChild(rows[firstRow]);
61656             }
61657             this.stripeRows(firstRow);
61658             this.fireEvent("rowsdeleted", this, firstRow, lastRow);
61659         }
61660     },
61661
61662     updateRows : function(dataSource, firstRow, lastRow){
61663         var s = this.getScrollState();
61664         this.refresh();
61665         this.restoreScroll(s);
61666     },
61667
61668     handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
61669         if(!noRefresh){
61670            this.refresh();
61671         }
61672         this.updateHeaderSortState();
61673     },
61674
61675     getScrollState : function(){
61676         
61677         var sb = this.scroller.dom;
61678         return {left: sb.scrollLeft, top: sb.scrollTop};
61679     },
61680
61681     stripeRows : function(startRow){
61682         if(!this.grid.stripeRows || this.ds.getCount() < 1){
61683             return;
61684         }
61685         startRow = startRow || 0;
61686         var rows = this.getBodyTable().rows;
61687         var lrows = this.getLockedTable().rows;
61688         var cls = ' x-grid-row-alt ';
61689         for(var i = startRow, len = rows.length; i < len; i++){
61690             var row = rows[i], lrow = lrows[i];
61691             var isAlt = ((i+1) % 2 == 0);
61692             var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
61693             if(isAlt == hasAlt){
61694                 continue;
61695             }
61696             if(isAlt){
61697                 row.className += " x-grid-row-alt";
61698             }else{
61699                 row.className = row.className.replace("x-grid-row-alt", "");
61700             }
61701             if(lrow){
61702                 lrow.className = row.className;
61703             }
61704         }
61705     },
61706
61707     restoreScroll : function(state){
61708         //Roo.log('GridView.restoreScroll');
61709         var sb = this.scroller.dom;
61710         sb.scrollLeft = state.left;
61711         sb.scrollTop = state.top;
61712         this.syncScroll();
61713     },
61714
61715     syncScroll : function(){
61716         //Roo.log('GridView.syncScroll');
61717         var sb = this.scroller.dom;
61718         var sh = this.mainHd.dom;
61719         var bs = this.mainBody.dom;
61720         var lv = this.lockedBody.dom;
61721         sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
61722         lv.scrollTop = bs.scrollTop = sb.scrollTop;
61723     },
61724
61725     handleScroll : function(e){
61726         this.syncScroll();
61727         var sb = this.scroller.dom;
61728         this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
61729         e.stopEvent();
61730     },
61731
61732     handleWheel : function(e){
61733         var d = e.getWheelDelta();
61734         this.scroller.dom.scrollTop -= d*22;
61735         // set this here to prevent jumpy scrolling on large tables
61736         this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
61737         e.stopEvent();
61738     },
61739
61740     renderRows : function(startRow, endRow){
61741         // pull in all the crap needed to render rows
61742         var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
61743         var colCount = cm.getColumnCount();
61744
61745         if(ds.getCount() < 1){
61746             return ["", ""];
61747         }
61748
61749         // build a map for all the columns
61750         var cs = [];
61751         for(var i = 0; i < colCount; i++){
61752             var name = cm.getDataIndex(i);
61753             cs[i] = {
61754                 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
61755                 renderer : cm.getRenderer(i),
61756                 id : cm.getColumnId(i),
61757                 locked : cm.isLocked(i),
61758                 has_editor : cm.isCellEditable(i)
61759             };
61760         }
61761
61762         startRow = startRow || 0;
61763         endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
61764
61765         // records to render
61766         var rs = ds.getRange(startRow, endRow);
61767
61768         return this.doRender(cs, rs, ds, startRow, colCount, stripe);
61769     },
61770
61771     // As much as I hate to duplicate code, this was branched because FireFox really hates
61772     // [].join("") on strings. The performance difference was substantial enough to
61773     // branch this function
61774     doRender : Roo.isGecko ?
61775             function(cs, rs, ds, startRow, colCount, stripe){
61776                 var ts = this.templates, ct = ts.cell, rt = ts.row;
61777                 // buffers
61778                 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
61779                 
61780                 var hasListener = this.grid.hasListener('rowclass');
61781                 var rowcfg = {};
61782                 for(var j = 0, len = rs.length; j < len; j++){
61783                     r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
61784                     for(var i = 0; i < colCount; i++){
61785                         c = cs[i];
61786                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
61787                         p.id = c.id;
61788                         p.css = p.attr = "";
61789                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
61790                         if(p.value == undefined || p.value === "") {
61791                             p.value = "&#160;";
61792                         }
61793                         if(c.has_editor){
61794                             p.css += ' x-grid-editable-cell';
61795                         }
61796                         if(c.dirty && typeof r.modified[c.name] !== 'undefined'){
61797                             p.css +=  ' x-grid-dirty-cell';
61798                         }
61799                         var markup = ct.apply(p);
61800                         if(!c.locked){
61801                             cb+= markup;
61802                         }else{
61803                             lcb+= markup;
61804                         }
61805                     }
61806                     var alt = [];
61807                     if(stripe && ((rowIndex+1) % 2 == 0)){
61808                         alt.push("x-grid-row-alt")
61809                     }
61810                     if(r.dirty){
61811                         alt.push(  " x-grid-dirty-row");
61812                     }
61813                     rp.cells = lcb;
61814                     if(this.getRowClass){
61815                         alt.push(this.getRowClass(r, rowIndex));
61816                     }
61817                     if (hasListener) {
61818                         rowcfg = {
61819                              
61820                             record: r,
61821                             rowIndex : rowIndex,
61822                             rowClass : ''
61823                         };
61824                         this.grid.fireEvent('rowclass', this, rowcfg);
61825                         alt.push(rowcfg.rowClass);
61826                     }
61827                     rp.alt = alt.join(" ");
61828                     lbuf+= rt.apply(rp);
61829                     rp.cells = cb;
61830                     buf+=  rt.apply(rp);
61831                 }
61832                 return [lbuf, buf];
61833             } :
61834             function(cs, rs, ds, startRow, colCount, stripe){
61835                 var ts = this.templates, ct = ts.cell, rt = ts.row;
61836                 // buffers
61837                 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
61838                 var hasListener = this.grid.hasListener('rowclass');
61839  
61840                 var rowcfg = {};
61841                 for(var j = 0, len = rs.length; j < len; j++){
61842                     r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
61843                     for(var i = 0; i < colCount; i++){
61844                         c = cs[i];
61845                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
61846                         p.id = c.id;
61847                         p.css = p.attr = "";
61848                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
61849                         if(p.value == undefined || p.value === "") {
61850                             p.value = "&#160;";
61851                         }
61852                         //Roo.log(c);
61853                          if(c.has_editor){
61854                             p.css += ' x-grid-editable-cell';
61855                         }
61856                         if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
61857                             p.css += ' x-grid-dirty-cell' 
61858                         }
61859                         
61860                         var markup = ct.apply(p);
61861                         if(!c.locked){
61862                             cb[cb.length] = markup;
61863                         }else{
61864                             lcb[lcb.length] = markup;
61865                         }
61866                     }
61867                     var alt = [];
61868                     if(stripe && ((rowIndex+1) % 2 == 0)){
61869                         alt.push( "x-grid-row-alt");
61870                     }
61871                     if(r.dirty){
61872                         alt.push(" x-grid-dirty-row");
61873                     }
61874                     rp.cells = lcb;
61875                     if(this.getRowClass){
61876                         alt.push( this.getRowClass(r, rowIndex));
61877                     }
61878                     if (hasListener) {
61879                         rowcfg = {
61880                              
61881                             record: r,
61882                             rowIndex : rowIndex,
61883                             rowClass : ''
61884                         };
61885                         this.grid.fireEvent('rowclass', this, rowcfg);
61886                         alt.push(rowcfg.rowClass);
61887                     }
61888                     
61889                     rp.alt = alt.join(" ");
61890                     rp.cells = lcb.join("");
61891                     lbuf[lbuf.length] = rt.apply(rp);
61892                     rp.cells = cb.join("");
61893                     buf[buf.length] =  rt.apply(rp);
61894                 }
61895                 return [lbuf.join(""), buf.join("")];
61896             },
61897
61898     renderBody : function(){
61899         var markup = this.renderRows();
61900         var bt = this.templates.body;
61901         return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
61902     },
61903
61904     /**
61905      * Refreshes the grid
61906      * @param {Boolean} headersToo
61907      */
61908     refresh : function(headersToo){
61909         this.fireEvent("beforerefresh", this);
61910         this.grid.stopEditing();
61911         var result = this.renderBody();
61912         this.lockedBody.update(result[0]);
61913         this.mainBody.update(result[1]);
61914         if(headersToo === true){
61915             this.updateHeaders();
61916             this.updateColumns();
61917             this.updateSplitters();
61918             this.updateHeaderSortState();
61919         }
61920         this.syncRowHeights();
61921         this.layout();
61922         this.fireEvent("refresh", this);
61923     },
61924
61925     handleColumnMove : function(cm, oldIndex, newIndex){
61926         this.indexMap = null;
61927         var s = this.getScrollState();
61928         this.refresh(true);
61929         this.restoreScroll(s);
61930         this.afterMove(newIndex);
61931     },
61932
61933     afterMove : function(colIndex){
61934         if(this.enableMoveAnim && Roo.enableFx){
61935             this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
61936         }
61937         // if multisort - fix sortOrder, and reload..
61938         if (this.grid.dataSource.multiSort) {
61939             // the we can call sort again..
61940             var dm = this.grid.dataSource;
61941             var cm = this.grid.colModel;
61942             var so = [];
61943             for(var i = 0; i < cm.config.length; i++ ) {
61944                 
61945                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
61946                     continue; // dont' bother, it's not in sort list or being set.
61947                 }
61948                 
61949                 so.push(cm.config[i].dataIndex);
61950             };
61951             dm.sortOrder = so;
61952             dm.load(dm.lastOptions);
61953             
61954             
61955         }
61956         
61957     },
61958
61959     updateCell : function(dm, rowIndex, dataIndex){
61960         var colIndex = this.getColumnIndexByDataIndex(dataIndex);
61961         if(typeof colIndex == "undefined"){ // not present in grid
61962             return;
61963         }
61964         var cm = this.grid.colModel;
61965         var cell = this.getCell(rowIndex, colIndex);
61966         var cellText = this.getCellText(rowIndex, colIndex);
61967
61968         var p = {
61969             cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
61970             id : cm.getColumnId(colIndex),
61971             css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
61972         };
61973         var renderer = cm.getRenderer(colIndex);
61974         var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
61975         if(typeof val == "undefined" || val === "") {
61976             val = "&#160;";
61977         }
61978         cellText.innerHTML = val;
61979         cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
61980         this.syncRowHeights(rowIndex, rowIndex);
61981     },
61982
61983     calcColumnWidth : function(colIndex, maxRowsToMeasure){
61984         var maxWidth = 0;
61985         if(this.grid.autoSizeHeaders){
61986             var h = this.getHeaderCellMeasure(colIndex);
61987             maxWidth = Math.max(maxWidth, h.scrollWidth);
61988         }
61989         var tb, index;
61990         if(this.cm.isLocked(colIndex)){
61991             tb = this.getLockedTable();
61992             index = colIndex;
61993         }else{
61994             tb = this.getBodyTable();
61995             index = colIndex - this.cm.getLockedCount();
61996         }
61997         if(tb && tb.rows){
61998             var rows = tb.rows;
61999             var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
62000             for(var i = 0; i < stopIndex; i++){
62001                 var cell = rows[i].childNodes[index].firstChild;
62002                 maxWidth = Math.max(maxWidth, cell.scrollWidth);
62003             }
62004         }
62005         return maxWidth + /*margin for error in IE*/ 5;
62006     },
62007     /**
62008      * Autofit a column to its content.
62009      * @param {Number} colIndex
62010      * @param {Boolean} forceMinSize true to force the column to go smaller if possible
62011      */
62012      autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
62013          if(this.cm.isHidden(colIndex)){
62014              return; // can't calc a hidden column
62015          }
62016         if(forceMinSize){
62017             var cid = this.cm.getColumnId(colIndex);
62018             this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
62019            if(this.grid.autoSizeHeaders){
62020                this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
62021            }
62022         }
62023         var newWidth = this.calcColumnWidth(colIndex);
62024         this.cm.setColumnWidth(colIndex,
62025             Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
62026         if(!suppressEvent){
62027             this.grid.fireEvent("columnresize", colIndex, newWidth);
62028         }
62029     },
62030
62031     /**
62032      * Autofits all columns to their content and then expands to fit any extra space in the grid
62033      */
62034      autoSizeColumns : function(){
62035         var cm = this.grid.colModel;
62036         var colCount = cm.getColumnCount();
62037         for(var i = 0; i < colCount; i++){
62038             this.autoSizeColumn(i, true, true);
62039         }
62040         if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
62041             this.fitColumns();
62042         }else{
62043             this.updateColumns();
62044             this.layout();
62045         }
62046     },
62047
62048     /**
62049      * Autofits all columns to the grid's width proportionate with their current size
62050      * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
62051      */
62052     fitColumns : function(reserveScrollSpace){
62053         var cm = this.grid.colModel;
62054         var colCount = cm.getColumnCount();
62055         var cols = [];
62056         var width = 0;
62057         var i, w;
62058         for (i = 0; i < colCount; i++){
62059             if(!cm.isHidden(i) && !cm.isFixed(i)){
62060                 w = cm.getColumnWidth(i);
62061                 cols.push(i);
62062                 cols.push(w);
62063                 width += w;
62064             }
62065         }
62066         var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
62067         if(reserveScrollSpace){
62068             avail -= 17;
62069         }
62070         var frac = (avail - cm.getTotalWidth())/width;
62071         while (cols.length){
62072             w = cols.pop();
62073             i = cols.pop();
62074             cm.setColumnWidth(i, Math.floor(w + w*frac), true);
62075         }
62076         this.updateColumns();
62077         this.layout();
62078     },
62079
62080     onRowSelect : function(rowIndex){
62081         var row = this.getRowComposite(rowIndex);
62082         row.addClass("x-grid-row-selected");
62083     },
62084
62085     onRowDeselect : function(rowIndex){
62086         var row = this.getRowComposite(rowIndex);
62087         row.removeClass("x-grid-row-selected");
62088     },
62089
62090     onCellSelect : function(row, col){
62091         var cell = this.getCell(row, col);
62092         if(cell){
62093             Roo.fly(cell).addClass("x-grid-cell-selected");
62094         }
62095     },
62096
62097     onCellDeselect : function(row, col){
62098         var cell = this.getCell(row, col);
62099         if(cell){
62100             Roo.fly(cell).removeClass("x-grid-cell-selected");
62101         }
62102     },
62103
62104     updateHeaderSortState : function(){
62105         
62106         // sort state can be single { field: xxx, direction : yyy}
62107         // or   { xxx=>ASC , yyy : DESC ..... }
62108         
62109         var mstate = {};
62110         if (!this.ds.multiSort) { 
62111             var state = this.ds.getSortState();
62112             if(!state){
62113                 return;
62114             }
62115             mstate[state.field] = state.direction;
62116             // FIXME... - this is not used here.. but might be elsewhere..
62117             this.sortState = state;
62118             
62119         } else {
62120             mstate = this.ds.sortToggle;
62121         }
62122         //remove existing sort classes..
62123         
62124         var sc = this.sortClasses;
62125         var hds = this.el.select(this.headerSelector).removeClass(sc);
62126         
62127         for(var f in mstate) {
62128         
62129             var sortColumn = this.cm.findColumnIndex(f);
62130             
62131             if(sortColumn != -1){
62132                 var sortDir = mstate[f];        
62133                 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
62134             }
62135         }
62136         
62137          
62138         
62139     },
62140
62141
62142     handleHeaderClick : function(g, index,e){
62143         
62144         Roo.log("header click");
62145         
62146         if (Roo.isTouch) {
62147             // touch events on header are handled by context
62148             this.handleHdCtx(g,index,e);
62149             return;
62150         }
62151         
62152         
62153         if(this.headersDisabled){
62154             return;
62155         }
62156         var dm = g.dataSource, cm = g.colModel;
62157         if(!cm.isSortable(index)){
62158             return;
62159         }
62160         g.stopEditing();
62161         
62162         if (dm.multiSort) {
62163             // update the sortOrder
62164             var so = [];
62165             for(var i = 0; i < cm.config.length; i++ ) {
62166                 
62167                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
62168                     continue; // dont' bother, it's not in sort list or being set.
62169                 }
62170                 
62171                 so.push(cm.config[i].dataIndex);
62172             };
62173             dm.sortOrder = so;
62174         }
62175         
62176         
62177         dm.sort(cm.getDataIndex(index));
62178     },
62179
62180
62181     destroy : function(){
62182         if(this.colMenu){
62183             this.colMenu.removeAll();
62184             Roo.menu.MenuMgr.unregister(this.colMenu);
62185             this.colMenu.getEl().remove();
62186             delete this.colMenu;
62187         }
62188         if(this.hmenu){
62189             this.hmenu.removeAll();
62190             Roo.menu.MenuMgr.unregister(this.hmenu);
62191             this.hmenu.getEl().remove();
62192             delete this.hmenu;
62193         }
62194         if(this.grid.enableColumnMove){
62195             var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
62196             if(dds){
62197                 for(var dd in dds){
62198                     if(!dds[dd].config.isTarget && dds[dd].dragElId){
62199                         var elid = dds[dd].dragElId;
62200                         dds[dd].unreg();
62201                         Roo.get(elid).remove();
62202                     } else if(dds[dd].config.isTarget){
62203                         dds[dd].proxyTop.remove();
62204                         dds[dd].proxyBottom.remove();
62205                         dds[dd].unreg();
62206                     }
62207                     if(Roo.dd.DDM.locationCache[dd]){
62208                         delete Roo.dd.DDM.locationCache[dd];
62209                     }
62210                 }
62211                 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
62212             }
62213         }
62214         Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
62215         this.bind(null, null);
62216         Roo.EventManager.removeResizeListener(this.onWindowResize, this);
62217     },
62218
62219     handleLockChange : function(){
62220         this.refresh(true);
62221     },
62222
62223     onDenyColumnLock : function(){
62224
62225     },
62226
62227     onDenyColumnHide : function(){
62228
62229     },
62230
62231     handleHdMenuClick : function(item){
62232         var index = this.hdCtxIndex;
62233         var cm = this.cm, ds = this.ds;
62234         switch(item.id){
62235             case "asc":
62236                 ds.sort(cm.getDataIndex(index), "ASC");
62237                 break;
62238             case "desc":
62239                 ds.sort(cm.getDataIndex(index), "DESC");
62240                 break;
62241             case "lock":
62242                 var lc = cm.getLockedCount();
62243                 if(cm.getColumnCount(true) <= lc+1){
62244                     this.onDenyColumnLock();
62245                     return;
62246                 }
62247                 if(lc != index){
62248                     cm.setLocked(index, true, true);
62249                     cm.moveColumn(index, lc);
62250                     this.grid.fireEvent("columnmove", index, lc);
62251                 }else{
62252                     cm.setLocked(index, true);
62253                 }
62254             break;
62255             case "unlock":
62256                 var lc = cm.getLockedCount();
62257                 if((lc-1) != index){
62258                     cm.setLocked(index, false, true);
62259                     cm.moveColumn(index, lc-1);
62260                     this.grid.fireEvent("columnmove", index, lc-1);
62261                 }else{
62262                     cm.setLocked(index, false);
62263                 }
62264             break;
62265             case 'wider': // used to expand cols on touch..
62266             case 'narrow':
62267                 var cw = cm.getColumnWidth(index);
62268                 cw += (item.id == 'wider' ? 1 : -1) * 50;
62269                 cw = Math.max(0, cw);
62270                 cw = Math.min(cw,4000);
62271                 cm.setColumnWidth(index, cw);
62272                 break;
62273                 
62274             default:
62275                 index = cm.getIndexById(item.id.substr(4));
62276                 if(index != -1){
62277                     if(item.checked && cm.getColumnCount(true) <= 1){
62278                         this.onDenyColumnHide();
62279                         return false;
62280                     }
62281                     cm.setHidden(index, item.checked);
62282                 }
62283         }
62284         return true;
62285     },
62286
62287     beforeColMenuShow : function(){
62288         var cm = this.cm,  colCount = cm.getColumnCount();
62289         this.colMenu.removeAll();
62290         
62291         var items = [];
62292         for(var i = 0; i < colCount; i++){
62293             items.push({
62294                 id: "col-"+cm.getColumnId(i),
62295                 text: cm.getColumnHeader(i),
62296                 checked: !cm.isHidden(i),
62297                 hideOnClick:false
62298             });
62299         }
62300         
62301         if (this.grid.sortColMenu) {
62302             items.sort(function(a,b) {
62303                 if (a.text == b.text) {
62304                     return 0;
62305                 }
62306                 return a.text.toUpperCase() > b.text.toUpperCase() ? 1 : -1;
62307             });
62308         }
62309         
62310         for(var i = 0; i < colCount; i++){
62311             this.colMenu.add(new Roo.menu.CheckItem(items[i]));
62312         }
62313     },
62314
62315     handleHdCtx : function(g, index, e){
62316         e.stopEvent();
62317         var hd = this.getHeaderCell(index);
62318         this.hdCtxIndex = index;
62319         var ms = this.hmenu.items, cm = this.cm;
62320         ms.get("asc").setDisabled(!cm.isSortable(index));
62321         ms.get("desc").setDisabled(!cm.isSortable(index));
62322         if(this.grid.enableColLock !== false){
62323             ms.get("lock").setDisabled(cm.isLocked(index));
62324             ms.get("unlock").setDisabled(!cm.isLocked(index));
62325         }
62326         this.hmenu.show(hd, "tl-bl");
62327     },
62328
62329     handleHdOver : function(e){
62330         var hd = this.findHeaderCell(e.getTarget());
62331         if(hd && !this.headersDisabled){
62332             if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
62333                this.fly(hd).addClass("x-grid-hd-over");
62334             }
62335         }
62336     },
62337
62338     handleHdOut : function(e){
62339         var hd = this.findHeaderCell(e.getTarget());
62340         if(hd){
62341             this.fly(hd).removeClass("x-grid-hd-over");
62342         }
62343     },
62344
62345     handleSplitDblClick : function(e, t){
62346         var i = this.getCellIndex(t);
62347         if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
62348             this.autoSizeColumn(i, true);
62349             this.layout();
62350         }
62351     },
62352
62353     render : function(){
62354
62355         var cm = this.cm;
62356         var colCount = cm.getColumnCount();
62357
62358         if(this.grid.monitorWindowResize === true){
62359             Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
62360         }
62361         var header = this.renderHeaders();
62362         var body = this.templates.body.apply({rows:""});
62363         var html = this.templates.master.apply({
62364             lockedBody: body,
62365             body: body,
62366             lockedHeader: header[0],
62367             header: header[1]
62368         });
62369
62370         //this.updateColumns();
62371
62372         this.grid.getGridEl().dom.innerHTML = html;
62373
62374         this.initElements();
62375         
62376         // a kludge to fix the random scolling effect in webkit
62377         this.el.on("scroll", function() {
62378             this.el.dom.scrollTop=0; // hopefully not recursive..
62379         },this);
62380
62381         this.scroller.on("scroll", this.handleScroll, this);
62382         this.lockedBody.on("mousewheel", this.handleWheel, this);
62383         this.mainBody.on("mousewheel", this.handleWheel, this);
62384
62385         this.mainHd.on("mouseover", this.handleHdOver, this);
62386         this.mainHd.on("mouseout", this.handleHdOut, this);
62387         this.mainHd.on("dblclick", this.handleSplitDblClick, this,
62388                 {delegate: "."+this.splitClass});
62389
62390         this.lockedHd.on("mouseover", this.handleHdOver, this);
62391         this.lockedHd.on("mouseout", this.handleHdOut, this);
62392         this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
62393                 {delegate: "."+this.splitClass});
62394
62395         if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
62396             new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
62397         }
62398
62399         this.updateSplitters();
62400
62401         if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
62402             new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
62403             new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
62404         }
62405
62406         if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
62407             this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
62408             this.hmenu.add(
62409                 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
62410                 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
62411             );
62412             if(this.grid.enableColLock !== false){
62413                 this.hmenu.add('-',
62414                     {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
62415                     {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
62416                 );
62417             }
62418             if (Roo.isTouch) {
62419                  this.hmenu.add('-',
62420                     {id:"wider", text: this.columnsWiderText},
62421                     {id:"narrow", text: this.columnsNarrowText }
62422                 );
62423                 
62424                  
62425             }
62426             
62427             if(this.grid.enableColumnHide !== false){
62428
62429                 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
62430                 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
62431                 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
62432
62433                 this.hmenu.add('-',
62434                     {id:"columns", text: this.columnsText, menu: this.colMenu}
62435                 );
62436             }
62437             this.hmenu.on("itemclick", this.handleHdMenuClick, this);
62438
62439             this.grid.on("headercontextmenu", this.handleHdCtx, this);
62440         }
62441
62442         if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
62443             this.dd = new Roo.grid.GridDragZone(this.grid, {
62444                 ddGroup : this.grid.ddGroup || 'GridDD'
62445             });
62446             
62447         }
62448
62449         /*
62450         for(var i = 0; i < colCount; i++){
62451             if(cm.isHidden(i)){
62452                 this.hideColumn(i);
62453             }
62454             if(cm.config[i].align){
62455                 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
62456                 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
62457             }
62458         }*/
62459         
62460         this.updateHeaderSortState();
62461
62462         this.beforeInitialResize();
62463         this.layout(true);
62464
62465         // two part rendering gives faster view to the user
62466         this.renderPhase2.defer(1, this);
62467     },
62468
62469     renderPhase2 : function(){
62470         // render the rows now
62471         this.refresh();
62472         if(this.grid.autoSizeColumns){
62473             this.autoSizeColumns();
62474         }
62475     },
62476
62477     beforeInitialResize : function(){
62478
62479     },
62480
62481     onColumnSplitterMoved : function(i, w){
62482         this.userResized = true;
62483         var cm = this.grid.colModel;
62484         cm.setColumnWidth(i, w, true);
62485         var cid = cm.getColumnId(i);
62486         this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
62487         this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
62488         this.updateSplitters();
62489         this.layout();
62490         this.grid.fireEvent("columnresize", i, w);
62491     },
62492
62493     syncRowHeights : function(startIndex, endIndex){
62494         if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
62495             startIndex = startIndex || 0;
62496             var mrows = this.getBodyTable().rows;
62497             var lrows = this.getLockedTable().rows;
62498             var len = mrows.length-1;
62499             endIndex = Math.min(endIndex || len, len);
62500             for(var i = startIndex; i <= endIndex; i++){
62501                 var m = mrows[i], l = lrows[i];
62502                 var h = Math.max(m.offsetHeight, l.offsetHeight);
62503                 m.style.height = l.style.height = h + "px";
62504             }
62505         }
62506     },
62507
62508     layout : function(initialRender, is2ndPass)
62509     {
62510         var g = this.grid;
62511         var auto = g.autoHeight;
62512         var scrollOffset = 16;
62513         var c = g.getGridEl(), cm = this.cm,
62514                 expandCol = g.autoExpandColumn,
62515                 gv = this;
62516         //c.beginMeasure();
62517
62518         if(!c.dom.offsetWidth){ // display:none?
62519             if(initialRender){
62520                 this.lockedWrap.show();
62521                 this.mainWrap.show();
62522             }
62523             return;
62524         }
62525
62526         var hasLock = this.cm.isLocked(0);
62527
62528         var tbh = this.headerPanel.getHeight();
62529         var bbh = this.footerPanel.getHeight();
62530
62531         if(auto){
62532             var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
62533             var newHeight = ch + c.getBorderWidth("tb");
62534             if(g.maxHeight){
62535                 newHeight = Math.min(g.maxHeight, newHeight);
62536             }
62537             c.setHeight(newHeight);
62538         }
62539
62540         if(g.autoWidth){
62541             c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
62542         }
62543
62544         var s = this.scroller;
62545
62546         var csize = c.getSize(true);
62547
62548         this.el.setSize(csize.width, csize.height);
62549
62550         this.headerPanel.setWidth(csize.width);
62551         this.footerPanel.setWidth(csize.width);
62552
62553         var hdHeight = this.mainHd.getHeight();
62554         var vw = csize.width;
62555         var vh = csize.height - (tbh + bbh);
62556
62557         s.setSize(vw, vh);
62558
62559         var bt = this.getBodyTable();
62560         
62561         if(cm.getLockedCount() == cm.config.length){
62562             bt = this.getLockedTable();
62563         }
62564         
62565         var ltWidth = hasLock ?
62566                       Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
62567
62568         var scrollHeight = bt.offsetHeight;
62569         var scrollWidth = ltWidth + bt.offsetWidth;
62570         var vscroll = false, hscroll = false;
62571
62572         this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
62573
62574         var lw = this.lockedWrap, mw = this.mainWrap;
62575         var lb = this.lockedBody, mb = this.mainBody;
62576
62577         setTimeout(function(){
62578             var t = s.dom.offsetTop;
62579             var w = s.dom.clientWidth,
62580                 h = s.dom.clientHeight;
62581
62582             lw.setTop(t);
62583             lw.setSize(ltWidth, h);
62584
62585             mw.setLeftTop(ltWidth, t);
62586             mw.setSize(w-ltWidth, h);
62587
62588             lb.setHeight(h-hdHeight);
62589             mb.setHeight(h-hdHeight);
62590
62591             if(is2ndPass !== true && !gv.userResized && expandCol){
62592                 // high speed resize without full column calculation
62593                 
62594                 var ci = cm.getIndexById(expandCol);
62595                 if (ci < 0) {
62596                     ci = cm.findColumnIndex(expandCol);
62597                 }
62598                 ci = Math.max(0, ci); // make sure it's got at least the first col.
62599                 var expandId = cm.getColumnId(ci);
62600                 var  tw = cm.getTotalWidth(false);
62601                 var currentWidth = cm.getColumnWidth(ci);
62602                 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
62603                 if(currentWidth != cw){
62604                     cm.setColumnWidth(ci, cw, true);
62605                     gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
62606                     gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
62607                     gv.updateSplitters();
62608                     gv.layout(false, true);
62609                 }
62610             }
62611
62612             if(initialRender){
62613                 lw.show();
62614                 mw.show();
62615             }
62616             //c.endMeasure();
62617         }, 10);
62618     },
62619
62620     onWindowResize : function(){
62621         if(!this.grid.monitorWindowResize || this.grid.autoHeight){
62622             return;
62623         }
62624         this.layout();
62625     },
62626
62627     appendFooter : function(parentEl){
62628         return null;
62629     },
62630
62631     sortAscText : "Sort Ascending",
62632     sortDescText : "Sort Descending",
62633     lockText : "Lock Column",
62634     unlockText : "Unlock Column",
62635     columnsText : "Columns",
62636  
62637     columnsWiderText : "Wider",
62638     columnsNarrowText : "Thinner"
62639 });
62640
62641
62642 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
62643     Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
62644     this.proxy.el.addClass('x-grid3-col-dd');
62645 };
62646
62647 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
62648     handleMouseDown : function(e){
62649
62650     },
62651
62652     callHandleMouseDown : function(e){
62653         Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
62654     }
62655 });
62656 /*
62657  * Based on:
62658  * Ext JS Library 1.1.1
62659  * Copyright(c) 2006-2007, Ext JS, LLC.
62660  *
62661  * Originally Released Under LGPL - original licence link has changed is not relivant.
62662  *
62663  * Fork - LGPL
62664  * <script type="text/javascript">
62665  */
62666  /**
62667  * @extends Roo.dd.DDProxy
62668  * @class Roo.grid.SplitDragZone
62669  * Support for Column Header resizing
62670  * @constructor
62671  * @param {Object} config
62672  */
62673 // private
62674 // This is a support class used internally by the Grid components
62675 Roo.grid.SplitDragZone = function(grid, hd, hd2){
62676     this.grid = grid;
62677     this.view = grid.getView();
62678     this.proxy = this.view.resizeProxy;
62679     Roo.grid.SplitDragZone.superclass.constructor.call(
62680         this,
62681         hd, // ID
62682         "gridSplitters" + this.grid.getGridEl().id, // SGROUP
62683         {  // CONFIG
62684             dragElId : Roo.id(this.proxy.dom),
62685             resizeFrame:false
62686         }
62687     );
62688     
62689     this.setHandleElId(Roo.id(hd));
62690     if (hd2 !== false) {
62691         this.setOuterHandleElId(Roo.id(hd2));
62692     }
62693     
62694     this.scroll = false;
62695 };
62696 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
62697     fly: Roo.Element.fly,
62698
62699     b4StartDrag : function(x, y){
62700         this.view.headersDisabled = true;
62701         var h = this.view.mainWrap ? this.view.mainWrap.getHeight() : (
62702                     this.view.headEl.getHeight() + this.view.bodyEl.getHeight()
62703         );
62704         this.proxy.setHeight(h);
62705         
62706         // for old system colWidth really stored the actual width?
62707         // in bootstrap we tried using xs/ms/etc.. to do % sizing?
62708         // which in reality did not work.. - it worked only for fixed sizes
62709         // for resizable we need to use actual sizes.
62710         var w = this.cm.getColumnWidth(this.cellIndex);
62711         if (!this.view.mainWrap) {
62712             // bootstrap.
62713             w = this.view.getHeaderIndex(this.cellIndex).getWidth();
62714         }
62715         
62716         
62717         
62718         // this was w-this.grid.minColumnWidth;
62719         // doesnt really make sense? - w = thie curren width or the rendered one?
62720         var minw = Math.max(w-this.grid.minColumnWidth, 0);
62721         this.resetConstraints();
62722         this.setXConstraint(minw, 1000);
62723         this.setYConstraint(0, 0);
62724         this.minX = x - minw;
62725         this.maxX = x + 1000;
62726         this.startPos = x;
62727         if (!this.view.mainWrap) { // this is Bootstrap code..
62728             this.getDragEl().style.display='block';
62729         }
62730         
62731         Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
62732     },
62733
62734
62735     handleMouseDown : function(e){
62736         ev = Roo.EventObject.setEvent(e);
62737         var t = this.fly(ev.getTarget());
62738         if(t.hasClass("x-grid-split")){
62739             this.cellIndex = this.view.getCellIndex(t.dom);
62740             this.split = t.dom;
62741             this.cm = this.grid.colModel;
62742             if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
62743                 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
62744             }
62745         }
62746     },
62747
62748     endDrag : function(e){
62749         this.view.headersDisabled = false;
62750         var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
62751         var diff = endX - this.startPos;
62752         // 
62753         var w = this.cm.getColumnWidth(this.cellIndex);
62754         if (!this.view.mainWrap) {
62755             w = 0;
62756         }
62757         this.view.onColumnSplitterMoved(this.cellIndex, w+diff);
62758     },
62759
62760     autoOffset : function(){
62761         this.setDelta(0,0);
62762     }
62763 });/*
62764  * Based on:
62765  * Ext JS Library 1.1.1
62766  * Copyright(c) 2006-2007, Ext JS, LLC.
62767  *
62768  * Originally Released Under LGPL - original licence link has changed is not relivant.
62769  *
62770  * Fork - LGPL
62771  * <script type="text/javascript">
62772  */
62773  
62774 // private
62775 // This is a support class used internally by the Grid components
62776 Roo.grid.GridDragZone = function(grid, config){
62777     this.view = grid.getView();
62778     Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
62779     if(this.view.lockedBody){
62780         this.setHandleElId(Roo.id(this.view.mainBody.dom));
62781         this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
62782     }
62783     this.scroll = false;
62784     this.grid = grid;
62785     this.ddel = document.createElement('div');
62786     this.ddel.className = 'x-grid-dd-wrap';
62787 };
62788
62789 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
62790     ddGroup : "GridDD",
62791
62792     getDragData : function(e){
62793         var t = Roo.lib.Event.getTarget(e);
62794         var rowIndex = this.view.findRowIndex(t);
62795         var sm = this.grid.selModel;
62796             
62797         //Roo.log(rowIndex);
62798         
62799         if (sm.getSelectedCell) {
62800             // cell selection..
62801             if (!sm.getSelectedCell()) {
62802                 return false;
62803             }
62804             if (rowIndex != sm.getSelectedCell()[0]) {
62805                 return false;
62806             }
62807         
62808         }
62809         if (sm.getSelections && sm.getSelections().length < 1) {
62810             return false;
62811         }
62812         
62813         
62814         // before it used to all dragging of unseleted... - now we dont do that.
62815         if(rowIndex !== false){
62816             
62817             // if editorgrid.. 
62818             
62819             
62820             //Roo.log([ sm.getSelectedCell() ? sm.getSelectedCell()[0] : 'NO' , rowIndex ]);
62821                
62822             //if(!sm.isSelected(rowIndex) || e.hasModifier()){
62823               //  
62824             //}
62825             if (e.hasModifier()){
62826                 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
62827             }
62828             
62829             Roo.log("getDragData");
62830             
62831             return {
62832                 grid: this.grid,
62833                 ddel: this.ddel,
62834                 rowIndex: rowIndex,
62835                 selections: sm.getSelections ? sm.getSelections() : (
62836                     sm.getSelectedCell() ? [ this.grid.ds.getAt(sm.getSelectedCell()[0]) ] : [])
62837             };
62838         }
62839         return false;
62840     },
62841     
62842     
62843     onInitDrag : function(e){
62844         var data = this.dragData;
62845         this.ddel.innerHTML = this.grid.getDragDropText();
62846         this.proxy.update(this.ddel);
62847         // fire start drag?
62848     },
62849
62850     afterRepair : function(){
62851         this.dragging = false;
62852     },
62853
62854     getRepairXY : function(e, data){
62855         return false;
62856     },
62857
62858     onEndDrag : function(data, e){
62859         // fire end drag?
62860     },
62861
62862     onValidDrop : function(dd, e, id){
62863         // fire drag drop?
62864         this.hideProxy();
62865     },
62866
62867     beforeInvalidDrop : function(e, id){
62868
62869     }
62870 });/*
62871  * Based on:
62872  * Ext JS Library 1.1.1
62873  * Copyright(c) 2006-2007, Ext JS, LLC.
62874  *
62875  * Originally Released Under LGPL - original licence link has changed is not relivant.
62876  *
62877  * Fork - LGPL
62878  * <script type="text/javascript">
62879  */
62880  
62881
62882 /**
62883  * @class Roo.grid.ColumnModel
62884  * @extends Roo.util.Observable
62885  * This is the default implementation of a ColumnModel used by the Grid. It defines
62886  * the columns in the grid.
62887  * <br>Usage:<br>
62888  <pre><code>
62889  var colModel = new Roo.grid.ColumnModel([
62890         {header: "Ticker", width: 60, sortable: true, locked: true},
62891         {header: "Company Name", width: 150, sortable: true},
62892         {header: "Market Cap.", width: 100, sortable: true},
62893         {header: "$ Sales", width: 100, sortable: true, renderer: money},
62894         {header: "Employees", width: 100, sortable: true, resizable: false}
62895  ]);
62896  </code></pre>
62897  * <p>
62898  
62899  * The config options listed for this class are options which may appear in each
62900  * individual column definition.
62901  * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
62902  * @constructor
62903  * @param {Object} config An Array of column config objects. See this class's
62904  * config objects for details.
62905 */
62906 Roo.grid.ColumnModel = function(config){
62907         /**
62908      * The config passed into the constructor
62909      */
62910     this.config = []; //config;
62911     this.lookup = {};
62912
62913     // if no id, create one
62914     // if the column does not have a dataIndex mapping,
62915     // map it to the order it is in the config
62916     for(var i = 0, len = config.length; i < len; i++){
62917         this.addColumn(config[i]);
62918         
62919     }
62920
62921     /**
62922      * The width of columns which have no width specified (defaults to 100)
62923      * @type Number
62924      */
62925     this.defaultWidth = 100;
62926
62927     /**
62928      * Default sortable of columns which have no sortable specified (defaults to false)
62929      * @type Boolean
62930      */
62931     this.defaultSortable = false;
62932
62933     this.addEvents({
62934         /**
62935              * @event widthchange
62936              * Fires when the width of a column changes.
62937              * @param {ColumnModel} this
62938              * @param {Number} columnIndex The column index
62939              * @param {Number} newWidth The new width
62940              */
62941             "widthchange": true,
62942         /**
62943              * @event headerchange
62944              * Fires when the text of a header changes.
62945              * @param {ColumnModel} this
62946              * @param {Number} columnIndex The column index
62947              * @param {Number} newText The new header text
62948              */
62949             "headerchange": true,
62950         /**
62951              * @event hiddenchange
62952              * Fires when a column is hidden or "unhidden".
62953              * @param {ColumnModel} this
62954              * @param {Number} columnIndex The column index
62955              * @param {Boolean} hidden true if hidden, false otherwise
62956              */
62957             "hiddenchange": true,
62958             /**
62959          * @event columnmoved
62960          * Fires when a column is moved.
62961          * @param {ColumnModel} this
62962          * @param {Number} oldIndex
62963          * @param {Number} newIndex
62964          */
62965         "columnmoved" : true,
62966         /**
62967          * @event columlockchange
62968          * Fires when a column's locked state is changed
62969          * @param {ColumnModel} this
62970          * @param {Number} colIndex
62971          * @param {Boolean} locked true if locked
62972          */
62973         "columnlockchange" : true
62974     });
62975     Roo.grid.ColumnModel.superclass.constructor.call(this);
62976 };
62977 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
62978     /**
62979      * @cfg {String} header The header text to display in the Grid view.
62980      */
62981         /**
62982      * @cfg {String} xsHeader Header at Bootsrap Extra Small width (default for all)
62983      */
62984         /**
62985      * @cfg {String} smHeader Header at Bootsrap Small width
62986      */
62987         /**
62988      * @cfg {String} mdHeader Header at Bootsrap Medium width
62989      */
62990         /**
62991      * @cfg {String} lgHeader Header at Bootsrap Large width
62992      */
62993         /**
62994      * @cfg {String} xlHeader Header at Bootsrap extra Large width
62995      */
62996     /**
62997      * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
62998      * {@link Roo.data.Record} definition from which to draw the column's value. If not
62999      * specified, the column's index is used as an index into the Record's data Array.
63000      */
63001     /**
63002      * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
63003      * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
63004      */
63005     /**
63006      * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
63007      * Defaults to the value of the {@link #defaultSortable} property.
63008      * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
63009      */
63010     /**
63011      * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid.  Defaults to false.
63012      */
63013     /**
63014      * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed.  Defaults to false.
63015      */
63016     /**
63017      * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
63018      */
63019     /**
63020      * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
63021      */
63022     /**
63023      * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
63024      * given the cell's data value. See {@link #setRenderer}. If not specified, the
63025      * default renderer returns the escaped data value. If an object is returned (bootstrap only)
63026      * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
63027      */
63028        /**
63029      * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor 
63030      */
63031     /**
63032      * @cfg {String} align (Optional) Set the CSS text-align property of the column.  Defaults to undefined.
63033      */
63034     /**
63035      * @cfg {String} valign (Optional) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc).  Defaults to undefined.
63036      */
63037     /**
63038      * @cfg {String} cursor (Optional)
63039      */
63040     /**
63041      * @cfg {String} tooltip (Optional)
63042      */
63043     /**
63044      * @cfg {Number} xs (Optional) can be '0' for hidden at this size (number less than 12)
63045      */
63046     /**
63047      * @cfg {Number} sm (Optional) can be '0' for hidden at this size (number less than 12)
63048      */
63049     /**
63050      * @cfg {Number} md (Optional) can be '0' for hidden at this size (number less than 12)
63051      */
63052     /**
63053      * @cfg {Number} lg (Optional) can be '0' for hidden at this size (number less than 12)
63054      */
63055         /**
63056      * @cfg {Number} xl (Optional) can be '0' for hidden at this size (number less than 12)
63057      */
63058     /**
63059      * Returns the id of the column at the specified index.
63060      * @param {Number} index The column index
63061      * @return {String} the id
63062      */
63063     getColumnId : function(index){
63064         return this.config[index].id;
63065     },
63066
63067     /**
63068      * Returns the column for a specified id.
63069      * @param {String} id The column id
63070      * @return {Object} the column
63071      */
63072     getColumnById : function(id){
63073         return this.lookup[id];
63074     },
63075
63076     
63077     /**
63078      * Returns the column Object for a specified dataIndex.
63079      * @param {String} dataIndex The column dataIndex
63080      * @return {Object|Boolean} the column or false if not found
63081      */
63082     getColumnByDataIndex: function(dataIndex){
63083         var index = this.findColumnIndex(dataIndex);
63084         return index > -1 ? this.config[index] : false;
63085     },
63086     
63087     /**
63088      * Returns the index for a specified column id.
63089      * @param {String} id The column id
63090      * @return {Number} the index, or -1 if not found
63091      */
63092     getIndexById : function(id){
63093         for(var i = 0, len = this.config.length; i < len; i++){
63094             if(this.config[i].id == id){
63095                 return i;
63096             }
63097         }
63098         return -1;
63099     },
63100     
63101     /**
63102      * Returns the index for a specified column dataIndex.
63103      * @param {String} dataIndex The column dataIndex
63104      * @return {Number} the index, or -1 if not found
63105      */
63106     
63107     findColumnIndex : function(dataIndex){
63108         for(var i = 0, len = this.config.length; i < len; i++){
63109             if(this.config[i].dataIndex == dataIndex){
63110                 return i;
63111             }
63112         }
63113         return -1;
63114     },
63115     
63116     
63117     moveColumn : function(oldIndex, newIndex){
63118         var c = this.config[oldIndex];
63119         this.config.splice(oldIndex, 1);
63120         this.config.splice(newIndex, 0, c);
63121         this.dataMap = null;
63122         this.fireEvent("columnmoved", this, oldIndex, newIndex);
63123     },
63124
63125     isLocked : function(colIndex){
63126         return this.config[colIndex].locked === true;
63127     },
63128
63129     setLocked : function(colIndex, value, suppressEvent){
63130         if(this.isLocked(colIndex) == value){
63131             return;
63132         }
63133         this.config[colIndex].locked = value;
63134         if(!suppressEvent){
63135             this.fireEvent("columnlockchange", this, colIndex, value);
63136         }
63137     },
63138
63139     getTotalLockedWidth : function(){
63140         var totalWidth = 0;
63141         for(var i = 0; i < this.config.length; i++){
63142             if(this.isLocked(i) && !this.isHidden(i)){
63143                 this.totalWidth += this.getColumnWidth(i);
63144             }
63145         }
63146         return totalWidth;
63147     },
63148
63149     getLockedCount : function(){
63150         for(var i = 0, len = this.config.length; i < len; i++){
63151             if(!this.isLocked(i)){
63152                 return i;
63153             }
63154         }
63155         
63156         return this.config.length;
63157     },
63158
63159     /**
63160      * Returns the number of columns.
63161      * @return {Number}
63162      */
63163     getColumnCount : function(visibleOnly){
63164         if(visibleOnly === true){
63165             var c = 0;
63166             for(var i = 0, len = this.config.length; i < len; i++){
63167                 if(!this.isHidden(i)){
63168                     c++;
63169                 }
63170             }
63171             return c;
63172         }
63173         return this.config.length;
63174     },
63175
63176     /**
63177      * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
63178      * @param {Function} fn
63179      * @param {Object} scope (optional)
63180      * @return {Array} result
63181      */
63182     getColumnsBy : function(fn, scope){
63183         var r = [];
63184         for(var i = 0, len = this.config.length; i < len; i++){
63185             var c = this.config[i];
63186             if(fn.call(scope||this, c, i) === true){
63187                 r[r.length] = c;
63188             }
63189         }
63190         return r;
63191     },
63192
63193     /**
63194      * Returns true if the specified column is sortable.
63195      * @param {Number} col The column index
63196      * @return {Boolean}
63197      */
63198     isSortable : function(col){
63199         if(typeof this.config[col].sortable == "undefined"){
63200             return this.defaultSortable;
63201         }
63202         return this.config[col].sortable;
63203     },
63204
63205     /**
63206      * Returns the rendering (formatting) function defined for the column.
63207      * @param {Number} col The column index.
63208      * @return {Function} The function used to render the cell. See {@link #setRenderer}.
63209      */
63210     getRenderer : function(col){
63211         if(!this.config[col].renderer){
63212             return Roo.grid.ColumnModel.defaultRenderer;
63213         }
63214         return this.config[col].renderer;
63215     },
63216
63217     /**
63218      * Sets the rendering (formatting) function for a column.
63219      * @param {Number} col The column index
63220      * @param {Function} fn The function to use to process the cell's raw data
63221      * to return HTML markup for the grid view. The render function is called with
63222      * the following parameters:<ul>
63223      * <li>Data value.</li>
63224      * <li>Cell metadata. An object in which you may set the following attributes:<ul>
63225      * <li>css A CSS style string to apply to the table cell.</li>
63226      * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
63227      * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
63228      * <li>Row index</li>
63229      * <li>Column index</li>
63230      * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
63231      */
63232     setRenderer : function(col, fn){
63233         this.config[col].renderer = fn;
63234     },
63235
63236     /**
63237      * Returns the width for the specified column.
63238      * @param {Number} col The column index
63239      * @param (optional) {String} gridSize bootstrap width size.
63240      * @return {Number}
63241      */
63242     getColumnWidth : function(col, gridSize)
63243         {
63244                 var cfg = this.config[col];
63245                 
63246                 if (typeof(gridSize) == 'undefined') {
63247                         return cfg.width * 1 || this.defaultWidth;
63248                 }
63249                 if (gridSize === false) { // if we set it..
63250                         return cfg.width || false;
63251                 }
63252                 var sizes = ['xl', 'lg', 'md', 'sm', 'xs'];
63253                 
63254                 for(var i = sizes.indexOf(gridSize); i < sizes.length; i++) {
63255                         if (typeof(cfg[ sizes[i] ] ) == 'undefined') {
63256                                 continue;
63257                         }
63258                         return cfg[ sizes[i] ];
63259                 }
63260                 return 1;
63261                 
63262     },
63263
63264     /**
63265      * Sets the width for a column.
63266      * @param {Number} col The column index
63267      * @param {Number} width The new width
63268      */
63269     setColumnWidth : function(col, width, suppressEvent){
63270         this.config[col].width = width;
63271         this.totalWidth = null;
63272         if(!suppressEvent){
63273              this.fireEvent("widthchange", this, col, width);
63274         }
63275     },
63276
63277     /**
63278      * Returns the total width of all columns.
63279      * @param {Boolean} includeHidden True to include hidden column widths
63280      * @return {Number}
63281      */
63282     getTotalWidth : function(includeHidden){
63283         if(!this.totalWidth){
63284             this.totalWidth = 0;
63285             for(var i = 0, len = this.config.length; i < len; i++){
63286                 if(includeHidden || !this.isHidden(i)){
63287                     this.totalWidth += this.getColumnWidth(i);
63288                 }
63289             }
63290         }
63291         return this.totalWidth;
63292     },
63293
63294     /**
63295      * Returns the header for the specified column.
63296      * @param {Number} col The column index
63297      * @return {String}
63298      */
63299     getColumnHeader : function(col){
63300         return this.config[col].header;
63301     },
63302
63303     /**
63304      * Sets the header for a column.
63305      * @param {Number} col The column index
63306      * @param {String} header The new header
63307      */
63308     setColumnHeader : function(col, header){
63309         this.config[col].header = header;
63310         this.fireEvent("headerchange", this, col, header);
63311     },
63312
63313     /**
63314      * Returns the tooltip for the specified column.
63315      * @param {Number} col The column index
63316      * @return {String}
63317      */
63318     getColumnTooltip : function(col){
63319             return this.config[col].tooltip;
63320     },
63321     /**
63322      * Sets the tooltip for a column.
63323      * @param {Number} col The column index
63324      * @param {String} tooltip The new tooltip
63325      */
63326     setColumnTooltip : function(col, tooltip){
63327             this.config[col].tooltip = tooltip;
63328     },
63329
63330     /**
63331      * Returns the dataIndex for the specified column.
63332      * @param {Number} col The column index
63333      * @return {Number}
63334      */
63335     getDataIndex : function(col){
63336         return this.config[col].dataIndex;
63337     },
63338
63339     /**
63340      * Sets the dataIndex for a column.
63341      * @param {Number} col The column index
63342      * @param {Number} dataIndex The new dataIndex
63343      */
63344     setDataIndex : function(col, dataIndex){
63345         this.config[col].dataIndex = dataIndex;
63346     },
63347
63348     
63349     
63350     /**
63351      * Returns true if the cell is editable.
63352      * @param {Number} colIndex The column index
63353      * @param {Number} rowIndex The row index - this is nto actually used..?
63354      * @return {Boolean}
63355      */
63356     isCellEditable : function(colIndex, rowIndex){
63357         return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
63358     },
63359
63360     /**
63361      * Returns the editor defined for the cell/column.
63362      * return false or null to disable editing.
63363      * @param {Number} colIndex The column index
63364      * @param {Number} rowIndex The row index
63365      * @return {Object}
63366      */
63367     getCellEditor : function(colIndex, rowIndex){
63368         return this.config[colIndex].editor;
63369     },
63370
63371     /**
63372      * Sets if a column is editable.
63373      * @param {Number} col The column index
63374      * @param {Boolean} editable True if the column is editable
63375      */
63376     setEditable : function(col, editable){
63377         this.config[col].editable = editable;
63378     },
63379
63380
63381     /**
63382      * Returns true if the column is hidden.
63383      * @param {Number} colIndex The column index
63384      * @return {Boolean}
63385      */
63386     isHidden : function(colIndex){
63387         return this.config[colIndex].hidden;
63388     },
63389
63390
63391     /**
63392      * Returns true if the column width cannot be changed
63393      */
63394     isFixed : function(colIndex){
63395         return this.config[colIndex].fixed;
63396     },
63397
63398     /**
63399      * Returns true if the column can be resized
63400      * @return {Boolean}
63401      */
63402     isResizable : function(colIndex){
63403         return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
63404     },
63405     /**
63406      * Sets if a column is hidden.
63407      * @param {Number} colIndex The column index
63408      * @param {Boolean} hidden True if the column is hidden
63409      */
63410     setHidden : function(colIndex, hidden){
63411         this.config[colIndex].hidden = hidden;
63412         this.totalWidth = null;
63413         this.fireEvent("hiddenchange", this, colIndex, hidden);
63414     },
63415
63416     /**
63417      * Sets the editor for a column.
63418      * @param {Number} col The column index
63419      * @param {Object} editor The editor object
63420      */
63421     setEditor : function(col, editor){
63422         this.config[col].editor = editor;
63423     },
63424     /**
63425      * Add a column (experimental...) - defaults to adding to the end..
63426      * @param {Object} config 
63427     */
63428     addColumn : function(c)
63429     {
63430     
63431         var i = this.config.length;
63432         this.config[i] = c;
63433         
63434         if(typeof c.dataIndex == "undefined"){
63435             c.dataIndex = i;
63436         }
63437         if(typeof c.renderer == "string"){
63438             c.renderer = Roo.util.Format[c.renderer];
63439         }
63440         if(typeof c.id == "undefined"){
63441             c.id = Roo.id();
63442         }
63443         if(c.editor && c.editor.xtype){
63444             c.editor  = Roo.factory(c.editor, Roo.grid);
63445         }
63446         if(c.editor && c.editor.isFormField){
63447             c.editor = new Roo.grid.GridEditor(c.editor);
63448         }
63449         this.lookup[c.id] = c;
63450     }
63451     
63452 });
63453
63454 Roo.grid.ColumnModel.defaultRenderer = function(value)
63455 {
63456     if(typeof value == "object") {
63457         return value;
63458     }
63459         if(typeof value == "string" && value.length < 1){
63460             return "&#160;";
63461         }
63462     
63463         return String.format("{0}", value);
63464 };
63465
63466 // Alias for backwards compatibility
63467 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
63468 /*
63469  * Based on:
63470  * Ext JS Library 1.1.1
63471  * Copyright(c) 2006-2007, Ext JS, LLC.
63472  *
63473  * Originally Released Under LGPL - original licence link has changed is not relivant.
63474  *
63475  * Fork - LGPL
63476  * <script type="text/javascript">
63477  */
63478
63479 /**
63480  * @class Roo.grid.AbstractSelectionModel
63481  * @extends Roo.util.Observable
63482  * @abstract
63483  * Abstract base class for grid SelectionModels.  It provides the interface that should be
63484  * implemented by descendant classes.  This class should not be directly instantiated.
63485  * @constructor
63486  */
63487 Roo.grid.AbstractSelectionModel = function(){
63488     this.locked = false;
63489     Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
63490 };
63491
63492 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable,  {
63493     /** @ignore Called by the grid automatically. Do not call directly. */
63494     init : function(grid){
63495         this.grid = grid;
63496         this.initEvents();
63497     },
63498
63499     /**
63500      * Locks the selections.
63501      */
63502     lock : function(){
63503         this.locked = true;
63504     },
63505
63506     /**
63507      * Unlocks the selections.
63508      */
63509     unlock : function(){
63510         this.locked = false;
63511     },
63512
63513     /**
63514      * Returns true if the selections are locked.
63515      * @return {Boolean}
63516      */
63517     isLocked : function(){
63518         return this.locked;
63519     }
63520 });/*
63521  * Based on:
63522  * Ext JS Library 1.1.1
63523  * Copyright(c) 2006-2007, Ext JS, LLC.
63524  *
63525  * Originally Released Under LGPL - original licence link has changed is not relivant.
63526  *
63527  * Fork - LGPL
63528  * <script type="text/javascript">
63529  */
63530 /**
63531  * @extends Roo.grid.AbstractSelectionModel
63532  * @class Roo.grid.RowSelectionModel
63533  * The default SelectionModel used by {@link Roo.grid.Grid}.
63534  * It supports multiple selections and keyboard selection/navigation. 
63535  * @constructor
63536  * @param {Object} config
63537  */
63538 Roo.grid.RowSelectionModel = function(config){
63539     Roo.apply(this, config);
63540     this.selections = new Roo.util.MixedCollection(false, function(o){
63541         return o.id;
63542     });
63543
63544     this.last = false;
63545     this.lastActive = false;
63546
63547     this.addEvents({
63548         /**
63549         * @event selectionchange
63550         * Fires when the selection changes
63551         * @param {SelectionModel} this
63552         */
63553        "selectionchange" : true,
63554        /**
63555         * @event afterselectionchange
63556         * Fires after the selection changes (eg. by key press or clicking)
63557         * @param {SelectionModel} this
63558         */
63559        "afterselectionchange" : true,
63560        /**
63561         * @event beforerowselect
63562         * Fires when a row is selected being selected, return false to cancel.
63563         * @param {SelectionModel} this
63564         * @param {Number} rowIndex The selected index
63565         * @param {Boolean} keepExisting False if other selections will be cleared
63566         */
63567        "beforerowselect" : true,
63568        /**
63569         * @event rowselect
63570         * Fires when a row is selected.
63571         * @param {SelectionModel} this
63572         * @param {Number} rowIndex The selected index
63573         * @param {Roo.data.Record} r The record
63574         */
63575        "rowselect" : true,
63576        /**
63577         * @event rowdeselect
63578         * Fires when a row is deselected.
63579         * @param {SelectionModel} this
63580         * @param {Number} rowIndex The selected index
63581         */
63582         "rowdeselect" : true
63583     });
63584     Roo.grid.RowSelectionModel.superclass.constructor.call(this);
63585     this.locked = false;
63586 };
63587
63588 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel,  {
63589     /**
63590      * @cfg {Boolean} singleSelect
63591      * True to allow selection of only one row at a time (defaults to false)
63592      */
63593     singleSelect : false,
63594
63595     // private
63596     initEvents : function(){
63597
63598         if(!this.grid.enableDragDrop && !this.grid.enableDrag){
63599             this.grid.on("mousedown", this.handleMouseDown, this);
63600         }else{ // allow click to work like normal
63601             this.grid.on("rowclick", this.handleDragableRowClick, this);
63602         }
63603         // bootstrap does not have a view..
63604         var view = this.grid.view ? this.grid.view : this.grid;
63605         this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
63606             "up" : function(e){
63607                 if(!e.shiftKey){
63608                     this.selectPrevious(e.shiftKey);
63609                 }else if(this.last !== false && this.lastActive !== false){
63610                     var last = this.last;
63611                     this.selectRange(this.last,  this.lastActive-1);
63612                     view.focusRow(this.lastActive);
63613                     if(last !== false){
63614                         this.last = last;
63615                     }
63616                 }else{
63617                     this.selectFirstRow();
63618                 }
63619                 this.fireEvent("afterselectionchange", this);
63620             },
63621             "down" : function(e){
63622                 if(!e.shiftKey){
63623                     this.selectNext(e.shiftKey);
63624                 }else if(this.last !== false && this.lastActive !== false){
63625                     var last = this.last;
63626                     this.selectRange(this.last,  this.lastActive+1);
63627                     view.focusRow(this.lastActive);
63628                     if(last !== false){
63629                         this.last = last;
63630                     }
63631                 }else{
63632                     this.selectFirstRow();
63633                 }
63634                 this.fireEvent("afterselectionchange", this);
63635             },
63636             scope: this
63637         });
63638
63639          
63640         view.on("refresh", this.onRefresh, this);
63641         view.on("rowupdated", this.onRowUpdated, this);
63642         view.on("rowremoved", this.onRemove, this);
63643     },
63644
63645     // private
63646     onRefresh : function(){
63647         var ds = this.grid.ds, i, v = this.grid.view;
63648         var s = this.selections;
63649         s.each(function(r){
63650             if((i = ds.indexOfId(r.id)) != -1){
63651                 v.onRowSelect(i);
63652                 s.add(ds.getAt(i)); // updating the selection relate data
63653             }else{
63654                 s.remove(r);
63655             }
63656         });
63657     },
63658
63659     // private
63660     onRemove : function(v, index, r){
63661         this.selections.remove(r);
63662     },
63663
63664     // private
63665     onRowUpdated : function(v, index, r){
63666         if(this.isSelected(r)){
63667             v.onRowSelect(index);
63668         }
63669     },
63670
63671     /**
63672      * Select records.
63673      * @param {Array} records The records to select
63674      * @param {Boolean} keepExisting (optional) True to keep existing selections
63675      */
63676     selectRecords : function(records, keepExisting){
63677         if(!keepExisting){
63678             this.clearSelections();
63679         }
63680         var ds = this.grid.ds;
63681         for(var i = 0, len = records.length; i < len; i++){
63682             this.selectRow(ds.indexOf(records[i]), true);
63683         }
63684     },
63685
63686     /**
63687      * Gets the number of selected rows.
63688      * @return {Number}
63689      */
63690     getCount : function(){
63691         return this.selections.length;
63692     },
63693
63694     /**
63695      * Selects the first row in the grid.
63696      */
63697     selectFirstRow : function(){
63698         this.selectRow(0);
63699     },
63700
63701     /**
63702      * Select the last row.
63703      * @param {Boolean} keepExisting (optional) True to keep existing selections
63704      */
63705     selectLastRow : function(keepExisting){
63706         this.selectRow(this.grid.ds.getCount() - 1, keepExisting);
63707     },
63708
63709     /**
63710      * Selects the row immediately following the last selected row.
63711      * @param {Boolean} keepExisting (optional) True to keep existing selections
63712      */
63713     selectNext : function(keepExisting){
63714         if(this.last !== false && (this.last+1) < this.grid.ds.getCount()){
63715             this.selectRow(this.last+1, keepExisting);
63716             var view = this.grid.view ? this.grid.view : this.grid;
63717             view.focusRow(this.last);
63718         }
63719     },
63720
63721     /**
63722      * Selects the row that precedes the last selected row.
63723      * @param {Boolean} keepExisting (optional) True to keep existing selections
63724      */
63725     selectPrevious : function(keepExisting){
63726         if(this.last){
63727             this.selectRow(this.last-1, keepExisting);
63728             var view = this.grid.view ? this.grid.view : this.grid;
63729             view.focusRow(this.last);
63730         }
63731     },
63732
63733     /**
63734      * Returns the selected records
63735      * @return {Array} Array of selected records
63736      */
63737     getSelections : function(){
63738         return [].concat(this.selections.items);
63739     },
63740
63741     /**
63742      * Returns the first selected record.
63743      * @return {Record}
63744      */
63745     getSelected : function(){
63746         return this.selections.itemAt(0);
63747     },
63748
63749
63750     /**
63751      * Clears all selections.
63752      */
63753     clearSelections : function(fast){
63754         if(this.locked) {
63755             return;
63756         }
63757         if(fast !== true){
63758             var ds = this.grid.ds;
63759             var s = this.selections;
63760             s.each(function(r){
63761                 this.deselectRow(ds.indexOfId(r.id));
63762             }, this);
63763             s.clear();
63764         }else{
63765             this.selections.clear();
63766         }
63767         this.last = false;
63768     },
63769
63770
63771     /**
63772      * Selects all rows.
63773      */
63774     selectAll : function(){
63775         if(this.locked) {
63776             return;
63777         }
63778         this.selections.clear();
63779         for(var i = 0, len = this.grid.ds.getCount(); i < len; i++){
63780             this.selectRow(i, true);
63781         }
63782     },
63783
63784     /**
63785      * Returns True if there is a selection.
63786      * @return {Boolean}
63787      */
63788     hasSelection : function(){
63789         return this.selections.length > 0;
63790     },
63791
63792     /**
63793      * Returns True if the specified row is selected.
63794      * @param {Number/Record} record The record or index of the record to check
63795      * @return {Boolean}
63796      */
63797     isSelected : function(index){
63798         var r = typeof index == "number" ? this.grid.ds.getAt(index) : index;
63799         return (r && this.selections.key(r.id) ? true : false);
63800     },
63801
63802     /**
63803      * Returns True if the specified record id is selected.
63804      * @param {String} id The id of record to check
63805      * @return {Boolean}
63806      */
63807     isIdSelected : function(id){
63808         return (this.selections.key(id) ? true : false);
63809     },
63810
63811     // private
63812     handleMouseDown : function(e, t)
63813     {
63814         var view = this.grid.view ? this.grid.view : this.grid;
63815         var rowIndex;
63816         if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
63817             return;
63818         };
63819         if(e.shiftKey && this.last !== false){
63820             var last = this.last;
63821             this.selectRange(last, rowIndex, e.ctrlKey);
63822             this.last = last; // reset the last
63823             view.focusRow(rowIndex);
63824         }else{
63825             var isSelected = this.isSelected(rowIndex);
63826             if(e.button !== 0 && isSelected){
63827                 view.focusRow(rowIndex);
63828             }else if(e.ctrlKey && isSelected){
63829                 this.deselectRow(rowIndex);
63830             }else if(!isSelected){
63831                 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
63832                 view.focusRow(rowIndex);
63833             }
63834         }
63835         this.fireEvent("afterselectionchange", this);
63836     },
63837     // private
63838     handleDragableRowClick :  function(grid, rowIndex, e) 
63839     {
63840         if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
63841             this.selectRow(rowIndex, false);
63842             var view = this.grid.view ? this.grid.view : this.grid;
63843             view.focusRow(rowIndex);
63844              this.fireEvent("afterselectionchange", this);
63845         }
63846     },
63847     
63848     /**
63849      * Selects multiple rows.
63850      * @param {Array} rows Array of the indexes of the row to select
63851      * @param {Boolean} keepExisting (optional) True to keep existing selections
63852      */
63853     selectRows : function(rows, keepExisting){
63854         if(!keepExisting){
63855             this.clearSelections();
63856         }
63857         for(var i = 0, len = rows.length; i < len; i++){
63858             this.selectRow(rows[i], true);
63859         }
63860     },
63861
63862     /**
63863      * Selects a range of rows. All rows in between startRow and endRow are also selected.
63864      * @param {Number} startRow The index of the first row in the range
63865      * @param {Number} endRow The index of the last row in the range
63866      * @param {Boolean} keepExisting (optional) True to retain existing selections
63867      */
63868     selectRange : function(startRow, endRow, keepExisting){
63869         if(this.locked) {
63870             return;
63871         }
63872         if(!keepExisting){
63873             this.clearSelections();
63874         }
63875         if(startRow <= endRow){
63876             for(var i = startRow; i <= endRow; i++){
63877                 this.selectRow(i, true);
63878             }
63879         }else{
63880             for(var i = startRow; i >= endRow; i--){
63881                 this.selectRow(i, true);
63882             }
63883         }
63884     },
63885
63886     /**
63887      * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
63888      * @param {Number} startRow The index of the first row in the range
63889      * @param {Number} endRow The index of the last row in the range
63890      */
63891     deselectRange : function(startRow, endRow, preventViewNotify){
63892         if(this.locked) {
63893             return;
63894         }
63895         for(var i = startRow; i <= endRow; i++){
63896             this.deselectRow(i, preventViewNotify);
63897         }
63898     },
63899
63900     /**
63901      * Selects a row.
63902      * @param {Number} row The index of the row to select
63903      * @param {Boolean} keepExisting (optional) True to keep existing selections
63904      */
63905     selectRow : function(index, keepExisting, preventViewNotify){
63906         if(this.locked || (index < 0 || index >= this.grid.ds.getCount())) {
63907             return;
63908         }
63909         if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
63910             if(!keepExisting || this.singleSelect){
63911                 this.clearSelections();
63912             }
63913             var r = this.grid.ds.getAt(index);
63914             this.selections.add(r);
63915             this.last = this.lastActive = index;
63916             if(!preventViewNotify){
63917                 var view = this.grid.view ? this.grid.view : this.grid;
63918                 view.onRowSelect(index);
63919             }
63920             this.fireEvent("rowselect", this, index, r);
63921             this.fireEvent("selectionchange", this);
63922         }
63923     },
63924
63925     /**
63926      * Deselects a row.
63927      * @param {Number} row The index of the row to deselect
63928      */
63929     deselectRow : function(index, preventViewNotify){
63930         if(this.locked) {
63931             return;
63932         }
63933         if(this.last == index){
63934             this.last = false;
63935         }
63936         if(this.lastActive == index){
63937             this.lastActive = false;
63938         }
63939         var r = this.grid.ds.getAt(index);
63940         this.selections.remove(r);
63941         if(!preventViewNotify){
63942             var view = this.grid.view ? this.grid.view : this.grid;
63943             view.onRowDeselect(index);
63944         }
63945         this.fireEvent("rowdeselect", this, index);
63946         this.fireEvent("selectionchange", this);
63947     },
63948
63949     // private
63950     restoreLast : function(){
63951         if(this._last){
63952             this.last = this._last;
63953         }
63954     },
63955
63956     // private
63957     acceptsNav : function(row, col, cm){
63958         return !cm.isHidden(col) && cm.isCellEditable(col, row);
63959     },
63960
63961     // private
63962     onEditorKey : function(field, e){
63963         var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
63964         if(k == e.TAB){
63965             e.stopEvent();
63966             ed.completeEdit();
63967             if(e.shiftKey){
63968                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
63969             }else{
63970                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
63971             }
63972         }else if(k == e.ENTER && !e.ctrlKey){
63973             e.stopEvent();
63974             ed.completeEdit();
63975             if(e.shiftKey){
63976                 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
63977             }else{
63978                 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
63979             }
63980         }else if(k == e.ESC){
63981             ed.cancelEdit();
63982         }
63983         if(newCell){
63984             g.startEditing(newCell[0], newCell[1]);
63985         }
63986     }
63987 });/*
63988  * Based on:
63989  * Ext JS Library 1.1.1
63990  * Copyright(c) 2006-2007, Ext JS, LLC.
63991  *
63992  * Originally Released Under LGPL - original licence link has changed is not relivant.
63993  *
63994  * Fork - LGPL
63995  * <script type="text/javascript">
63996  */
63997 /**
63998  * @class Roo.grid.CellSelectionModel
63999  * @extends Roo.grid.AbstractSelectionModel
64000  * This class provides the basic implementation for cell selection in a grid.
64001  * @constructor
64002  * @param {Object} config The object containing the configuration of this model.
64003  * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
64004  */
64005 Roo.grid.CellSelectionModel = function(config){
64006     Roo.apply(this, config);
64007
64008     this.selection = null;
64009
64010     this.addEvents({
64011         /**
64012              * @event beforerowselect
64013              * Fires before a cell is selected.
64014              * @param {SelectionModel} this
64015              * @param {Number} rowIndex The selected row index
64016              * @param {Number} colIndex The selected cell index
64017              */
64018             "beforecellselect" : true,
64019         /**
64020              * @event cellselect
64021              * Fires when a cell is selected.
64022              * @param {SelectionModel} this
64023              * @param {Number} rowIndex The selected row index
64024              * @param {Number} colIndex The selected cell index
64025              */
64026             "cellselect" : true,
64027         /**
64028              * @event selectionchange
64029              * Fires when the active selection changes.
64030              * @param {SelectionModel} this
64031              * @param {Object} selection null for no selection or an object (o) with two properties
64032                 <ul>
64033                 <li>o.record: the record object for the row the selection is in</li>
64034                 <li>o.cell: An array of [rowIndex, columnIndex]</li>
64035                 </ul>
64036              */
64037             "selectionchange" : true,
64038         /**
64039              * @event tabend
64040              * Fires when the tab (or enter) was pressed on the last editable cell
64041              * You can use this to trigger add new row.
64042              * @param {SelectionModel} this
64043              */
64044             "tabend" : true,
64045          /**
64046              * @event beforeeditnext
64047              * Fires before the next editable sell is made active
64048              * You can use this to skip to another cell or fire the tabend
64049              *    if you set cell to false
64050              * @param {Object} eventdata object : { cell : [ row, col ] } 
64051              */
64052             "beforeeditnext" : true
64053     });
64054     Roo.grid.CellSelectionModel.superclass.constructor.call(this);
64055 };
64056
64057 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel,  {
64058     
64059     enter_is_tab: false,
64060
64061     /** @ignore */
64062     initEvents : function(){
64063         this.grid.on("mousedown", this.handleMouseDown, this);
64064         this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
64065         var view = this.grid.view;
64066         view.on("refresh", this.onViewChange, this);
64067         view.on("rowupdated", this.onRowUpdated, this);
64068         view.on("beforerowremoved", this.clearSelections, this);
64069         view.on("beforerowsinserted", this.clearSelections, this);
64070         if(this.grid.isEditor){
64071             this.grid.on("beforeedit", this.beforeEdit,  this);
64072         }
64073     },
64074
64075         //private
64076     beforeEdit : function(e){
64077         this.select(e.row, e.column, false, true, e.record);
64078     },
64079
64080         //private
64081     onRowUpdated : function(v, index, r){
64082         if(this.selection && this.selection.record == r){
64083             v.onCellSelect(index, this.selection.cell[1]);
64084         }
64085     },
64086
64087         //private
64088     onViewChange : function(){
64089         this.clearSelections(true);
64090     },
64091
64092         /**
64093          * Returns the currently selected cell,.
64094          * @return {Array} The selected cell (row, column) or null if none selected.
64095          */
64096     getSelectedCell : function(){
64097         return this.selection ? this.selection.cell : null;
64098     },
64099
64100     /**
64101      * Clears all selections.
64102      * @param {Boolean} true to prevent the gridview from being notified about the change.
64103      */
64104     clearSelections : function(preventNotify){
64105         var s = this.selection;
64106         if(s){
64107             if(preventNotify !== true){
64108                 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
64109             }
64110             this.selection = null;
64111             this.fireEvent("selectionchange", this, null);
64112         }
64113     },
64114
64115     /**
64116      * Returns true if there is a selection.
64117      * @return {Boolean}
64118      */
64119     hasSelection : function(){
64120         return this.selection ? true : false;
64121     },
64122
64123     /** @ignore */
64124     handleMouseDown : function(e, t){
64125         var v = this.grid.getView();
64126         if(this.isLocked()){
64127             return;
64128         };
64129         var row = v.findRowIndex(t);
64130         var cell = v.findCellIndex(t);
64131         if(row !== false && cell !== false){
64132             this.select(row, cell);
64133         }
64134     },
64135
64136     /**
64137      * Selects a cell.
64138      * @param {Number} rowIndex
64139      * @param {Number} collIndex
64140      */
64141     select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
64142         if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
64143             this.clearSelections();
64144             r = r || this.grid.dataSource.getAt(rowIndex);
64145             this.selection = {
64146                 record : r,
64147                 cell : [rowIndex, colIndex]
64148             };
64149             if(!preventViewNotify){
64150                 var v = this.grid.getView();
64151                 v.onCellSelect(rowIndex, colIndex);
64152                 if(preventFocus !== true){
64153                     v.focusCell(rowIndex, colIndex);
64154                 }
64155             }
64156             this.fireEvent("cellselect", this, rowIndex, colIndex);
64157             this.fireEvent("selectionchange", this, this.selection);
64158         }
64159     },
64160
64161         //private
64162     isSelectable : function(rowIndex, colIndex, cm){
64163         return !cm.isHidden(colIndex);
64164     },
64165
64166     /** @ignore */
64167     handleKeyDown : function(e){
64168         //Roo.log('Cell Sel Model handleKeyDown');
64169         if(!e.isNavKeyPress()){
64170             return;
64171         }
64172         var g = this.grid, s = this.selection;
64173         if(!s){
64174             e.stopEvent();
64175             var cell = g.walkCells(0, 0, 1, this.isSelectable,  this);
64176             if(cell){
64177                 this.select(cell[0], cell[1]);
64178             }
64179             return;
64180         }
64181         var sm = this;
64182         var walk = function(row, col, step){
64183             return g.walkCells(row, col, step, sm.isSelectable,  sm);
64184         };
64185         var k = e.getKey(), r = s.cell[0], c = s.cell[1];
64186         var newCell;
64187
64188       
64189
64190         switch(k){
64191             case e.TAB:
64192                 // handled by onEditorKey
64193                 if (g.isEditor && g.editing) {
64194                     return;
64195                 }
64196                 if(e.shiftKey) {
64197                     newCell = walk(r, c-1, -1);
64198                 } else {
64199                     newCell = walk(r, c+1, 1);
64200                 }
64201                 break;
64202             
64203             case e.DOWN:
64204                newCell = walk(r+1, c, 1);
64205                 break;
64206             
64207             case e.UP:
64208                 newCell = walk(r-1, c, -1);
64209                 break;
64210             
64211             case e.RIGHT:
64212                 newCell = walk(r, c+1, 1);
64213                 break;
64214             
64215             case e.LEFT:
64216                 newCell = walk(r, c-1, -1);
64217                 break;
64218             
64219             case e.ENTER:
64220                 
64221                 if(g.isEditor && !g.editing){
64222                    g.startEditing(r, c);
64223                    e.stopEvent();
64224                    return;
64225                 }
64226                 
64227                 
64228              break;
64229         };
64230         if(newCell){
64231             this.select(newCell[0], newCell[1]);
64232             e.stopEvent();
64233             
64234         }
64235     },
64236
64237     acceptsNav : function(row, col, cm){
64238         return !cm.isHidden(col) && cm.isCellEditable(col, row);
64239     },
64240     /**
64241      * Selects a cell.
64242      * @param {Number} field (not used) - as it's normally used as a listener
64243      * @param {Number} e - event - fake it by using
64244      *
64245      * var e = Roo.EventObjectImpl.prototype;
64246      * e.keyCode = e.TAB
64247      *
64248      * 
64249      */
64250     onEditorKey : function(field, e){
64251         
64252         var k = e.getKey(),
64253             newCell,
64254             g = this.grid,
64255             ed = g.activeEditor,
64256             forward = false;
64257         ///Roo.log('onEditorKey' + k);
64258         
64259         
64260         if (this.enter_is_tab && k == e.ENTER) {
64261             k = e.TAB;
64262         }
64263         
64264         if(k == e.TAB){
64265             if(e.shiftKey){
64266                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
64267             }else{
64268                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
64269                 forward = true;
64270             }
64271             
64272             e.stopEvent();
64273             
64274         } else if(k == e.ENTER &&  !e.ctrlKey){
64275             ed.completeEdit();
64276             e.stopEvent();
64277             newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
64278         
64279                 } else if(k == e.ESC){
64280             ed.cancelEdit();
64281         }
64282                 
64283         if (newCell) {
64284             var ecall = { cell : newCell, forward : forward };
64285             this.fireEvent('beforeeditnext', ecall );
64286             newCell = ecall.cell;
64287                         forward = ecall.forward;
64288         }
64289                 
64290         if(newCell){
64291             //Roo.log('next cell after edit');
64292             g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
64293         } else if (forward) {
64294             // tabbed past last
64295             this.fireEvent.defer(100, this, ['tabend',this]);
64296         }
64297     }
64298 });/*
64299  * Based on:
64300  * Ext JS Library 1.1.1
64301  * Copyright(c) 2006-2007, Ext JS, LLC.
64302  *
64303  * Originally Released Under LGPL - original licence link has changed is not relivant.
64304  *
64305  * Fork - LGPL
64306  * <script type="text/javascript">
64307  */
64308  
64309 /**
64310  * @class Roo.grid.EditorGrid
64311  * @extends Roo.grid.Grid
64312  * Class for creating and editable grid.
64313  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered - 
64314  * The container MUST have some type of size defined for the grid to fill. The container will be 
64315  * automatically set to position relative if it isn't already.
64316  * @param {Object} dataSource The data model to bind to
64317  * @param {Object} colModel The column model with info about this grid's columns
64318  */
64319 Roo.grid.EditorGrid = function(container, config){
64320     Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
64321     this.getGridEl().addClass("xedit-grid");
64322
64323     if(!this.selModel){
64324         this.selModel = new Roo.grid.CellSelectionModel();
64325     }
64326
64327     this.activeEditor = null;
64328
64329         this.addEvents({
64330             /**
64331              * @event beforeedit
64332              * Fires before cell editing is triggered. The edit event object has the following properties <br />
64333              * <ul style="padding:5px;padding-left:16px;">
64334              * <li>grid - This grid</li>
64335              * <li>record - The record being edited</li>
64336              * <li>field - The field name being edited</li>
64337              * <li>value - The value for the field being edited.</li>
64338              * <li>row - The grid row index</li>
64339              * <li>column - The grid column index</li>
64340              * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
64341              * </ul>
64342              * @param {Object} e An edit event (see above for description)
64343              */
64344             "beforeedit" : true,
64345             /**
64346              * @event afteredit
64347              * Fires after a cell is edited. <br />
64348              * <ul style="padding:5px;padding-left:16px;">
64349              * <li>grid - This grid</li>
64350              * <li>record - The record being edited</li>
64351              * <li>field - The field name being edited</li>
64352              * <li>value - The value being set</li>
64353              * <li>originalValue - The original value for the field, before the edit.</li>
64354              * <li>row - The grid row index</li>
64355              * <li>column - The grid column index</li>
64356              * </ul>
64357              * @param {Object} e An edit event (see above for description)
64358              */
64359             "afteredit" : true,
64360             /**
64361              * @event validateedit
64362              * Fires after a cell is edited, but before the value is set in the record. 
64363          * You can use this to modify the value being set in the field, Return false
64364              * to cancel the change. The edit event object has the following properties <br />
64365              * <ul style="padding:5px;padding-left:16px;">
64366          * <li>editor - This editor</li>
64367              * <li>grid - This grid</li>
64368              * <li>record - The record being edited</li>
64369              * <li>field - The field name being edited</li>
64370              * <li>value - The value being set</li>
64371              * <li>originalValue - The original value for the field, before the edit.</li>
64372              * <li>row - The grid row index</li>
64373              * <li>column - The grid column index</li>
64374              * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
64375              * </ul>
64376              * @param {Object} e An edit event (see above for description)
64377              */
64378             "validateedit" : true
64379         });
64380     this.on("bodyscroll", this.stopEditing,  this);
64381     this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick,  this);
64382 };
64383
64384 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
64385     /**
64386      * @cfg {Number} clicksToEdit
64387      * The number of clicks on a cell required to display the cell's editor (defaults to 2)
64388      */
64389     clicksToEdit: 2,
64390
64391     // private
64392     isEditor : true,
64393     // private
64394     trackMouseOver: false, // causes very odd FF errors
64395
64396     onCellDblClick : function(g, row, col){
64397         this.startEditing(row, col);
64398     },
64399
64400     onEditComplete : function(ed, value, startValue){
64401         this.editing = false;
64402         this.activeEditor = null;
64403         ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
64404         var r = ed.record;
64405         var field = this.colModel.getDataIndex(ed.col);
64406         var e = {
64407             grid: this,
64408             record: r,
64409             field: field,
64410             originalValue: startValue,
64411             value: value,
64412             row: ed.row,
64413             column: ed.col,
64414             cancel:false,
64415             editor: ed
64416         };
64417         var cell = Roo.get(this.view.getCell(ed.row,ed.col));
64418         cell.show();
64419           
64420         if(String(value) !== String(startValue)){
64421             
64422             if(this.fireEvent("validateedit", e) !== false && !e.cancel){
64423                 r.set(field, e.value);
64424                 // if we are dealing with a combo box..
64425                 // then we also set the 'name' colum to be the displayField
64426                 if (ed.field.displayField && ed.field.name) {
64427                     r.set(ed.field.name, ed.field.el.dom.value);
64428                 }
64429                 
64430                 delete e.cancel; //?? why!!!
64431                 this.fireEvent("afteredit", e);
64432             }
64433         } else {
64434             this.fireEvent("afteredit", e); // always fire it!
64435         }
64436         this.view.focusCell(ed.row, ed.col);
64437     },
64438
64439     /**
64440      * Starts editing the specified for the specified row/column
64441      * @param {Number} rowIndex
64442      * @param {Number} colIndex
64443      */
64444     startEditing : function(row, col){
64445         this.stopEditing();
64446         if(this.colModel.isCellEditable(col, row)){
64447             this.view.ensureVisible(row, col, true);
64448           
64449             var r = this.dataSource.getAt(row);
64450             var field = this.colModel.getDataIndex(col);
64451             var cell = Roo.get(this.view.getCell(row,col));
64452             var e = {
64453                 grid: this,
64454                 record: r,
64455                 field: field,
64456                 value: r.data[field],
64457                 row: row,
64458                 column: col,
64459                 cancel:false 
64460             };
64461             if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
64462                 this.editing = true;
64463                 var ed = this.colModel.getCellEditor(col, row);
64464                 
64465                 if (!ed) {
64466                     return;
64467                 }
64468                 if(!ed.rendered){
64469                     ed.render(ed.parentEl || document.body);
64470                 }
64471                 ed.field.reset();
64472                
64473                 cell.hide();
64474                 
64475                 (function(){ // complex but required for focus issues in safari, ie and opera
64476                     ed.row = row;
64477                     ed.col = col;
64478                     ed.record = r;
64479                     ed.on("complete",   this.onEditComplete,        this,       {single: true});
64480                     ed.on("specialkey", this.selModel.onEditorKey,  this.selModel);
64481                     this.activeEditor = ed;
64482                     var v = r.data[field];
64483                     ed.startEdit(this.view.getCell(row, col), v);
64484                     // combo's with 'displayField and name set
64485                     if (ed.field.displayField && ed.field.name) {
64486                         ed.field.el.dom.value = r.data[ed.field.name];
64487                     }
64488                     
64489                     
64490                 }).defer(50, this);
64491             }
64492         }
64493     },
64494         
64495     /**
64496      * Stops any active editing
64497      */
64498     stopEditing : function(){
64499         if(this.activeEditor){
64500             this.activeEditor.completeEdit();
64501         }
64502         this.activeEditor = null;
64503     },
64504         
64505          /**
64506      * Called to get grid's drag proxy text, by default returns this.ddText.
64507      * @return {String}
64508      */
64509     getDragDropText : function(){
64510         var count = this.selModel.getSelectedCell() ? 1 : 0;
64511         return String.format(this.ddText, count, count == 1 ? '' : 's');
64512     }
64513         
64514 });/*
64515  * Based on:
64516  * Ext JS Library 1.1.1
64517  * Copyright(c) 2006-2007, Ext JS, LLC.
64518  *
64519  * Originally Released Under LGPL - original licence link has changed is not relivant.
64520  *
64521  * Fork - LGPL
64522  * <script type="text/javascript">
64523  */
64524
64525 // private - not really -- you end up using it !
64526 // This is a support class used internally by the Grid components
64527
64528 /**
64529  * @class Roo.grid.GridEditor
64530  * @extends Roo.Editor
64531  * Class for creating and editable grid elements.
64532  * @param {Object} config any settings (must include field)
64533  */
64534 Roo.grid.GridEditor = function(field, config){
64535     if (!config && field.field) {
64536         config = field;
64537         field = Roo.factory(config.field, Roo.form);
64538     }
64539     Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
64540     field.monitorTab = false;
64541 };
64542
64543 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
64544     
64545     /**
64546      * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
64547      */
64548     
64549     alignment: "tl-tl",
64550     autoSize: "width",
64551     hideEl : false,
64552     cls: "x-small-editor x-grid-editor",
64553     shim:false,
64554     shadow:"frame"
64555 });/*
64556  * Based on:
64557  * Ext JS Library 1.1.1
64558  * Copyright(c) 2006-2007, Ext JS, LLC.
64559  *
64560  * Originally Released Under LGPL - original licence link has changed is not relivant.
64561  *
64562  * Fork - LGPL
64563  * <script type="text/javascript">
64564  */
64565   
64566
64567   
64568 Roo.grid.PropertyRecord = Roo.data.Record.create([
64569     {name:'name',type:'string'},  'value'
64570 ]);
64571
64572
64573 Roo.grid.PropertyStore = function(grid, source){
64574     this.grid = grid;
64575     this.store = new Roo.data.Store({
64576         recordType : Roo.grid.PropertyRecord
64577     });
64578     this.store.on('update', this.onUpdate,  this);
64579     if(source){
64580         this.setSource(source);
64581     }
64582     Roo.grid.PropertyStore.superclass.constructor.call(this);
64583 };
64584
64585
64586
64587 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
64588     setSource : function(o){
64589         this.source = o;
64590         this.store.removeAll();
64591         var data = [];
64592         for(var k in o){
64593             if(this.isEditableValue(o[k])){
64594                 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
64595             }
64596         }
64597         this.store.loadRecords({records: data}, {}, true);
64598     },
64599
64600     onUpdate : function(ds, record, type){
64601         if(type == Roo.data.Record.EDIT){
64602             var v = record.data['value'];
64603             var oldValue = record.modified['value'];
64604             if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
64605                 this.source[record.id] = v;
64606                 record.commit();
64607                 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
64608             }else{
64609                 record.reject();
64610             }
64611         }
64612     },
64613
64614     getProperty : function(row){
64615        return this.store.getAt(row);
64616     },
64617
64618     isEditableValue: function(val){
64619         if(val && val instanceof Date){
64620             return true;
64621         }else if(typeof val == 'object' || typeof val == 'function'){
64622             return false;
64623         }
64624         return true;
64625     },
64626
64627     setValue : function(prop, value){
64628         this.source[prop] = value;
64629         this.store.getById(prop).set('value', value);
64630     },
64631
64632     getSource : function(){
64633         return this.source;
64634     }
64635 });
64636
64637 Roo.grid.PropertyColumnModel = function(grid, store){
64638     this.grid = grid;
64639     var g = Roo.grid;
64640     g.PropertyColumnModel.superclass.constructor.call(this, [
64641         {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
64642         {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
64643     ]);
64644     this.store = store;
64645     this.bselect = Roo.DomHelper.append(document.body, {
64646         tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
64647             {tag: 'option', value: 'true', html: 'true'},
64648             {tag: 'option', value: 'false', html: 'false'}
64649         ]
64650     });
64651     Roo.id(this.bselect);
64652     var f = Roo.form;
64653     this.editors = {
64654         'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
64655         'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
64656         'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
64657         'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
64658         'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
64659     };
64660     this.renderCellDelegate = this.renderCell.createDelegate(this);
64661     this.renderPropDelegate = this.renderProp.createDelegate(this);
64662 };
64663
64664 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
64665     
64666     
64667     nameText : 'Name',
64668     valueText : 'Value',
64669     
64670     dateFormat : 'm/j/Y',
64671     
64672     
64673     renderDate : function(dateVal){
64674         return dateVal.dateFormat(this.dateFormat);
64675     },
64676
64677     renderBool : function(bVal){
64678         return bVal ? 'true' : 'false';
64679     },
64680
64681     isCellEditable : function(colIndex, rowIndex){
64682         return colIndex == 1;
64683     },
64684
64685     getRenderer : function(col){
64686         return col == 1 ?
64687             this.renderCellDelegate : this.renderPropDelegate;
64688     },
64689
64690     renderProp : function(v){
64691         return this.getPropertyName(v);
64692     },
64693
64694     renderCell : function(val){
64695         var rv = val;
64696         if(val instanceof Date){
64697             rv = this.renderDate(val);
64698         }else if(typeof val == 'boolean'){
64699             rv = this.renderBool(val);
64700         }
64701         return Roo.util.Format.htmlEncode(rv);
64702     },
64703
64704     getPropertyName : function(name){
64705         var pn = this.grid.propertyNames;
64706         return pn && pn[name] ? pn[name] : name;
64707     },
64708
64709     getCellEditor : function(colIndex, rowIndex){
64710         var p = this.store.getProperty(rowIndex);
64711         var n = p.data['name'], val = p.data['value'];
64712         
64713         if(typeof(this.grid.customEditors[n]) == 'string'){
64714             return this.editors[this.grid.customEditors[n]];
64715         }
64716         if(typeof(this.grid.customEditors[n]) != 'undefined'){
64717             return this.grid.customEditors[n];
64718         }
64719         if(val instanceof Date){
64720             return this.editors['date'];
64721         }else if(typeof val == 'number'){
64722             return this.editors['number'];
64723         }else if(typeof val == 'boolean'){
64724             return this.editors['boolean'];
64725         }else{
64726             return this.editors['string'];
64727         }
64728     }
64729 });
64730
64731 /**
64732  * @class Roo.grid.PropertyGrid
64733  * @extends Roo.grid.EditorGrid
64734  * This class represents the  interface of a component based property grid control.
64735  * <br><br>Usage:<pre><code>
64736  var grid = new Roo.grid.PropertyGrid("my-container-id", {
64737       
64738  });
64739  // set any options
64740  grid.render();
64741  * </code></pre>
64742   
64743  * @constructor
64744  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
64745  * The container MUST have some type of size defined for the grid to fill. The container will be
64746  * automatically set to position relative if it isn't already.
64747  * @param {Object} config A config object that sets properties on this grid.
64748  */
64749 Roo.grid.PropertyGrid = function(container, config){
64750     config = config || {};
64751     var store = new Roo.grid.PropertyStore(this);
64752     this.store = store;
64753     var cm = new Roo.grid.PropertyColumnModel(this, store);
64754     store.store.sort('name', 'ASC');
64755     Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
64756         ds: store.store,
64757         cm: cm,
64758         enableColLock:false,
64759         enableColumnMove:false,
64760         stripeRows:false,
64761         trackMouseOver: false,
64762         clicksToEdit:1
64763     }, config));
64764     this.getGridEl().addClass('x-props-grid');
64765     this.lastEditRow = null;
64766     this.on('columnresize', this.onColumnResize, this);
64767     this.addEvents({
64768          /**
64769              * @event beforepropertychange
64770              * Fires before a property changes (return false to stop?)
64771              * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
64772              * @param {String} id Record Id
64773              * @param {String} newval New Value
64774          * @param {String} oldval Old Value
64775              */
64776         "beforepropertychange": true,
64777         /**
64778              * @event propertychange
64779              * Fires after a property changes
64780              * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
64781              * @param {String} id Record Id
64782              * @param {String} newval New Value
64783          * @param {String} oldval Old Value
64784              */
64785         "propertychange": true
64786     });
64787     this.customEditors = this.customEditors || {};
64788 };
64789 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
64790     
64791      /**
64792      * @cfg {Object} customEditors map of colnames=> custom editors.
64793      * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
64794      * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
64795      * false disables editing of the field.
64796          */
64797     
64798       /**
64799      * @cfg {Object} propertyNames map of property Names to their displayed value
64800          */
64801     
64802     render : function(){
64803         Roo.grid.PropertyGrid.superclass.render.call(this);
64804         this.autoSize.defer(100, this);
64805     },
64806
64807     autoSize : function(){
64808         Roo.grid.PropertyGrid.superclass.autoSize.call(this);
64809         if(this.view){
64810             this.view.fitColumns();
64811         }
64812     },
64813
64814     onColumnResize : function(){
64815         this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
64816         this.autoSize();
64817     },
64818     /**
64819      * Sets the data for the Grid
64820      * accepts a Key => Value object of all the elements avaiable.
64821      * @param {Object} data  to appear in grid.
64822      */
64823     setSource : function(source){
64824         this.store.setSource(source);
64825         //this.autoSize();
64826     },
64827     /**
64828      * Gets all the data from the grid.
64829      * @return {Object} data  data stored in grid
64830      */
64831     getSource : function(){
64832         return this.store.getSource();
64833     }
64834 });/*
64835   
64836  * Licence LGPL
64837  
64838  */
64839  
64840 /**
64841  * @class Roo.grid.Calendar
64842  * @extends Roo.grid.Grid
64843  * This class extends the Grid to provide a calendar widget
64844  * <br><br>Usage:<pre><code>
64845  var grid = new Roo.grid.Calendar("my-container-id", {
64846      ds: myDataStore,
64847      cm: myColModel,
64848      selModel: mySelectionModel,
64849      autoSizeColumns: true,
64850      monitorWindowResize: false,
64851      trackMouseOver: true
64852      eventstore : real data store..
64853  });
64854  // set any options
64855  grid.render();
64856   
64857   * @constructor
64858  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
64859  * The container MUST have some type of size defined for the grid to fill. The container will be
64860  * automatically set to position relative if it isn't already.
64861  * @param {Object} config A config object that sets properties on this grid.
64862  */
64863 Roo.grid.Calendar = function(container, config){
64864         // initialize the container
64865         this.container = Roo.get(container);
64866         this.container.update("");
64867         this.container.setStyle("overflow", "hidden");
64868     this.container.addClass('x-grid-container');
64869
64870     this.id = this.container.id;
64871
64872     Roo.apply(this, config);
64873     // check and correct shorthanded configs
64874     
64875     var rows = [];
64876     var d =1;
64877     for (var r = 0;r < 6;r++) {
64878         
64879         rows[r]=[];
64880         for (var c =0;c < 7;c++) {
64881             rows[r][c]= '';
64882         }
64883     }
64884     if (this.eventStore) {
64885         this.eventStore= Roo.factory(this.eventStore, Roo.data);
64886         this.eventStore.on('load',this.onLoad, this);
64887         this.eventStore.on('beforeload',this.clearEvents, this);
64888          
64889     }
64890     
64891     this.dataSource = new Roo.data.Store({
64892             proxy: new Roo.data.MemoryProxy(rows),
64893             reader: new Roo.data.ArrayReader({}, [
64894                    'weekday0', 'weekday1', 'weekday2', 'weekday3', 'weekday4', 'weekday5', 'weekday6' ])
64895     });
64896
64897     this.dataSource.load();
64898     this.ds = this.dataSource;
64899     this.ds.xmodule = this.xmodule || false;
64900     
64901     
64902     var cellRender = function(v,x,r)
64903     {
64904         return String.format(
64905             '<div class="fc-day  fc-widget-content"><div>' +
64906                 '<div class="fc-event-container"></div>' +
64907                 '<div class="fc-day-number">{0}</div>'+
64908                 
64909                 '<div class="fc-day-content"><div style="position:relative"></div></div>' +
64910             '</div></div>', v);
64911     
64912     }
64913     
64914     
64915     this.colModel = new Roo.grid.ColumnModel( [
64916         {
64917             xtype: 'ColumnModel',
64918             xns: Roo.grid,
64919             dataIndex : 'weekday0',
64920             header : 'Sunday',
64921             renderer : cellRender
64922         },
64923         {
64924             xtype: 'ColumnModel',
64925             xns: Roo.grid,
64926             dataIndex : 'weekday1',
64927             header : 'Monday',
64928             renderer : cellRender
64929         },
64930         {
64931             xtype: 'ColumnModel',
64932             xns: Roo.grid,
64933             dataIndex : 'weekday2',
64934             header : 'Tuesday',
64935             renderer : cellRender
64936         },
64937         {
64938             xtype: 'ColumnModel',
64939             xns: Roo.grid,
64940             dataIndex : 'weekday3',
64941             header : 'Wednesday',
64942             renderer : cellRender
64943         },
64944         {
64945             xtype: 'ColumnModel',
64946             xns: Roo.grid,
64947             dataIndex : 'weekday4',
64948             header : 'Thursday',
64949             renderer : cellRender
64950         },
64951         {
64952             xtype: 'ColumnModel',
64953             xns: Roo.grid,
64954             dataIndex : 'weekday5',
64955             header : 'Friday',
64956             renderer : cellRender
64957         },
64958         {
64959             xtype: 'ColumnModel',
64960             xns: Roo.grid,
64961             dataIndex : 'weekday6',
64962             header : 'Saturday',
64963             renderer : cellRender
64964         }
64965     ]);
64966     this.cm = this.colModel;
64967     this.cm.xmodule = this.xmodule || false;
64968  
64969         
64970           
64971     //this.selModel = new Roo.grid.CellSelectionModel();
64972     //this.sm = this.selModel;
64973     //this.selModel.init(this);
64974     
64975     
64976     if(this.width){
64977         this.container.setWidth(this.width);
64978     }
64979
64980     if(this.height){
64981         this.container.setHeight(this.height);
64982     }
64983     /** @private */
64984         this.addEvents({
64985         // raw events
64986         /**
64987          * @event click
64988          * The raw click event for the entire grid.
64989          * @param {Roo.EventObject} e
64990          */
64991         "click" : true,
64992         /**
64993          * @event dblclick
64994          * The raw dblclick event for the entire grid.
64995          * @param {Roo.EventObject} e
64996          */
64997         "dblclick" : true,
64998         /**
64999          * @event contextmenu
65000          * The raw contextmenu event for the entire grid.
65001          * @param {Roo.EventObject} e
65002          */
65003         "contextmenu" : true,
65004         /**
65005          * @event mousedown
65006          * The raw mousedown event for the entire grid.
65007          * @param {Roo.EventObject} e
65008          */
65009         "mousedown" : true,
65010         /**
65011          * @event mouseup
65012          * The raw mouseup event for the entire grid.
65013          * @param {Roo.EventObject} e
65014          */
65015         "mouseup" : true,
65016         /**
65017          * @event mouseover
65018          * The raw mouseover event for the entire grid.
65019          * @param {Roo.EventObject} e
65020          */
65021         "mouseover" : true,
65022         /**
65023          * @event mouseout
65024          * The raw mouseout event for the entire grid.
65025          * @param {Roo.EventObject} e
65026          */
65027         "mouseout" : true,
65028         /**
65029          * @event keypress
65030          * The raw keypress event for the entire grid.
65031          * @param {Roo.EventObject} e
65032          */
65033         "keypress" : true,
65034         /**
65035          * @event keydown
65036          * The raw keydown event for the entire grid.
65037          * @param {Roo.EventObject} e
65038          */
65039         "keydown" : true,
65040
65041         // custom events
65042
65043         /**
65044          * @event cellclick
65045          * Fires when a cell is clicked
65046          * @param {Grid} this
65047          * @param {Number} rowIndex
65048          * @param {Number} columnIndex
65049          * @param {Roo.EventObject} e
65050          */
65051         "cellclick" : true,
65052         /**
65053          * @event celldblclick
65054          * Fires when a cell is double clicked
65055          * @param {Grid} this
65056          * @param {Number} rowIndex
65057          * @param {Number} columnIndex
65058          * @param {Roo.EventObject} e
65059          */
65060         "celldblclick" : true,
65061         /**
65062          * @event rowclick
65063          * Fires when a row is clicked
65064          * @param {Grid} this
65065          * @param {Number} rowIndex
65066          * @param {Roo.EventObject} e
65067          */
65068         "rowclick" : true,
65069         /**
65070          * @event rowdblclick
65071          * Fires when a row is double clicked
65072          * @param {Grid} this
65073          * @param {Number} rowIndex
65074          * @param {Roo.EventObject} e
65075          */
65076         "rowdblclick" : true,
65077         /**
65078          * @event headerclick
65079          * Fires when a header is clicked
65080          * @param {Grid} this
65081          * @param {Number} columnIndex
65082          * @param {Roo.EventObject} e
65083          */
65084         "headerclick" : true,
65085         /**
65086          * @event headerdblclick
65087          * Fires when a header cell is double clicked
65088          * @param {Grid} this
65089          * @param {Number} columnIndex
65090          * @param {Roo.EventObject} e
65091          */
65092         "headerdblclick" : true,
65093         /**
65094          * @event rowcontextmenu
65095          * Fires when a row is right clicked
65096          * @param {Grid} this
65097          * @param {Number} rowIndex
65098          * @param {Roo.EventObject} e
65099          */
65100         "rowcontextmenu" : true,
65101         /**
65102          * @event cellcontextmenu
65103          * Fires when a cell is right clicked
65104          * @param {Grid} this
65105          * @param {Number} rowIndex
65106          * @param {Number} cellIndex
65107          * @param {Roo.EventObject} e
65108          */
65109          "cellcontextmenu" : true,
65110         /**
65111          * @event headercontextmenu
65112          * Fires when a header is right clicked
65113          * @param {Grid} this
65114          * @param {Number} columnIndex
65115          * @param {Roo.EventObject} e
65116          */
65117         "headercontextmenu" : true,
65118         /**
65119          * @event bodyscroll
65120          * Fires when the body element is scrolled
65121          * @param {Number} scrollLeft
65122          * @param {Number} scrollTop
65123          */
65124         "bodyscroll" : true,
65125         /**
65126          * @event columnresize
65127          * Fires when the user resizes a column
65128          * @param {Number} columnIndex
65129          * @param {Number} newSize
65130          */
65131         "columnresize" : true,
65132         /**
65133          * @event columnmove
65134          * Fires when the user moves a column
65135          * @param {Number} oldIndex
65136          * @param {Number} newIndex
65137          */
65138         "columnmove" : true,
65139         /**
65140          * @event startdrag
65141          * Fires when row(s) start being dragged
65142          * @param {Grid} this
65143          * @param {Roo.GridDD} dd The drag drop object
65144          * @param {event} e The raw browser event
65145          */
65146         "startdrag" : true,
65147         /**
65148          * @event enddrag
65149          * Fires when a drag operation is complete
65150          * @param {Grid} this
65151          * @param {Roo.GridDD} dd The drag drop object
65152          * @param {event} e The raw browser event
65153          */
65154         "enddrag" : true,
65155         /**
65156          * @event dragdrop
65157          * Fires when dragged row(s) are dropped on a valid DD target
65158          * @param {Grid} this
65159          * @param {Roo.GridDD} dd The drag drop object
65160          * @param {String} targetId The target drag drop object
65161          * @param {event} e The raw browser event
65162          */
65163         "dragdrop" : true,
65164         /**
65165          * @event dragover
65166          * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
65167          * @param {Grid} this
65168          * @param {Roo.GridDD} dd The drag drop object
65169          * @param {String} targetId The target drag drop object
65170          * @param {event} e The raw browser event
65171          */
65172         "dragover" : true,
65173         /**
65174          * @event dragenter
65175          *  Fires when the dragged row(s) first cross another DD target while being dragged
65176          * @param {Grid} this
65177          * @param {Roo.GridDD} dd The drag drop object
65178          * @param {String} targetId The target drag drop object
65179          * @param {event} e The raw browser event
65180          */
65181         "dragenter" : true,
65182         /**
65183          * @event dragout
65184          * Fires when the dragged row(s) leave another DD target while being dragged
65185          * @param {Grid} this
65186          * @param {Roo.GridDD} dd The drag drop object
65187          * @param {String} targetId The target drag drop object
65188          * @param {event} e The raw browser event
65189          */
65190         "dragout" : true,
65191         /**
65192          * @event rowclass
65193          * Fires when a row is rendered, so you can change add a style to it.
65194          * @param {GridView} gridview   The grid view
65195          * @param {Object} rowcfg   contains record  rowIndex and rowClass - set rowClass to add a style.
65196          */
65197         'rowclass' : true,
65198
65199         /**
65200          * @event render
65201          * Fires when the grid is rendered
65202          * @param {Grid} grid
65203          */
65204         'render' : true,
65205             /**
65206              * @event select
65207              * Fires when a date is selected
65208              * @param {DatePicker} this
65209              * @param {Date} date The selected date
65210              */
65211         'select': true,
65212         /**
65213              * @event monthchange
65214              * Fires when the displayed month changes 
65215              * @param {DatePicker} this
65216              * @param {Date} date The selected month
65217              */
65218         'monthchange': true,
65219         /**
65220              * @event evententer
65221              * Fires when mouse over an event
65222              * @param {Calendar} this
65223              * @param {event} Event
65224              */
65225         'evententer': true,
65226         /**
65227              * @event eventleave
65228              * Fires when the mouse leaves an
65229              * @param {Calendar} this
65230              * @param {event}
65231              */
65232         'eventleave': true,
65233         /**
65234              * @event eventclick
65235              * Fires when the mouse click an
65236              * @param {Calendar} this
65237              * @param {event}
65238              */
65239         'eventclick': true,
65240         /**
65241              * @event eventrender
65242              * Fires before each cell is rendered, so you can modify the contents, like cls / title / qtip
65243              * @param {Calendar} this
65244              * @param {data} data to be modified
65245              */
65246         'eventrender': true
65247         
65248     });
65249
65250     Roo.grid.Grid.superclass.constructor.call(this);
65251     this.on('render', function() {
65252         this.view.el.addClass('x-grid-cal'); 
65253         
65254         (function() { this.setDate(new Date()); }).defer(100,this); //default today..
65255
65256     },this);
65257     
65258     if (!Roo.grid.Calendar.style) {
65259         Roo.grid.Calendar.style = Roo.util.CSS.createStyleSheet({
65260             
65261             
65262             '.x-grid-cal .x-grid-col' :  {
65263                 height: 'auto !important',
65264                 'vertical-align': 'top'
65265             },
65266             '.x-grid-cal  .fc-event-hori' : {
65267                 height: '14px'
65268             }
65269              
65270             
65271         }, Roo.id());
65272     }
65273
65274     
65275     
65276 };
65277 Roo.extend(Roo.grid.Calendar, Roo.grid.Grid, {
65278     /**
65279      * @cfg {Store} eventStore The store that loads events.
65280      */
65281     eventStore : 25,
65282
65283      
65284     activeDate : false,
65285     startDay : 0,
65286     autoWidth : true,
65287     monitorWindowResize : false,
65288
65289     
65290     resizeColumns : function() {
65291         var col = (this.view.el.getWidth() / 7) - 3;
65292         // loop through cols, and setWidth
65293         for(var i =0 ; i < 7 ; i++){
65294             this.cm.setColumnWidth(i, col);
65295         }
65296     },
65297      setDate :function(date) {
65298         
65299         Roo.log('setDate?');
65300         
65301         this.resizeColumns();
65302         var vd = this.activeDate;
65303         this.activeDate = date;
65304 //        if(vd && this.el){
65305 //            var t = date.getTime();
65306 //            if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
65307 //                Roo.log('using add remove');
65308 //                
65309 //                this.fireEvent('monthchange', this, date);
65310 //                
65311 //                this.cells.removeClass("fc-state-highlight");
65312 //                this.cells.each(function(c){
65313 //                   if(c.dateValue == t){
65314 //                       c.addClass("fc-state-highlight");
65315 //                       setTimeout(function(){
65316 //                            try{c.dom.firstChild.focus();}catch(e){}
65317 //                       }, 50);
65318 //                       return false;
65319 //                   }
65320 //                   return true;
65321 //                });
65322 //                return;
65323 //            }
65324 //        }
65325         
65326         var days = date.getDaysInMonth();
65327         
65328         var firstOfMonth = date.getFirstDateOfMonth();
65329         var startingPos = firstOfMonth.getDay()-this.startDay;
65330         
65331         if(startingPos < this.startDay){
65332             startingPos += 7;
65333         }
65334         
65335         var pm = date.add(Date.MONTH, -1);
65336         var prevStart = pm.getDaysInMonth()-startingPos;
65337 //        
65338         
65339         
65340         this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
65341         
65342         this.textNodes = this.view.el.query('.x-grid-row .x-grid-col .x-grid-cell-text');
65343         //this.cells.addClassOnOver('fc-state-hover');
65344         
65345         var cells = this.cells.elements;
65346         var textEls = this.textNodes;
65347         
65348         //Roo.each(cells, function(cell){
65349         //    cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
65350         //});
65351         
65352         days += startingPos;
65353
65354         // convert everything to numbers so it's fast
65355         var day = 86400000;
65356         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
65357         //Roo.log(d);
65358         //Roo.log(pm);
65359         //Roo.log(prevStart);
65360         
65361         var today = new Date().clearTime().getTime();
65362         var sel = date.clearTime().getTime();
65363         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
65364         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
65365         var ddMatch = this.disabledDatesRE;
65366         var ddText = this.disabledDatesText;
65367         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
65368         var ddaysText = this.disabledDaysText;
65369         var format = this.format;
65370         
65371         var setCellClass = function(cal, cell){
65372             
65373             //Roo.log('set Cell Class');
65374             cell.title = "";
65375             var t = d.getTime();
65376             
65377             //Roo.log(d);
65378             
65379             
65380             cell.dateValue = t;
65381             if(t == today){
65382                 cell.className += " fc-today";
65383                 cell.className += " fc-state-highlight";
65384                 cell.title = cal.todayText;
65385             }
65386             if(t == sel){
65387                 // disable highlight in other month..
65388                 cell.className += " fc-state-highlight";
65389                 
65390             }
65391             // disabling
65392             if(t < min) {
65393                 //cell.className = " fc-state-disabled";
65394                 cell.title = cal.minText;
65395                 return;
65396             }
65397             if(t > max) {
65398                 //cell.className = " fc-state-disabled";
65399                 cell.title = cal.maxText;
65400                 return;
65401             }
65402             if(ddays){
65403                 if(ddays.indexOf(d.getDay()) != -1){
65404                     // cell.title = ddaysText;
65405                    // cell.className = " fc-state-disabled";
65406                 }
65407             }
65408             if(ddMatch && format){
65409                 var fvalue = d.dateFormat(format);
65410                 if(ddMatch.test(fvalue)){
65411                     cell.title = ddText.replace("%0", fvalue);
65412                    cell.className = " fc-state-disabled";
65413                 }
65414             }
65415             
65416             if (!cell.initialClassName) {
65417                 cell.initialClassName = cell.dom.className;
65418             }
65419             
65420             cell.dom.className = cell.initialClassName  + ' ' +  cell.className;
65421         };
65422
65423         var i = 0;
65424         
65425         for(; i < startingPos; i++) {
65426             cells[i].dayName =  (++prevStart);
65427             Roo.log(textEls[i]);
65428             d.setDate(d.getDate()+1);
65429             
65430             //cells[i].className = "fc-past fc-other-month";
65431             setCellClass(this, cells[i]);
65432         }
65433         
65434         var intDay = 0;
65435         
65436         for(; i < days; i++){
65437             intDay = i - startingPos + 1;
65438             cells[i].dayName =  (intDay);
65439             d.setDate(d.getDate()+1);
65440             
65441             cells[i].className = ''; // "x-date-active";
65442             setCellClass(this, cells[i]);
65443         }
65444         var extraDays = 0;
65445         
65446         for(; i < 42; i++) {
65447             //textEls[i].innerHTML = (++extraDays);
65448             
65449             d.setDate(d.getDate()+1);
65450             cells[i].dayName = (++extraDays);
65451             cells[i].className = "fc-future fc-other-month";
65452             setCellClass(this, cells[i]);
65453         }
65454         
65455         //this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
65456         
65457         var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
65458         
65459         // this will cause all the cells to mis
65460         var rows= [];
65461         var i =0;
65462         for (var r = 0;r < 6;r++) {
65463             for (var c =0;c < 7;c++) {
65464                 this.ds.getAt(r).set('weekday' + c ,cells[i++].dayName );
65465             }    
65466         }
65467         
65468         this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
65469         for(i=0;i<cells.length;i++) {
65470             
65471             this.cells.elements[i].dayName = cells[i].dayName ;
65472             this.cells.elements[i].className = cells[i].className;
65473             this.cells.elements[i].initialClassName = cells[i].initialClassName ;
65474             this.cells.elements[i].title = cells[i].title ;
65475             this.cells.elements[i].dateValue = cells[i].dateValue ;
65476         }
65477         
65478         
65479         
65480         
65481         //this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
65482         //this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
65483         
65484         ////if(totalRows != 6){
65485             //this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
65486            // this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
65487        // }
65488         
65489         this.fireEvent('monthchange', this, date);
65490         
65491         
65492     },
65493  /**
65494      * Returns the grid's SelectionModel.
65495      * @return {SelectionModel}
65496      */
65497     getSelectionModel : function(){
65498         if(!this.selModel){
65499             this.selModel = new Roo.grid.CellSelectionModel();
65500         }
65501         return this.selModel;
65502     },
65503
65504     load: function() {
65505         this.eventStore.load()
65506         
65507         
65508         
65509     },
65510     
65511     findCell : function(dt) {
65512         dt = dt.clearTime().getTime();
65513         var ret = false;
65514         this.cells.each(function(c){
65515             //Roo.log("check " +c.dateValue + '?=' + dt);
65516             if(c.dateValue == dt){
65517                 ret = c;
65518                 return false;
65519             }
65520             return true;
65521         });
65522         
65523         return ret;
65524     },
65525     
65526     findCells : function(rec) {
65527         var s = rec.data.start_dt.clone().clearTime().getTime();
65528        // Roo.log(s);
65529         var e= rec.data.end_dt.clone().clearTime().getTime();
65530        // Roo.log(e);
65531         var ret = [];
65532         this.cells.each(function(c){
65533              ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
65534             
65535             if(c.dateValue > e){
65536                 return ;
65537             }
65538             if(c.dateValue < s){
65539                 return ;
65540             }
65541             ret.push(c);
65542         });
65543         
65544         return ret;    
65545     },
65546     
65547     findBestRow: function(cells)
65548     {
65549         var ret = 0;
65550         
65551         for (var i =0 ; i < cells.length;i++) {
65552             ret  = Math.max(cells[i].rows || 0,ret);
65553         }
65554         return ret;
65555         
65556     },
65557     
65558     
65559     addItem : function(rec)
65560     {
65561         // look for vertical location slot in
65562         var cells = this.findCells(rec);
65563         
65564         rec.row = this.findBestRow(cells);
65565         
65566         // work out the location.
65567         
65568         var crow = false;
65569         var rows = [];
65570         for(var i =0; i < cells.length; i++) {
65571             if (!crow) {
65572                 crow = {
65573                     start : cells[i],
65574                     end :  cells[i]
65575                 };
65576                 continue;
65577             }
65578             if (crow.start.getY() == cells[i].getY()) {
65579                 // on same row.
65580                 crow.end = cells[i];
65581                 continue;
65582             }
65583             // different row.
65584             rows.push(crow);
65585             crow = {
65586                 start: cells[i],
65587                 end : cells[i]
65588             };
65589             
65590         }
65591         
65592         rows.push(crow);
65593         rec.els = [];
65594         rec.rows = rows;
65595         rec.cells = cells;
65596         for (var i = 0; i < cells.length;i++) {
65597             cells[i].rows = Math.max(cells[i].rows || 0 , rec.row + 1 );
65598             
65599         }
65600         
65601         
65602     },
65603     
65604     clearEvents: function() {
65605         
65606         if (!this.eventStore.getCount()) {
65607             return;
65608         }
65609         // reset number of rows in cells.
65610         Roo.each(this.cells.elements, function(c){
65611             c.rows = 0;
65612         });
65613         
65614         this.eventStore.each(function(e) {
65615             this.clearEvent(e);
65616         },this);
65617         
65618     },
65619     
65620     clearEvent : function(ev)
65621     {
65622         if (ev.els) {
65623             Roo.each(ev.els, function(el) {
65624                 el.un('mouseenter' ,this.onEventEnter, this);
65625                 el.un('mouseleave' ,this.onEventLeave, this);
65626                 el.remove();
65627             },this);
65628             ev.els = [];
65629         }
65630     },
65631     
65632     
65633     renderEvent : function(ev,ctr) {
65634         if (!ctr) {
65635              ctr = this.view.el.select('.fc-event-container',true).first();
65636         }
65637         
65638          
65639         this.clearEvent(ev);
65640             //code
65641        
65642         
65643         
65644         ev.els = [];
65645         var cells = ev.cells;
65646         var rows = ev.rows;
65647         this.fireEvent('eventrender', this, ev);
65648         
65649         for(var i =0; i < rows.length; i++) {
65650             
65651             cls = '';
65652             if (i == 0) {
65653                 cls += ' fc-event-start';
65654             }
65655             if ((i+1) == rows.length) {
65656                 cls += ' fc-event-end';
65657             }
65658             
65659             //Roo.log(ev.data);
65660             // how many rows should it span..
65661             var cg = this.eventTmpl.append(ctr,Roo.apply({
65662                 fccls : cls
65663                 
65664             }, ev.data) , true);
65665             
65666             
65667             cg.on('mouseenter' ,this.onEventEnter, this, ev);
65668             cg.on('mouseleave' ,this.onEventLeave, this, ev);
65669             cg.on('click', this.onEventClick, this, ev);
65670             
65671             ev.els.push(cg);
65672             
65673             var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
65674             var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
65675             //Roo.log(cg);
65676              
65677             cg.setXY([sbox.x +2, sbox.y +(ev.row * 20)]);    
65678             cg.setWidth(ebox.right - sbox.x -2);
65679         }
65680     },
65681     
65682     renderEvents: function()
65683     {   
65684         // first make sure there is enough space..
65685         
65686         if (!this.eventTmpl) {
65687             this.eventTmpl = new Roo.Template(
65688                 '<div class="roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable {fccls} {cls}"  style="position: absolute" unselectable="on">' +
65689                     '<div class="fc-event-inner">' +
65690                         '<span class="fc-event-time">{time}</span>' +
65691                         '<span class="fc-event-title" qtip="{qtip}">{title}</span>' +
65692                     '</div>' +
65693                     '<div class="ui-resizable-heandle ui-resizable-e">&nbsp;&nbsp;&nbsp;</div>' +
65694                 '</div>'
65695             );
65696                 
65697         }
65698                
65699         
65700         
65701         this.cells.each(function(c) {
65702             //Roo.log(c.select('.fc-day-content div',true).first());
65703             c.select('.fc-day-content div',true).first().setHeight(Math.max(34, (c.rows || 1) * 20));
65704         });
65705         
65706         var ctr = this.view.el.select('.fc-event-container',true).first();
65707         
65708         var cls;
65709         this.eventStore.each(function(ev){
65710             
65711             this.renderEvent(ev);
65712              
65713              
65714         }, this);
65715         this.view.layout();
65716         
65717     },
65718     
65719     onEventEnter: function (e, el,event,d) {
65720         this.fireEvent('evententer', this, el, event);
65721     },
65722     
65723     onEventLeave: function (e, el,event,d) {
65724         this.fireEvent('eventleave', this, el, event);
65725     },
65726     
65727     onEventClick: function (e, el,event,d) {
65728         this.fireEvent('eventclick', this, el, event);
65729     },
65730     
65731     onMonthChange: function () {
65732         this.store.load();
65733     },
65734     
65735     onLoad: function () {
65736         
65737         //Roo.log('calendar onload');
65738 //         
65739         if(this.eventStore.getCount() > 0){
65740             
65741            
65742             
65743             this.eventStore.each(function(d){
65744                 
65745                 
65746                 // FIXME..
65747                 var add =   d.data;
65748                 if (typeof(add.end_dt) == 'undefined')  {
65749                     Roo.log("Missing End time in calendar data: ");
65750                     Roo.log(d);
65751                     return;
65752                 }
65753                 if (typeof(add.start_dt) == 'undefined')  {
65754                     Roo.log("Missing Start time in calendar data: ");
65755                     Roo.log(d);
65756                     return;
65757                 }
65758                 add.start_dt = typeof(add.start_dt) == 'string' ? Date.parseDate(add.start_dt,'Y-m-d H:i:s') : add.start_dt,
65759                 add.end_dt = typeof(add.end_dt) == 'string' ? Date.parseDate(add.end_dt,'Y-m-d H:i:s') : add.end_dt,
65760                 add.id = add.id || d.id;
65761                 add.title = add.title || '??';
65762                 
65763                 this.addItem(d);
65764                 
65765              
65766             },this);
65767         }
65768         
65769         this.renderEvents();
65770     }
65771     
65772
65773 });
65774 /*
65775  grid : {
65776                 xtype: 'Grid',
65777                 xns: Roo.grid,
65778                 listeners : {
65779                     render : function ()
65780                     {
65781                         _this.grid = this;
65782                         
65783                         if (!this.view.el.hasClass('course-timesheet')) {
65784                             this.view.el.addClass('course-timesheet');
65785                         }
65786                         if (this.tsStyle) {
65787                             this.ds.load({});
65788                             return; 
65789                         }
65790                         Roo.log('width');
65791                         Roo.log(_this.grid.view.el.getWidth());
65792                         
65793                         
65794                         this.tsStyle =  Roo.util.CSS.createStyleSheet({
65795                             '.course-timesheet .x-grid-row' : {
65796                                 height: '80px'
65797                             },
65798                             '.x-grid-row td' : {
65799                                 'vertical-align' : 0
65800                             },
65801                             '.course-edit-link' : {
65802                                 'color' : 'blue',
65803                                 'text-overflow' : 'ellipsis',
65804                                 'overflow' : 'hidden',
65805                                 'white-space' : 'nowrap',
65806                                 'cursor' : 'pointer'
65807                             },
65808                             '.sub-link' : {
65809                                 'color' : 'green'
65810                             },
65811                             '.de-act-sup-link' : {
65812                                 'color' : 'purple',
65813                                 'text-decoration' : 'line-through'
65814                             },
65815                             '.de-act-link' : {
65816                                 'color' : 'red',
65817                                 'text-decoration' : 'line-through'
65818                             },
65819                             '.course-timesheet .course-highlight' : {
65820                                 'border-top-style': 'dashed !important',
65821                                 'border-bottom-bottom': 'dashed !important'
65822                             },
65823                             '.course-timesheet .course-item' : {
65824                                 'font-family'   : 'tahoma, arial, helvetica',
65825                                 'font-size'     : '11px',
65826                                 'overflow'      : 'hidden',
65827                                 'padding-left'  : '10px',
65828                                 'padding-right' : '10px',
65829                                 'padding-top' : '10px' 
65830                             }
65831                             
65832                         }, Roo.id());
65833                                 this.ds.load({});
65834                     }
65835                 },
65836                 autoWidth : true,
65837                 monitorWindowResize : false,
65838                 cellrenderer : function(v,x,r)
65839                 {
65840                     return v;
65841                 },
65842                 sm : {
65843                     xtype: 'CellSelectionModel',
65844                     xns: Roo.grid
65845                 },
65846                 dataSource : {
65847                     xtype: 'Store',
65848                     xns: Roo.data,
65849                     listeners : {
65850                         beforeload : function (_self, options)
65851                         {
65852                             options.params = options.params || {};
65853                             options.params._month = _this.monthField.getValue();
65854                             options.params.limit = 9999;
65855                             options.params['sort'] = 'when_dt';    
65856                             options.params['dir'] = 'ASC';    
65857                             this.proxy.loadResponse = this.loadResponse;
65858                             Roo.log("load?");
65859                             //this.addColumns();
65860                         },
65861                         load : function (_self, records, options)
65862                         {
65863                             _this.grid.view.el.select('.course-edit-link', true).on('click', function() {
65864                                 // if you click on the translation.. you can edit it...
65865                                 var el = Roo.get(this);
65866                                 var id = el.dom.getAttribute('data-id');
65867                                 var d = el.dom.getAttribute('data-date');
65868                                 var t = el.dom.getAttribute('data-time');
65869                                 //var id = this.child('span').dom.textContent;
65870                                 
65871                                 //Roo.log(this);
65872                                 Pman.Dialog.CourseCalendar.show({
65873                                     id : id,
65874                                     when_d : d,
65875                                     when_t : t,
65876                                     productitem_active : id ? 1 : 0
65877                                 }, function() {
65878                                     _this.grid.ds.load({});
65879                                 });
65880                            
65881                            });
65882                            
65883                            _this.panel.fireEvent('resize', [ '', '' ]);
65884                         }
65885                     },
65886                     loadResponse : function(o, success, response){
65887                             // this is overridden on before load..
65888                             
65889                             Roo.log("our code?");       
65890                             //Roo.log(success);
65891                             //Roo.log(response)
65892                             delete this.activeRequest;
65893                             if(!success){
65894                                 this.fireEvent("loadexception", this, o, response);
65895                                 o.request.callback.call(o.request.scope, null, o.request.arg, false);
65896                                 return;
65897                             }
65898                             var result;
65899                             try {
65900                                 result = o.reader.read(response);
65901                             }catch(e){
65902                                 Roo.log("load exception?");
65903                                 this.fireEvent("loadexception", this, o, response, e);
65904                                 o.request.callback.call(o.request.scope, null, o.request.arg, false);
65905                                 return;
65906                             }
65907                             Roo.log("ready...");        
65908                             // loop through result.records;
65909                             // and set this.tdate[date] = [] << array of records..
65910                             _this.tdata  = {};
65911                             Roo.each(result.records, function(r){
65912                                 //Roo.log(r.data);
65913                                 if(typeof(_this.tdata[r.data.when_dt.format('j')]) == 'undefined'){
65914                                     _this.tdata[r.data.when_dt.format('j')] = [];
65915                                 }
65916                                 _this.tdata[r.data.when_dt.format('j')].push(r.data);
65917                             });
65918                             
65919                             //Roo.log(_this.tdata);
65920                             
65921                             result.records = [];
65922                             result.totalRecords = 6;
65923                     
65924                             // let's generate some duumy records for the rows.
65925                             //var st = _this.dateField.getValue();
65926                             
65927                             // work out monday..
65928                             //st = st.add(Date.DAY, -1 * st.format('w'));
65929                             
65930                             var date = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
65931                             
65932                             var firstOfMonth = date.getFirstDayOfMonth();
65933                             var days = date.getDaysInMonth();
65934                             var d = 1;
65935                             var firstAdded = false;
65936                             for (var i = 0; i < result.totalRecords ; i++) {
65937                                 //var d= st.add(Date.DAY, i);
65938                                 var row = {};
65939                                 var added = 0;
65940                                 for(var w = 0 ; w < 7 ; w++){
65941                                     if(!firstAdded && firstOfMonth != w){
65942                                         continue;
65943                                     }
65944                                     if(d > days){
65945                                         continue;
65946                                     }
65947                                     firstAdded = true;
65948                                     var dd = (d > 0 && d < 10) ? "0"+d : d;
65949                                     row['weekday'+w] = String.format(
65950                                                     '<span style="font-size: 16px;"><b>{0}</b></span>'+
65951                                                     '<span class="course-edit-link" style="color:blue;" data-id="0" data-date="{1}"> Add New</span>',
65952                                                     d,
65953                                                     date.format('Y-m-')+dd
65954                                                 );
65955                                     added++;
65956                                     if(typeof(_this.tdata[d]) != 'undefined'){
65957                                         Roo.each(_this.tdata[d], function(r){
65958                                             var is_sub = '';
65959                                             var deactive = '';
65960                                             var id = r.id;
65961                                             var desc = (r.productitem_id_descrip) ? r.productitem_id_descrip : '';
65962                                             if(r.parent_id*1>0){
65963                                                 is_sub = (r.productitem_id_visible*1 < 1) ? 'de-act-sup-link' :'sub-link';
65964                                                 id = r.parent_id;
65965                                             }
65966                                             if(r.productitem_id_visible*1 < 1 && r.parent_id*1 < 1){
65967                                                 deactive = 'de-act-link';
65968                                             }
65969                                             
65970                                             row['weekday'+w] += String.format(
65971                                                     '<br /><span class="course-edit-link {3} {4}" qtip="{5}" data-id="{0}">{2} - {1}</span>',
65972                                                     id, //0
65973                                                     r.product_id_name, //1
65974                                                     r.when_dt.format('h:ia'), //2
65975                                                     is_sub, //3
65976                                                     deactive, //4
65977                                                     desc // 5
65978                                             );
65979                                         });
65980                                     }
65981                                     d++;
65982                                 }
65983                                 
65984                                 // only do this if something added..
65985                                 if(added > 0){ 
65986                                     result.records.push(_this.grid.dataSource.reader.newRow(row));
65987                                 }
65988                                 
65989                                 
65990                                 // push it twice. (second one with an hour..
65991                                 
65992                             }
65993                             //Roo.log(result);
65994                             this.fireEvent("load", this, o, o.request.arg);
65995                             o.request.callback.call(o.request.scope, result, o.request.arg, true);
65996                         },
65997                     sortInfo : {field: 'when_dt', direction : 'ASC' },
65998                     proxy : {
65999                         xtype: 'HttpProxy',
66000                         xns: Roo.data,
66001                         method : 'GET',
66002                         url : baseURL + '/Roo/Shop_course.php'
66003                     },
66004                     reader : {
66005                         xtype: 'JsonReader',
66006                         xns: Roo.data,
66007                         id : 'id',
66008                         fields : [
66009                             {
66010                                 'name': 'id',
66011                                 'type': 'int'
66012                             },
66013                             {
66014                                 'name': 'when_dt',
66015                                 'type': 'string'
66016                             },
66017                             {
66018                                 'name': 'end_dt',
66019                                 'type': 'string'
66020                             },
66021                             {
66022                                 'name': 'parent_id',
66023                                 'type': 'int'
66024                             },
66025                             {
66026                                 'name': 'product_id',
66027                                 'type': 'int'
66028                             },
66029                             {
66030                                 'name': 'productitem_id',
66031                                 'type': 'int'
66032                             },
66033                             {
66034                                 'name': 'guid',
66035                                 'type': 'int'
66036                             }
66037                         ]
66038                     }
66039                 },
66040                 toolbar : {
66041                     xtype: 'Toolbar',
66042                     xns: Roo,
66043                     items : [
66044                         {
66045                             xtype: 'Button',
66046                             xns: Roo.Toolbar,
66047                             listeners : {
66048                                 click : function (_self, e)
66049                                 {
66050                                     var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
66051                                     sd.setMonth(sd.getMonth()-1);
66052                                     _this.monthField.setValue(sd.format('Y-m-d'));
66053                                     _this.grid.ds.load({});
66054                                 }
66055                             },
66056                             text : "Back"
66057                         },
66058                         {
66059                             xtype: 'Separator',
66060                             xns: Roo.Toolbar
66061                         },
66062                         {
66063                             xtype: 'MonthField',
66064                             xns: Roo.form,
66065                             listeners : {
66066                                 render : function (_self)
66067                                 {
66068                                     _this.monthField = _self;
66069                                    // _this.monthField.set  today
66070                                 },
66071                                 select : function (combo, date)
66072                                 {
66073                                     _this.grid.ds.load({});
66074                                 }
66075                             },
66076                             value : (function() { return new Date(); })()
66077                         },
66078                         {
66079                             xtype: 'Separator',
66080                             xns: Roo.Toolbar
66081                         },
66082                         {
66083                             xtype: 'TextItem',
66084                             xns: Roo.Toolbar,
66085                             text : "Blue: in-active, green: in-active sup-event, red: de-active, purple: de-active sup-event"
66086                         },
66087                         {
66088                             xtype: 'Fill',
66089                             xns: Roo.Toolbar
66090                         },
66091                         {
66092                             xtype: 'Button',
66093                             xns: Roo.Toolbar,
66094                             listeners : {
66095                                 click : function (_self, e)
66096                                 {
66097                                     var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
66098                                     sd.setMonth(sd.getMonth()+1);
66099                                     _this.monthField.setValue(sd.format('Y-m-d'));
66100                                     _this.grid.ds.load({});
66101                                 }
66102                             },
66103                             text : "Next"
66104                         }
66105                     ]
66106                 },
66107                  
66108             }
66109         };
66110         
66111         *//*
66112  * Based on:
66113  * Ext JS Library 1.1.1
66114  * Copyright(c) 2006-2007, Ext JS, LLC.
66115  *
66116  * Originally Released Under LGPL - original licence link has changed is not relivant.
66117  *
66118  * Fork - LGPL
66119  * <script type="text/javascript">
66120  */
66121  
66122 /**
66123  * @class Roo.LoadMask
66124  * A simple utility class for generically masking elements while loading data.  If the element being masked has
66125  * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
66126  * process and the mask element will be cached for reuse.  For all other elements, this mask will replace the
66127  * element's UpdateManager load indicator and will be destroyed after the initial load.
66128  * @constructor
66129  * Create a new LoadMask
66130  * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
66131  * @param {Object} config The config object
66132  */
66133 Roo.LoadMask = function(el, config){
66134     this.el = Roo.get(el);
66135     Roo.apply(this, config);
66136     if(this.store){
66137         this.store.on('beforeload', this.onBeforeLoad, this);
66138         this.store.on('load', this.onLoad, this);
66139         this.store.on('loadexception', this.onLoadException, this);
66140         this.removeMask = false;
66141     }else{
66142         var um = this.el.getUpdateManager();
66143         um.showLoadIndicator = false; // disable the default indicator
66144         um.on('beforeupdate', this.onBeforeLoad, this);
66145         um.on('update', this.onLoad, this);
66146         um.on('failure', this.onLoad, this);
66147         this.removeMask = true;
66148     }
66149 };
66150
66151 Roo.LoadMask.prototype = {
66152     /**
66153      * @cfg {Boolean} removeMask
66154      * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
66155      * False to persist the mask element reference for multiple uses (e.g., for paged data widgets).  Defaults to false.
66156      */
66157     removeMask : false,
66158     /**
66159      * @cfg {String} msg
66160      * The text to display in a centered loading message box (defaults to 'Loading...')
66161      */
66162     msg : 'Loading...',
66163     /**
66164      * @cfg {String} msgCls
66165      * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
66166      */
66167     msgCls : 'x-mask-loading',
66168
66169     /**
66170      * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
66171      * @type Boolean
66172      */
66173     disabled: false,
66174
66175     /**
66176      * Disables the mask to prevent it from being displayed
66177      */
66178     disable : function(){
66179        this.disabled = true;
66180     },
66181
66182     /**
66183      * Enables the mask so that it can be displayed
66184      */
66185     enable : function(){
66186         this.disabled = false;
66187     },
66188     
66189     onLoadException : function()
66190     {
66191         Roo.log(arguments);
66192         
66193         if (typeof(arguments[3]) != 'undefined') {
66194             Roo.MessageBox.alert("Error loading",arguments[3]);
66195         } 
66196         /*
66197         try {
66198             if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
66199                 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
66200             }   
66201         } catch(e) {
66202             
66203         }
66204         */
66205     
66206         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
66207     },
66208     // private
66209     onLoad : function()
66210     {
66211         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
66212     },
66213
66214     // private
66215     onBeforeLoad : function(){
66216         if(!this.disabled){
66217             (function() { this.el.mask(this.msg, this.msgCls); }).defer(50, this);
66218         }
66219     },
66220
66221     // private
66222     destroy : function(){
66223         if(this.store){
66224             this.store.un('beforeload', this.onBeforeLoad, this);
66225             this.store.un('load', this.onLoad, this);
66226             this.store.un('loadexception', this.onLoadException, this);
66227         }else{
66228             var um = this.el.getUpdateManager();
66229             um.un('beforeupdate', this.onBeforeLoad, this);
66230             um.un('update', this.onLoad, this);
66231             um.un('failure', this.onLoad, this);
66232         }
66233     }
66234 };/*
66235  * Based on:
66236  * Ext JS Library 1.1.1
66237  * Copyright(c) 2006-2007, Ext JS, LLC.
66238  *
66239  * Originally Released Under LGPL - original licence link has changed is not relivant.
66240  *
66241  * Fork - LGPL
66242  * <script type="text/javascript">
66243  */
66244
66245
66246 /**
66247  * @class Roo.XTemplate
66248  * @extends Roo.Template
66249  * Provides a template that can have nested templates for loops or conditionals. The syntax is:
66250 <pre><code>
66251 var t = new Roo.XTemplate(
66252         '&lt;select name="{name}"&gt;',
66253                 '&lt;tpl for="options"&gt;&lt;option value="{value:trim}"&gt;{text:ellipsis(10)}&lt;/option&gt;&lt;/tpl&gt;',
66254         '&lt;/select&gt;'
66255 );
66256  
66257 // then append, applying the master template values
66258  </code></pre>
66259  *
66260  * Supported features:
66261  *
66262  *  Tags:
66263
66264 <pre><code>
66265       {a_variable} - output encoded.
66266       {a_variable.format:("Y-m-d")} - call a method on the variable
66267       {a_variable:raw} - unencoded output
66268       {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
66269       {a_variable:this.method_on_template(...)} - call a method on the template object.
66270  
66271 </code></pre>
66272  *  The tpl tag:
66273 <pre><code>
66274         &lt;tpl for="a_variable or condition.."&gt;&lt;/tpl&gt;
66275         &lt;tpl if="a_variable or condition"&gt;&lt;/tpl&gt;
66276         &lt;tpl exec="some javascript"&gt;&lt;/tpl&gt;
66277         &lt;tpl name="named_template"&gt;&lt;/tpl&gt; (experimental)
66278   
66279         &lt;tpl for="."&gt;&lt;/tpl&gt; - just iterate the property..
66280         &lt;tpl for=".."&gt;&lt;/tpl&gt; - iterates with the parent (probably the template) 
66281 </code></pre>
66282  *      
66283  */
66284 Roo.XTemplate = function()
66285 {
66286     Roo.XTemplate.superclass.constructor.apply(this, arguments);
66287     if (this.html) {
66288         this.compile();
66289     }
66290 };
66291
66292
66293 Roo.extend(Roo.XTemplate, Roo.Template, {
66294
66295     /**
66296      * The various sub templates
66297      */
66298     tpls : false,
66299     /**
66300      *
66301      * basic tag replacing syntax
66302      * WORD:WORD()
66303      *
66304      * // you can fake an object call by doing this
66305      *  x.t:(test,tesT) 
66306      * 
66307      */
66308     re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
66309
66310     /**
66311      * compile the template
66312      *
66313      * This is not recursive, so I'm not sure how nested templates are really going to be handled..
66314      *
66315      */
66316     compile: function()
66317     {
66318         var s = this.html;
66319      
66320         s = ['<tpl>', s, '</tpl>'].join('');
66321     
66322         var re     = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
66323             nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
66324             ifRe   = /^<tpl\b[^>]*?if="(.*?)"/,
66325             execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
66326             namedRe = /^<tpl\b[^>]*?name="(\w+)"/,  // named templates..
66327             m,
66328             id     = 0,
66329             tpls   = [];
66330     
66331         while(true == !!(m = s.match(re))){
66332             var forMatch   = m[0].match(nameRe),
66333                 ifMatch   = m[0].match(ifRe),
66334                 execMatch   = m[0].match(execRe),
66335                 namedMatch   = m[0].match(namedRe),
66336                 
66337                 exp  = null, 
66338                 fn   = null,
66339                 exec = null,
66340                 name = forMatch && forMatch[1] ? forMatch[1] : '';
66341                 
66342             if (ifMatch) {
66343                 // if - puts fn into test..
66344                 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
66345                 if(exp){
66346                    fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
66347                 }
66348             }
66349             
66350             if (execMatch) {
66351                 // exec - calls a function... returns empty if true is  returned.
66352                 exp = execMatch && execMatch[1] ? execMatch[1] : null;
66353                 if(exp){
66354                    exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
66355                 }
66356             }
66357             
66358             
66359             if (name) {
66360                 // for = 
66361                 switch(name){
66362                     case '.':  name = new Function('values', 'parent', 'with(values){ return values; }'); break;
66363                     case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
66364                     default:   name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
66365                 }
66366             }
66367             var uid = namedMatch ? namedMatch[1] : id;
66368             
66369             
66370             tpls.push({
66371                 id:     namedMatch ? namedMatch[1] : id,
66372                 target: name,
66373                 exec:   exec,
66374                 test:   fn,
66375                 body:   m[1] || ''
66376             });
66377             if (namedMatch) {
66378                 s = s.replace(m[0], '');
66379             } else { 
66380                 s = s.replace(m[0], '{xtpl'+ id + '}');
66381             }
66382             ++id;
66383         }
66384         this.tpls = [];
66385         for(var i = tpls.length-1; i >= 0; --i){
66386             this.compileTpl(tpls[i]);
66387             this.tpls[tpls[i].id] = tpls[i];
66388         }
66389         this.master = tpls[tpls.length-1];
66390         return this;
66391     },
66392     /**
66393      * same as applyTemplate, except it's done to one of the subTemplates
66394      * when using named templates, you can do:
66395      *
66396      * var str = pl.applySubTemplate('your-name', values);
66397      *
66398      * 
66399      * @param {Number} id of the template
66400      * @param {Object} values to apply to template
66401      * @param {Object} parent (normaly the instance of this object)
66402      */
66403     applySubTemplate : function(id, values, parent)
66404     {
66405         
66406         
66407         var t = this.tpls[id];
66408         
66409         
66410         try { 
66411             if(t.test && !t.test.call(this, values, parent)){
66412                 return '';
66413             }
66414         } catch(e) {
66415             Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
66416             Roo.log(e.toString());
66417             Roo.log(t.test);
66418             return ''
66419         }
66420         try { 
66421             
66422             if(t.exec && t.exec.call(this, values, parent)){
66423                 return '';
66424             }
66425         } catch(e) {
66426             Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
66427             Roo.log(e.toString());
66428             Roo.log(t.exec);
66429             return ''
66430         }
66431         try {
66432             var vs = t.target ? t.target.call(this, values, parent) : values;
66433             parent = t.target ? values : parent;
66434             if(t.target && vs instanceof Array){
66435                 var buf = [];
66436                 for(var i = 0, len = vs.length; i < len; i++){
66437                     buf[buf.length] = t.compiled.call(this, vs[i], parent);
66438                 }
66439                 return buf.join('');
66440             }
66441             return t.compiled.call(this, vs, parent);
66442         } catch (e) {
66443             Roo.log("Xtemplate.applySubTemplate : Exception thrown");
66444             Roo.log(e.toString());
66445             Roo.log(t.compiled);
66446             return '';
66447         }
66448     },
66449
66450     compileTpl : function(tpl)
66451     {
66452         var fm = Roo.util.Format;
66453         var useF = this.disableFormats !== true;
66454         var sep = Roo.isGecko ? "+" : ",";
66455         var undef = function(str) {
66456             Roo.log("Property not found :"  + str);
66457             return '';
66458         };
66459         
66460         var fn = function(m, name, format, args)
66461         {
66462             //Roo.log(arguments);
66463             args = args ? args.replace(/\\'/g,"'") : args;
66464             //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
66465             if (typeof(format) == 'undefined') {
66466                 format= 'htmlEncode';
66467             }
66468             if (format == 'raw' ) {
66469                 format = false;
66470             }
66471             
66472             if(name.substr(0, 4) == 'xtpl'){
66473                 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
66474             }
66475             
66476             // build an array of options to determine if value is undefined..
66477             
66478             // basically get 'xxxx.yyyy' then do
66479             // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
66480             //    (function () { Roo.log("Property not found"); return ''; })() :
66481             //    ......
66482             
66483             var udef_ar = [];
66484             var lookfor = '';
66485             Roo.each(name.split('.'), function(st) {
66486                 lookfor += (lookfor.length ? '.': '') + st;
66487                 udef_ar.push(  "(typeof(" + lookfor + ") == 'undefined')"  );
66488             });
66489             
66490             var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
66491             
66492             
66493             if(format && useF){
66494                 
66495                 args = args ? ',' + args : "";
66496                  
66497                 if(format.substr(0, 5) != "this."){
66498                     format = "fm." + format + '(';
66499                 }else{
66500                     format = 'this.call("'+ format.substr(5) + '", ';
66501                     args = ", values";
66502                 }
66503                 
66504                 return "'"+ sep +   udef_st   +    format + name + args + "))"+sep+"'";
66505             }
66506              
66507             if (args.length) {
66508                 // called with xxyx.yuu:(test,test)
66509                 // change to ()
66510                 return "'"+ sep + udef_st  + name + '(' +  args + "))"+sep+"'";
66511             }
66512             // raw.. - :raw modifier..
66513             return "'"+ sep + udef_st  + name + ")"+sep+"'";
66514             
66515         };
66516         var body;
66517         // branched to use + in gecko and [].join() in others
66518         if(Roo.isGecko){
66519             body = "tpl.compiled = function(values, parent){  with(values) { return '" +
66520                    tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
66521                     "';};};";
66522         }else{
66523             body = ["tpl.compiled = function(values, parent){  with (values) { return ['"];
66524             body.push(tpl.body.replace(/(\r\n|\n)/g,
66525                             '\\n').replace(/'/g, "\\'").replace(this.re, fn));
66526             body.push("'].join('');};};");
66527             body = body.join('');
66528         }
66529         
66530         Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
66531        
66532         /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef  */
66533         eval(body);
66534         
66535         return this;
66536     },
66537
66538     applyTemplate : function(values){
66539         return this.master.compiled.call(this, values, {});
66540         //var s = this.subs;
66541     },
66542
66543     apply : function(){
66544         return this.applyTemplate.apply(this, arguments);
66545     }
66546
66547  });
66548
66549 Roo.XTemplate.from = function(el){
66550     el = Roo.getDom(el);
66551     return new Roo.XTemplate(el.value || el.innerHTML);
66552 };