af3689ee8d0d3809222c438e6e63128060235a40
[roojs1] / roojs-ui-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  * @class Roo.data.SortTypes
15  * @static
16  * Defines the default sorting (casting?) comparison functions used when sorting data.
17  */
18 Roo.data.SortTypes = {
19     /**
20      * Default sort that does nothing
21      * @param {Mixed} s The value being converted
22      * @return {Mixed} The comparison value
23      */
24     none : function(s){
25         return s;
26     },
27     
28     /**
29      * The regular expression used to strip tags
30      * @type {RegExp}
31      * @property
32      */
33     stripTagsRE : /<\/?[^>]+>/gi,
34     
35     /**
36      * Strips all HTML tags to sort on text only
37      * @param {Mixed} s The value being converted
38      * @return {String} The comparison value
39      */
40     asText : function(s){
41         return String(s).replace(this.stripTagsRE, "");
42     },
43     
44     /**
45      * Strips all HTML tags to sort on text only - Case insensitive
46      * @param {Mixed} s The value being converted
47      * @return {String} The comparison value
48      */
49     asUCText : function(s){
50         return String(s).toUpperCase().replace(this.stripTagsRE, "");
51     },
52     
53     /**
54      * Case insensitive string
55      * @param {Mixed} s The value being converted
56      * @return {String} The comparison value
57      */
58     asUCString : function(s) {
59         return String(s).toUpperCase();
60     },
61     
62     /**
63      * Date sorting
64      * @param {Mixed} s The value being converted
65      * @return {Number} The comparison value
66      */
67     asDate : function(s) {
68         if(!s){
69             return 0;
70         }
71         if(s instanceof Date){
72             return s.getTime();
73         }
74         return Date.parse(String(s));
75     },
76     
77     /**
78      * Float sorting
79      * @param {Mixed} s The value being converted
80      * @return {Float} The comparison value
81      */
82     asFloat : function(s) {
83         var val = parseFloat(String(s).replace(/,/g, ""));
84         if(isNaN(val)) {
85             val = 0;
86         }
87         return val;
88     },
89     
90     /**
91      * Integer sorting
92      * @param {Mixed} s The value being converted
93      * @return {Number} The comparison value
94      */
95     asInt : function(s) {
96         var val = parseInt(String(s).replace(/,/g, ""));
97         if(isNaN(val)) {
98             val = 0;
99         }
100         return val;
101     }
102 };/*
103  * Based on:
104  * Ext JS Library 1.1.1
105  * Copyright(c) 2006-2007, Ext JS, LLC.
106  *
107  * Originally Released Under LGPL - original licence link has changed is not relivant.
108  *
109  * Fork - LGPL
110  * <script type="text/javascript">
111  */
112
113 /**
114 * @class Roo.data.Record
115  * Instances of this class encapsulate both record <em>definition</em> information, and record
116  * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
117  * to access Records cached in an {@link Roo.data.Store} object.<br>
118  * <p>
119  * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
120  * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
121  * objects.<br>
122  * <p>
123  * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
124  * @constructor
125  * This constructor should not be used to create Record objects. Instead, use the constructor generated by
126  * {@link #create}. The parameters are the same.
127  * @param {Array} data An associative Array of data values keyed by the field name.
128  * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
129  * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
130  * not specified an integer id is generated.
131  */
132 Roo.data.Record = function(data, id){
133     this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
134     this.data = data;
135 };
136
137 /**
138  * Generate a constructor for a specific record layout.
139  * @param {Array} o An Array of field definition objects which specify field names, and optionally,
140  * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
141  * Each field definition object may contain the following properties: <ul>
142  * <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,
143  * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
144  * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
145  * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
146  * is being used, then this is a string containing the javascript expression to reference the data relative to 
147  * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
148  * to the data item relative to the record element. If the mapping expression is the same as the field name,
149  * this may be omitted.</p></li>
150  * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
151  * <ul><li>auto (Default, implies no conversion)</li>
152  * <li>string</li>
153  * <li>int</li>
154  * <li>float</li>
155  * <li>boolean</li>
156  * <li>date</li></ul></p></li>
157  * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
158  * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
159  * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
160  * by the Reader into an object that will be stored in the Record. It is passed the
161  * following parameters:<ul>
162  * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
163  * </ul></p></li>
164  * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
165  * </ul>
166  * <br>usage:<br><pre><code>
167 var TopicRecord = Roo.data.Record.create(
168     {name: 'title', mapping: 'topic_title'},
169     {name: 'author', mapping: 'username'},
170     {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
171     {name: 'lastPost', mapping: 'post_time', type: 'date'},
172     {name: 'lastPoster', mapping: 'user2'},
173     {name: 'excerpt', mapping: 'post_text'}
174 );
175
176 var myNewRecord = new TopicRecord({
177     title: 'Do my job please',
178     author: 'noobie',
179     totalPosts: 1,
180     lastPost: new Date(),
181     lastPoster: 'Animal',
182     excerpt: 'No way dude!'
183 });
184 myStore.add(myNewRecord);
185 </code></pre>
186  * @method create
187  * @static
188  */
189 Roo.data.Record.create = function(o){
190     var f = function(){
191         f.superclass.constructor.apply(this, arguments);
192     };
193     Roo.extend(f, Roo.data.Record);
194     var p = f.prototype;
195     p.fields = new Roo.util.MixedCollection(false, function(field){
196         return field.name;
197     });
198     for(var i = 0, len = o.length; i < len; i++){
199         p.fields.add(new Roo.data.Field(o[i]));
200     }
201     f.getField = function(name){
202         return p.fields.get(name);  
203     };
204     return f;
205 };
206
207 Roo.data.Record.AUTO_ID = 1000;
208 Roo.data.Record.EDIT = 'edit';
209 Roo.data.Record.REJECT = 'reject';
210 Roo.data.Record.COMMIT = 'commit';
211
212 Roo.data.Record.prototype = {
213     /**
214      * Readonly flag - true if this record has been modified.
215      * @type Boolean
216      */
217     dirty : false,
218     editing : false,
219     error: null,
220     modified: null,
221
222     // private
223     join : function(store){
224         this.store = store;
225     },
226
227     /**
228      * Set the named field to the specified value.
229      * @param {String} name The name of the field to set.
230      * @param {Object} value The value to set the field to.
231      */
232     set : function(name, value){
233         if(this.data[name] == value){
234             return;
235         }
236         this.dirty = true;
237         if(!this.modified){
238             this.modified = {};
239         }
240         if(typeof this.modified[name] == 'undefined'){
241             this.modified[name] = this.data[name];
242         }
243         this.data[name] = value;
244         if(!this.editing && this.store){
245             this.store.afterEdit(this);
246         }       
247     },
248
249     /**
250      * Get the value of the named field.
251      * @param {String} name The name of the field to get the value of.
252      * @return {Object} The value of the field.
253      */
254     get : function(name){
255         return this.data[name]; 
256     },
257
258     // private
259     beginEdit : function(){
260         this.editing = true;
261         this.modified = {}; 
262     },
263
264     // private
265     cancelEdit : function(){
266         this.editing = false;
267         delete this.modified;
268     },
269
270     // private
271     endEdit : function(){
272         this.editing = false;
273         if(this.dirty && this.store){
274             this.store.afterEdit(this);
275         }
276     },
277
278     /**
279      * Usually called by the {@link Roo.data.Store} which owns the Record.
280      * Rejects all changes made to the Record since either creation, or the last commit operation.
281      * Modified fields are reverted to their original values.
282      * <p>
283      * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
284      * of reject operations.
285      */
286     reject : function(){
287         var m = this.modified;
288         for(var n in m){
289             if(typeof m[n] != "function"){
290                 this.data[n] = m[n];
291             }
292         }
293         this.dirty = false;
294         delete this.modified;
295         this.editing = false;
296         if(this.store){
297             this.store.afterReject(this);
298         }
299     },
300
301     /**
302      * Usually called by the {@link Roo.data.Store} which owns the Record.
303      * Commits all changes made to the Record since either creation, or the last commit operation.
304      * <p>
305      * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
306      * of commit operations.
307      */
308     commit : function(){
309         this.dirty = false;
310         delete this.modified;
311         this.editing = false;
312         if(this.store){
313             this.store.afterCommit(this);
314         }
315     },
316
317     // private
318     hasError : function(){
319         return this.error != null;
320     },
321
322     // private
323     clearError : function(){
324         this.error = null;
325     },
326
327     /**
328      * Creates a copy of this record.
329      * @param {String} id (optional) A new record id if you don't want to use this record's id
330      * @return {Record}
331      */
332     copy : function(newId) {
333         return new this.constructor(Roo.apply({}, this.data), newId || this.id);
334     }
335 };/*
336  * Based on:
337  * Ext JS Library 1.1.1
338  * Copyright(c) 2006-2007, Ext JS, LLC.
339  *
340  * Originally Released Under LGPL - original licence link has changed is not relivant.
341  *
342  * Fork - LGPL
343  * <script type="text/javascript">
344  */
345
346
347
348 /**
349  * @class Roo.data.Store
350  * @extends Roo.util.Observable
351  * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
352  * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
353  * <p>
354  * 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
355  * has no knowledge of the format of the data returned by the Proxy.<br>
356  * <p>
357  * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
358  * instances from the data object. These records are cached and made available through accessor functions.
359  * @constructor
360  * Creates a new Store.
361  * @param {Object} config A config object containing the objects needed for the Store to access data,
362  * and read the data into Records.
363  */
364 Roo.data.Store = function(config){
365     this.data = new Roo.util.MixedCollection(false);
366     this.data.getKey = function(o){
367         return o.id;
368     };
369     this.baseParams = {};
370     // private
371     this.paramNames = {
372         "start" : "start",
373         "limit" : "limit",
374         "sort" : "sort",
375         "dir" : "dir",
376         "multisort" : "_multisort"
377     };
378
379     if(config && config.data){
380         this.inlineData = config.data;
381         delete config.data;
382     }
383
384     Roo.apply(this, config);
385     
386     if(this.reader){ // reader passed
387         this.reader = Roo.factory(this.reader, Roo.data);
388         this.reader.xmodule = this.xmodule || false;
389         if(!this.recordType){
390             this.recordType = this.reader.recordType;
391         }
392         if(this.reader.onMetaChange){
393             this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
394         }
395     }
396
397     if(this.recordType){
398         this.fields = this.recordType.prototype.fields;
399     }
400     this.modified = [];
401
402     this.addEvents({
403         /**
404          * @event datachanged
405          * Fires when the data cache has changed, and a widget which is using this Store
406          * as a Record cache should refresh its view.
407          * @param {Store} this
408          */
409         datachanged : true,
410         /**
411          * @event metachange
412          * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
413          * @param {Store} this
414          * @param {Object} meta The JSON metadata
415          */
416         metachange : true,
417         /**
418          * @event add
419          * Fires when Records have been added to the Store
420          * @param {Store} this
421          * @param {Roo.data.Record[]} records The array of Records added
422          * @param {Number} index The index at which the record(s) were added
423          */
424         add : true,
425         /**
426          * @event remove
427          * Fires when a Record has been removed from the Store
428          * @param {Store} this
429          * @param {Roo.data.Record} record The Record that was removed
430          * @param {Number} index The index at which the record was removed
431          */
432         remove : true,
433         /**
434          * @event update
435          * Fires when a Record has been updated
436          * @param {Store} this
437          * @param {Roo.data.Record} record The Record that was updated
438          * @param {String} operation The update operation being performed.  Value may be one of:
439          * <pre><code>
440  Roo.data.Record.EDIT
441  Roo.data.Record.REJECT
442  Roo.data.Record.COMMIT
443          * </code></pre>
444          */
445         update : true,
446         /**
447          * @event clear
448          * Fires when the data cache has been cleared.
449          * @param {Store} this
450          */
451         clear : true,
452         /**
453          * @event beforeload
454          * Fires before a request is made for a new data object.  If the beforeload handler returns false
455          * the load action will be canceled.
456          * @param {Store} this
457          * @param {Object} options The loading options that were specified (see {@link #load} for details)
458          */
459         beforeload : true,
460         /**
461          * @event beforeloadadd
462          * Fires after a new set of Records has been loaded.
463          * @param {Store} this
464          * @param {Roo.data.Record[]} records The Records that were loaded
465          * @param {Object} options The loading options that were specified (see {@link #load} for details)
466          */
467         beforeloadadd : true,
468         /**
469          * @event load
470          * Fires after a new set of Records has been loaded, before they are added to the store.
471          * @param {Store} this
472          * @param {Roo.data.Record[]} records The Records that were loaded
473          * @param {Object} options The loading options that were specified (see {@link #load} for details)
474          * @params {Object} return from reader
475          */
476         load : true,
477         /**
478          * @event loadexception
479          * Fires if an exception occurs in the Proxy during loading.
480          * Called with the signature of the Proxy's "loadexception" event.
481          * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
482          * 
483          * @param {Proxy} 
484          * @param {Object} return from JsonData.reader() - success, totalRecords, records
485          * @param {Object} load options 
486          * @param {Object} jsonData from your request (normally this contains the Exception)
487          */
488         loadexception : true
489     });
490     
491     if(this.proxy){
492         this.proxy = Roo.factory(this.proxy, Roo.data);
493         this.proxy.xmodule = this.xmodule || false;
494         this.relayEvents(this.proxy,  ["loadexception"]);
495     }
496     this.sortToggle = {};
497     this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
498
499     Roo.data.Store.superclass.constructor.call(this);
500
501     if(this.inlineData){
502         this.loadData(this.inlineData);
503         delete this.inlineData;
504     }
505 };
506
507 Roo.extend(Roo.data.Store, Roo.util.Observable, {
508      /**
509     * @cfg {boolean} isLocal   flag if data is locally available (and can be always looked up
510     * without a remote query - used by combo/forms at present.
511     */
512     
513     /**
514     * @cfg {Roo.data.DataProxy} proxy [required] The Proxy object which provides access to a data object.
515     */
516     /**
517     * @cfg {Array} data Inline data to be loaded when the store is initialized.
518     */
519     /**
520     * @cfg {Roo.data.DataReader} reader [required]  The Reader object which processes the data object and returns
521     * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
522     */
523     /**
524     * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
525     * on any HTTP request
526     */
527     /**
528     * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
529     */
530     /**
531     * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
532     */
533     multiSort: false,
534     /**
535     * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
536     * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
537     */
538     remoteSort : false,
539
540     /**
541     * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
542      * loaded or when a record is removed. (defaults to false).
543     */
544     pruneModifiedRecords : false,
545
546     // private
547     lastOptions : null,
548
549     /**
550      * Add Records to the Store and fires the add event.
551      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
552      */
553     add : function(records){
554         records = [].concat(records);
555         for(var i = 0, len = records.length; i < len; i++){
556             records[i].join(this);
557         }
558         var index = this.data.length;
559         this.data.addAll(records);
560         this.fireEvent("add", this, records, index);
561     },
562
563     /**
564      * Remove a Record from the Store and fires the remove event.
565      * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
566      */
567     remove : function(record){
568         var index = this.data.indexOf(record);
569         this.data.removeAt(index);
570  
571         if(this.pruneModifiedRecords){
572             this.modified.remove(record);
573         }
574         this.fireEvent("remove", this, record, index);
575     },
576
577     /**
578      * Remove all Records from the Store and fires the clear event.
579      */
580     removeAll : function(){
581         this.data.clear();
582         if(this.pruneModifiedRecords){
583             this.modified = [];
584         }
585         this.fireEvent("clear", this);
586     },
587
588     /**
589      * Inserts Records to the Store at the given index and fires the add event.
590      * @param {Number} index The start index at which to insert the passed Records.
591      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
592      */
593     insert : function(index, records){
594         records = [].concat(records);
595         for(var i = 0, len = records.length; i < len; i++){
596             this.data.insert(index, records[i]);
597             records[i].join(this);
598         }
599         this.fireEvent("add", this, records, index);
600     },
601
602     /**
603      * Get the index within the cache of the passed Record.
604      * @param {Roo.data.Record} record The Roo.data.Record object to to find.
605      * @return {Number} The index of the passed Record. Returns -1 if not found.
606      */
607     indexOf : function(record){
608         return this.data.indexOf(record);
609     },
610
611     /**
612      * Get the index within the cache of the Record with the passed id.
613      * @param {String} id The id of the Record to find.
614      * @return {Number} The index of the Record. Returns -1 if not found.
615      */
616     indexOfId : function(id){
617         return this.data.indexOfKey(id);
618     },
619
620     /**
621      * Get the Record with the specified id.
622      * @param {String} id The id of the Record to find.
623      * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
624      */
625     getById : function(id){
626         return this.data.key(id);
627     },
628
629     /**
630      * Get the Record at the specified index.
631      * @param {Number} index The index of the Record to find.
632      * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
633      */
634     getAt : function(index){
635         return this.data.itemAt(index);
636     },
637
638     /**
639      * Returns a range of Records between specified indices.
640      * @param {Number} startIndex (optional) The starting index (defaults to 0)
641      * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
642      * @return {Roo.data.Record[]} An array of Records
643      */
644     getRange : function(start, end){
645         return this.data.getRange(start, end);
646     },
647
648     // private
649     storeOptions : function(o){
650         o = Roo.apply({}, o);
651         delete o.callback;
652         delete o.scope;
653         this.lastOptions = o;
654     },
655
656     /**
657      * Loads the Record cache from the configured Proxy using the configured Reader.
658      * <p>
659      * If using remote paging, then the first load call must specify the <em>start</em>
660      * and <em>limit</em> properties in the options.params property to establish the initial
661      * position within the dataset, and the number of Records to cache on each read from the Proxy.
662      * <p>
663      * <strong>It is important to note that for remote data sources, loading is asynchronous,
664      * and this call will return before the new data has been loaded. Perform any post-processing
665      * in a callback function, or in a "load" event handler.</strong>
666      * <p>
667      * @param {Object} options An object containing properties which control loading options:<ul>
668      * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
669      * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
670      * passed the following arguments:<ul>
671      * <li>r : Roo.data.Record[]</li>
672      * <li>options: Options object from the load call</li>
673      * <li>success: Boolean success indicator</li></ul></li>
674      * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
675      * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
676      * </ul>
677      */
678     load : function(options){
679         options = options || {};
680         if(this.fireEvent("beforeload", this, options) !== false){
681             this.storeOptions(options);
682             var p = Roo.apply(options.params || {}, this.baseParams);
683             // if meta was not loaded from remote source.. try requesting it.
684             if (!this.reader.metaFromRemote) {
685                 p._requestMeta = 1;
686             }
687             if(this.sortInfo && this.remoteSort){
688                 var pn = this.paramNames;
689                 p[pn["sort"]] = this.sortInfo.field;
690                 p[pn["dir"]] = this.sortInfo.direction;
691             }
692             if (this.multiSort) {
693                 var pn = this.paramNames;
694                 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
695             }
696             
697             this.proxy.load(p, this.reader, this.loadRecords, this, options);
698         }
699     },
700
701     /**
702      * Reloads the Record cache from the configured Proxy using the configured Reader and
703      * the options from the last load operation performed.
704      * @param {Object} options (optional) An object containing properties which may override the options
705      * used in the last load operation. See {@link #load} for details (defaults to null, in which case
706      * the most recently used options are reused).
707      */
708     reload : function(options){
709         this.load(Roo.applyIf(options||{}, this.lastOptions));
710     },
711
712     // private
713     // Called as a callback by the Reader during a load operation.
714     loadRecords : function(o, options, success){
715          
716         if(!o){
717             if(success !== false){
718                 this.fireEvent("load", this, [], options, o);
719             }
720             if(options.callback){
721                 options.callback.call(options.scope || this, [], options, false);
722             }
723             return;
724         }
725         // if data returned failure - throw an exception.
726         if (o.success === false) {
727             // show a message if no listener is registered.
728             if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
729                     Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
730             }
731             // loadmask wil be hooked into this..
732             this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
733             return;
734         }
735         var r = o.records, t = o.totalRecords || r.length;
736         
737         this.fireEvent("beforeloadadd", this, r, options, o);
738         
739         if(!options || options.add !== true){
740             if(this.pruneModifiedRecords){
741                 this.modified = [];
742             }
743             for(var i = 0, len = r.length; i < len; i++){
744                 r[i].join(this);
745             }
746             if(this.snapshot){
747                 this.data = this.snapshot;
748                 delete this.snapshot;
749             }
750             this.data.clear();
751             this.data.addAll(r);
752             this.totalLength = t;
753             this.applySort();
754             this.fireEvent("datachanged", this);
755         }else{
756             this.totalLength = Math.max(t, this.data.length+r.length);
757             this.add(r);
758         }
759         
760         if(this.parent && !Roo.isIOS && !this.useNativeIOS && this.parent.emptyTitle.length) {
761                 
762             var e = new Roo.data.Record({});
763
764             e.set(this.parent.displayField, this.parent.emptyTitle);
765             e.set(this.parent.valueField, '');
766
767             this.insert(0, e);
768         }
769             
770         this.fireEvent("load", this, r, options, o);
771         if(options.callback){
772             options.callback.call(options.scope || this, r, options, true);
773         }
774     },
775
776
777     /**
778      * Loads data from a passed data block. A Reader which understands the format of the data
779      * must have been configured in the constructor.
780      * @param {Object} data The data block from which to read the Records.  The format of the data expected
781      * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
782      * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
783      */
784     loadData : function(o, append){
785         var r = this.reader.readRecords(o);
786         this.loadRecords(r, {add: append}, true);
787     },
788     
789      /**
790      * using 'cn' the nested child reader read the child array into it's child stores.
791      * @param {Object} rec The record with a 'children array
792      */
793     loadDataFromChildren : function(rec)
794     {
795         this.loadData(this.reader.toLoadData(rec));
796     },
797     
798
799     /**
800      * Gets the number of cached records.
801      * <p>
802      * <em>If using paging, this may not be the total size of the dataset. If the data object
803      * used by the Reader contains the dataset size, then the getTotalCount() function returns
804      * the data set size</em>
805      */
806     getCount : function(){
807         return this.data.length || 0;
808     },
809
810     /**
811      * Gets the total number of records in the dataset as returned by the server.
812      * <p>
813      * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
814      * the dataset size</em>
815      */
816     getTotalCount : function(){
817         return this.totalLength || 0;
818     },
819
820     /**
821      * Returns the sort state of the Store as an object with two properties:
822      * <pre><code>
823  field {String} The name of the field by which the Records are sorted
824  direction {String} The sort order, "ASC" or "DESC"
825      * </code></pre>
826      */
827     getSortState : function(){
828         return this.sortInfo;
829     },
830
831     // private
832     applySort : function(){
833         if(this.sortInfo && !this.remoteSort){
834             var s = this.sortInfo, f = s.field;
835             var st = this.fields.get(f).sortType;
836             var fn = function(r1, r2){
837                 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
838                 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
839             };
840             this.data.sort(s.direction, fn);
841             if(this.snapshot && this.snapshot != this.data){
842                 this.snapshot.sort(s.direction, fn);
843             }
844         }
845     },
846
847     /**
848      * Sets the default sort column and order to be used by the next load operation.
849      * @param {String} fieldName The name of the field to sort by.
850      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
851      */
852     setDefaultSort : function(field, dir){
853         this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
854     },
855
856     /**
857      * Sort the Records.
858      * If remote sorting is used, the sort is performed on the server, and the cache is
859      * reloaded. If local sorting is used, the cache is sorted internally.
860      * @param {String} fieldName The name of the field to sort by.
861      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
862      */
863     sort : function(fieldName, dir){
864         var f = this.fields.get(fieldName);
865         if(!dir){
866             this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
867             
868             if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
869                 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
870             }else{
871                 dir = f.sortDir;
872             }
873         }
874         this.sortToggle[f.name] = dir;
875         this.sortInfo = {field: f.name, direction: dir};
876         if(!this.remoteSort){
877             this.applySort();
878             this.fireEvent("datachanged", this);
879         }else{
880             this.load(this.lastOptions);
881         }
882     },
883
884     /**
885      * Calls the specified function for each of the Records in the cache.
886      * @param {Function} fn The function to call. The Record is passed as the first parameter.
887      * Returning <em>false</em> aborts and exits the iteration.
888      * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
889      */
890     each : function(fn, scope){
891         this.data.each(fn, scope);
892     },
893
894     /**
895      * Gets all records modified since the last commit.  Modified records are persisted across load operations
896      * (e.g., during paging).
897      * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
898      */
899     getModifiedRecords : function(){
900         return this.modified;
901     },
902
903     // private
904     createFilterFn : function(property, value, anyMatch){
905         if(!value.exec){ // not a regex
906             value = String(value);
907             if(value.length == 0){
908                 return false;
909             }
910             value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
911         }
912         return function(r){
913             return value.test(r.data[property]);
914         };
915     },
916
917     /**
918      * Sums the value of <i>property</i> for each record between start and end and returns the result.
919      * @param {String} property A field on your records
920      * @param {Number} start The record index to start at (defaults to 0)
921      * @param {Number} end The last record index to include (defaults to length - 1)
922      * @return {Number} The sum
923      */
924     sum : function(property, start, end){
925         var rs = this.data.items, v = 0;
926         start = start || 0;
927         end = (end || end === 0) ? end : rs.length-1;
928
929         for(var i = start; i <= end; i++){
930             v += (rs[i].data[property] || 0);
931         }
932         return v;
933     },
934
935     /**
936      * Filter the records by a specified property.
937      * @param {String} field A field on your records
938      * @param {String/RegExp} value Either a string that the field
939      * should start with or a RegExp to test against the field
940      * @param {Boolean} anyMatch True to match any part not just the beginning
941      */
942     filter : function(property, value, anyMatch){
943         var fn = this.createFilterFn(property, value, anyMatch);
944         return fn ? this.filterBy(fn) : this.clearFilter();
945     },
946
947     /**
948      * Filter by a function. The specified function will be called with each
949      * record in this data source. If the function returns true the record is included,
950      * otherwise it is filtered.
951      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
952      * @param {Object} scope (optional) The scope of the function (defaults to this)
953      */
954     filterBy : function(fn, scope){
955         this.snapshot = this.snapshot || this.data;
956         this.data = this.queryBy(fn, scope||this);
957         this.fireEvent("datachanged", this);
958     },
959
960     /**
961      * Query the records by a specified property.
962      * @param {String} field A field on your records
963      * @param {String/RegExp} value Either a string that the field
964      * should start with or a RegExp to test against the field
965      * @param {Boolean} anyMatch True to match any part not just the beginning
966      * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
967      */
968     query : function(property, value, anyMatch){
969         var fn = this.createFilterFn(property, value, anyMatch);
970         return fn ? this.queryBy(fn) : this.data.clone();
971     },
972
973     /**
974      * Query by a function. The specified function will be called with each
975      * record in this data source. If the function returns true the record is included
976      * in the results.
977      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
978      * @param {Object} scope (optional) The scope of the function (defaults to this)
979       @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
980      **/
981     queryBy : function(fn, scope){
982         var data = this.snapshot || this.data;
983         return data.filterBy(fn, scope||this);
984     },
985
986     /**
987      * Collects unique values for a particular dataIndex from this store.
988      * @param {String} dataIndex The property to collect
989      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
990      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
991      * @return {Array} An array of the unique values
992      **/
993     collect : function(dataIndex, allowNull, bypassFilter){
994         var d = (bypassFilter === true && this.snapshot) ?
995                 this.snapshot.items : this.data.items;
996         var v, sv, r = [], l = {};
997         for(var i = 0, len = d.length; i < len; i++){
998             v = d[i].data[dataIndex];
999             sv = String(v);
1000             if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
1001                 l[sv] = true;
1002                 r[r.length] = v;
1003             }
1004         }
1005         return r;
1006     },
1007
1008     /**
1009      * Revert to a view of the Record cache with no filtering applied.
1010      * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
1011      */
1012     clearFilter : function(suppressEvent){
1013         if(this.snapshot && this.snapshot != this.data){
1014             this.data = this.snapshot;
1015             delete this.snapshot;
1016             if(suppressEvent !== true){
1017                 this.fireEvent("datachanged", this);
1018             }
1019         }
1020     },
1021
1022     // private
1023     afterEdit : function(record){
1024         if(this.modified.indexOf(record) == -1){
1025             this.modified.push(record);
1026         }
1027         this.fireEvent("update", this, record, Roo.data.Record.EDIT);
1028     },
1029     
1030     // private
1031     afterReject : function(record){
1032         this.modified.remove(record);
1033         this.fireEvent("update", this, record, Roo.data.Record.REJECT);
1034     },
1035
1036     // private
1037     afterCommit : function(record){
1038         this.modified.remove(record);
1039         this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
1040     },
1041
1042     /**
1043      * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
1044      * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
1045      */
1046     commitChanges : function(){
1047         var m = this.modified.slice(0);
1048         this.modified = [];
1049         for(var i = 0, len = m.length; i < len; i++){
1050             m[i].commit();
1051         }
1052     },
1053
1054     /**
1055      * Cancel outstanding changes on all changed records.
1056      */
1057     rejectChanges : function(){
1058         var m = this.modified.slice(0);
1059         this.modified = [];
1060         for(var i = 0, len = m.length; i < len; i++){
1061             m[i].reject();
1062         }
1063     },
1064
1065     onMetaChange : function(meta, rtype, o){
1066         this.recordType = rtype;
1067         this.fields = rtype.prototype.fields;
1068         delete this.snapshot;
1069         this.sortInfo = meta.sortInfo || this.sortInfo;
1070         this.modified = [];
1071         this.fireEvent('metachange', this, this.reader.meta);
1072     },
1073     
1074     moveIndex : function(data, type)
1075     {
1076         var index = this.indexOf(data);
1077         
1078         var newIndex = index + type;
1079         
1080         this.remove(data);
1081         
1082         this.insert(newIndex, data);
1083         
1084     }
1085 });/*
1086  * Based on:
1087  * Ext JS Library 1.1.1
1088  * Copyright(c) 2006-2007, Ext JS, LLC.
1089  *
1090  * Originally Released Under LGPL - original licence link has changed is not relivant.
1091  *
1092  * Fork - LGPL
1093  * <script type="text/javascript">
1094  */
1095
1096 /**
1097  * @class Roo.data.SimpleStore
1098  * @extends Roo.data.Store
1099  * Small helper class to make creating Stores from Array data easier.
1100  * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
1101  * @cfg {Array} fields An array of field definition objects, or field name strings.
1102  * @cfg {Object} an existing reader (eg. copied from another store)
1103  * @cfg {Array} data The multi-dimensional array of data
1104  * @cfg {Roo.data.DataProxy} proxy [not-required]  
1105  * @cfg {Roo.data.Reader} reader  [not-required] 
1106  * @constructor
1107  * @param {Object} config
1108  */
1109 Roo.data.SimpleStore = function(config)
1110 {
1111     Roo.data.SimpleStore.superclass.constructor.call(this, {
1112         isLocal : true,
1113         reader: typeof(config.reader) != 'undefined' ? config.reader : new Roo.data.ArrayReader({
1114                 id: config.id
1115             },
1116             Roo.data.Record.create(config.fields)
1117         ),
1118         proxy : new Roo.data.MemoryProxy(config.data)
1119     });
1120     this.load();
1121 };
1122 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
1123  * Based on:
1124  * Ext JS Library 1.1.1
1125  * Copyright(c) 2006-2007, Ext JS, LLC.
1126  *
1127  * Originally Released Under LGPL - original licence link has changed is not relivant.
1128  *
1129  * Fork - LGPL
1130  * <script type="text/javascript">
1131  */
1132
1133 /**
1134 /**
1135  * @extends Roo.data.Store
1136  * @class Roo.data.JsonStore
1137  * Small helper class to make creating Stores for JSON data easier. <br/>
1138 <pre><code>
1139 var store = new Roo.data.JsonStore({
1140     url: 'get-images.php',
1141     root: 'images',
1142     fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
1143 });
1144 </code></pre>
1145  * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
1146  * JsonReader and HttpProxy (unless inline data is provided).</b>
1147  * @cfg {Array} fields An array of field definition objects, or field name strings.
1148  * @constructor
1149  * @param {Object} config
1150  */
1151 Roo.data.JsonStore = function(c){
1152     Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
1153         proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
1154         reader: new Roo.data.JsonReader(c, c.fields)
1155     }));
1156 };
1157 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
1158  * Based on:
1159  * Ext JS Library 1.1.1
1160  * Copyright(c) 2006-2007, Ext JS, LLC.
1161  *
1162  * Originally Released Under LGPL - original licence link has changed is not relivant.
1163  *
1164  * Fork - LGPL
1165  * <script type="text/javascript">
1166  */
1167
1168  
1169 Roo.data.Field = function(config){
1170     if(typeof config == "string"){
1171         config = {name: config};
1172     }
1173     Roo.apply(this, config);
1174     
1175     if(!this.type){
1176         this.type = "auto";
1177     }
1178     
1179     var st = Roo.data.SortTypes;
1180     // named sortTypes are supported, here we look them up
1181     if(typeof this.sortType == "string"){
1182         this.sortType = st[this.sortType];
1183     }
1184     
1185     // set default sortType for strings and dates
1186     if(!this.sortType){
1187         switch(this.type){
1188             case "string":
1189                 this.sortType = st.asUCString;
1190                 break;
1191             case "date":
1192                 this.sortType = st.asDate;
1193                 break;
1194             default:
1195                 this.sortType = st.none;
1196         }
1197     }
1198
1199     // define once
1200     var stripRe = /[\$,%]/g;
1201
1202     // prebuilt conversion function for this field, instead of
1203     // switching every time we're reading a value
1204     if(!this.convert){
1205         var cv, dateFormat = this.dateFormat;
1206         switch(this.type){
1207             case "":
1208             case "auto":
1209             case undefined:
1210                 cv = function(v){ return v; };
1211                 break;
1212             case "string":
1213                 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
1214                 break;
1215             case "int":
1216                 cv = function(v){
1217                     return v !== undefined && v !== null && v !== '' ?
1218                            parseInt(String(v).replace(stripRe, ""), 10) : '';
1219                     };
1220                 break;
1221             case "float":
1222                 cv = function(v){
1223                     return v !== undefined && v !== null && v !== '' ?
1224                            parseFloat(String(v).replace(stripRe, ""), 10) : ''; 
1225                     };
1226                 break;
1227             case "bool":
1228             case "boolean":
1229                 cv = function(v){ return v === true || v === "true" || v == 1; };
1230                 break;
1231             case "date":
1232                 cv = function(v){
1233                     if(!v){
1234                         return '';
1235                     }
1236                     if(v instanceof Date){
1237                         return v;
1238                     }
1239                     if(dateFormat){
1240                         if(dateFormat == "timestamp"){
1241                             return new Date(v*1000);
1242                         }
1243                         return Date.parseDate(v, dateFormat);
1244                     }
1245                     var parsed = Date.parse(v);
1246                     return parsed ? new Date(parsed) : null;
1247                 };
1248              break;
1249             
1250         }
1251         this.convert = cv;
1252     }
1253 };
1254
1255 Roo.data.Field.prototype = {
1256     dateFormat: null,
1257     defaultValue: "",
1258     mapping: null,
1259     sortType : null,
1260     sortDir : "ASC"
1261 };/*
1262  * Based on:
1263  * Ext JS Library 1.1.1
1264  * Copyright(c) 2006-2007, Ext JS, LLC.
1265  *
1266  * Originally Released Under LGPL - original licence link has changed is not relivant.
1267  *
1268  * Fork - LGPL
1269  * <script type="text/javascript">
1270  */
1271  
1272 // Base class for reading structured data from a data source.  This class is intended to be
1273 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
1274
1275 /**
1276  * @class Roo.data.DataReader
1277  * @abstract
1278  * Base class for reading structured data from a data source.  This class is intended to be
1279  * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
1280  */
1281
1282 Roo.data.DataReader = function(meta, recordType){
1283     
1284     this.meta = meta;
1285     
1286     this.recordType = recordType instanceof Array ? 
1287         Roo.data.Record.create(recordType) : recordType;
1288 };
1289
1290 Roo.data.DataReader.prototype = {
1291     
1292     
1293     readerType : 'Data',
1294      /**
1295      * Create an empty record
1296      * @param {Object} data (optional) - overlay some values
1297      * @return {Roo.data.Record} record created.
1298      */
1299     newRow :  function(d) {
1300         var da =  {};
1301         this.recordType.prototype.fields.each(function(c) {
1302             switch( c.type) {
1303                 case 'int' : da[c.name] = 0; break;
1304                 case 'date' : da[c.name] = new Date(); break;
1305                 case 'float' : da[c.name] = 0.0; break;
1306                 case 'boolean' : da[c.name] = false; break;
1307                 default : da[c.name] = ""; break;
1308             }
1309             
1310         });
1311         return new this.recordType(Roo.apply(da, d));
1312     }
1313     
1314     
1315 };/*
1316  * Based on:
1317  * Ext JS Library 1.1.1
1318  * Copyright(c) 2006-2007, Ext JS, LLC.
1319  *
1320  * Originally Released Under LGPL - original licence link has changed is not relivant.
1321  *
1322  * Fork - LGPL
1323  * <script type="text/javascript">
1324  */
1325
1326 /**
1327  * @class Roo.data.DataProxy
1328  * @extends Roo.util.Observable
1329  * @abstract
1330  * This class is an abstract base class for implementations which provide retrieval of
1331  * unformatted data objects.<br>
1332  * <p>
1333  * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
1334  * (of the appropriate type which knows how to parse the data object) to provide a block of
1335  * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
1336  * <p>
1337  * Custom implementations must implement the load method as described in
1338  * {@link Roo.data.HttpProxy#load}.
1339  */
1340 Roo.data.DataProxy = function(){
1341     this.addEvents({
1342         /**
1343          * @event beforeload
1344          * Fires before a network request is made to retrieve a data object.
1345          * @param {Object} This DataProxy object.
1346          * @param {Object} params The params parameter to the load function.
1347          */
1348         beforeload : true,
1349         /**
1350          * @event load
1351          * Fires before the load method's callback is called.
1352          * @param {Object} This DataProxy object.
1353          * @param {Object} o The data object.
1354          * @param {Object} arg The callback argument object passed to the load function.
1355          */
1356         load : true,
1357         /**
1358          * @event loadexception
1359          * Fires if an Exception occurs during data retrieval.
1360          * @param {Object} This DataProxy object.
1361          * @param {Object} o The data object.
1362          * @param {Object} arg The callback argument object passed to the load function.
1363          * @param {Object} e The Exception.
1364          */
1365         loadexception : true
1366     });
1367     Roo.data.DataProxy.superclass.constructor.call(this);
1368 };
1369
1370 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
1371
1372     /**
1373      * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
1374      */
1375 /*
1376  * Based on:
1377  * Ext JS Library 1.1.1
1378  * Copyright(c) 2006-2007, Ext JS, LLC.
1379  *
1380  * Originally Released Under LGPL - original licence link has changed is not relivant.
1381  *
1382  * Fork - LGPL
1383  * <script type="text/javascript">
1384  */
1385 /**
1386  * @class Roo.data.MemoryProxy
1387  * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
1388  * to the Reader when its load method is called.
1389  * @constructor
1390  * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
1391  */
1392 Roo.data.MemoryProxy = function(data){
1393     if (data.data) {
1394         data = data.data;
1395     }
1396     Roo.data.MemoryProxy.superclass.constructor.call(this);
1397     this.data = data;
1398 };
1399
1400 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
1401     
1402     /**
1403      * Load data from the requested source (in this case an in-memory
1404      * data object passed to the constructor), read the data object into
1405      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
1406      * process that block using the passed callback.
1407      * @param {Object} params This parameter is not used by the MemoryProxy class.
1408      * @param {Roo.data.DataReader} reader The Reader object which converts the data
1409      * object into a block of Roo.data.Records.
1410      * @param {Function} callback The function into which to pass the block of Roo.data.records.
1411      * The function must be passed <ul>
1412      * <li>The Record block object</li>
1413      * <li>The "arg" argument from the load function</li>
1414      * <li>A boolean success indicator</li>
1415      * </ul>
1416      * @param {Object} scope The scope in which to call the callback
1417      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1418      */
1419     load : function(params, reader, callback, scope, arg){
1420         params = params || {};
1421         var result;
1422         try {
1423             result = reader.readRecords(params.data ? params.data :this.data);
1424         }catch(e){
1425             this.fireEvent("loadexception", this, arg, null, e);
1426             callback.call(scope, null, arg, false);
1427             return;
1428         }
1429         callback.call(scope, result, arg, true);
1430     },
1431     
1432     // private
1433     update : function(params, records){
1434         
1435     }
1436 });/*
1437  * Based on:
1438  * Ext JS Library 1.1.1
1439  * Copyright(c) 2006-2007, Ext JS, LLC.
1440  *
1441  * Originally Released Under LGPL - original licence link has changed is not relivant.
1442  *
1443  * Fork - LGPL
1444  * <script type="text/javascript">
1445  */
1446 /**
1447  * @class Roo.data.HttpProxy
1448  * @extends Roo.data.DataProxy
1449  * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
1450  * configured to reference a certain URL.<br><br>
1451  * <p>
1452  * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
1453  * from which the running page was served.<br><br>
1454  * <p>
1455  * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
1456  * <p>
1457  * Be aware that to enable the browser to parse an XML document, the server must set
1458  * the Content-Type header in the HTTP response to "text/xml".
1459  * @constructor
1460  * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
1461  * an {@link Roo.data.Connection} object.  If a Connection config is passed, the singleton {@link Roo.Ajax} object
1462  * will be used to make the request.
1463  */
1464 Roo.data.HttpProxy = function(conn){
1465     Roo.data.HttpProxy.superclass.constructor.call(this);
1466     // is conn a conn config or a real conn?
1467     this.conn = conn;
1468     this.useAjax = !conn || !conn.events;
1469   
1470 };
1471
1472 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
1473     // thse are take from connection...
1474     
1475     /**
1476      * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
1477      */
1478     /**
1479      * @cfg {Object} extraParams (Optional) An object containing properties which are used as
1480      * extra parameters to each request made by this object. (defaults to undefined)
1481      */
1482     /**
1483      * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
1484      *  to each request made by this object. (defaults to undefined)
1485      */
1486     /**
1487      * @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)
1488      */
1489     /**
1490      * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
1491      */
1492      /**
1493      * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
1494      * @type Boolean
1495      */
1496   
1497
1498     /**
1499      * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
1500      * @type Boolean
1501      */
1502     /**
1503      * Return the {@link Roo.data.Connection} object being used by this Proxy.
1504      * @return {Connection} The Connection object. This object may be used to subscribe to events on
1505      * a finer-grained basis than the DataProxy events.
1506      */
1507     getConnection : function(){
1508         return this.useAjax ? Roo.Ajax : this.conn;
1509     },
1510
1511     /**
1512      * Load data from the configured {@link Roo.data.Connection}, read the data object into
1513      * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
1514      * process that block using the passed callback.
1515      * @param {Object} params An object containing properties which are to be used as HTTP parameters
1516      * for the request to the remote server.
1517      * @param {Roo.data.DataReader} reader The Reader object which converts the data
1518      * object into a block of Roo.data.Records.
1519      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
1520      * The function must be passed <ul>
1521      * <li>The Record block object</li>
1522      * <li>The "arg" argument from the load function</li>
1523      * <li>A boolean success indicator</li>
1524      * </ul>
1525      * @param {Object} scope The scope in which to call the callback
1526      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1527      */
1528     load : function(params, reader, callback, scope, arg){
1529         if(this.fireEvent("beforeload", this, params) !== false){
1530             var  o = {
1531                 params : params || {},
1532                 request: {
1533                     callback : callback,
1534                     scope : scope,
1535                     arg : arg
1536                 },
1537                 reader: reader,
1538                 callback : this.loadResponse,
1539                 scope: this
1540             };
1541             if(this.useAjax){
1542                 Roo.applyIf(o, this.conn);
1543                 if(this.activeRequest){
1544                     Roo.Ajax.abort(this.activeRequest);
1545                 }
1546                 this.activeRequest = Roo.Ajax.request(o);
1547             }else{
1548                 this.conn.request(o);
1549             }
1550         }else{
1551             callback.call(scope||this, null, arg, false);
1552         }
1553     },
1554
1555     // private
1556     loadResponse : function(o, success, response){
1557         delete this.activeRequest;
1558         if(!success){
1559             this.fireEvent("loadexception", this, o, response);
1560             o.request.callback.call(o.request.scope, null, o.request.arg, false);
1561             return;
1562         }
1563         var result;
1564         try {
1565             result = o.reader.read(response);
1566         }catch(e){
1567             o.success = false;
1568             o.raw = { errorMsg : response.responseText };
1569             this.fireEvent("loadexception", this, o, response, e);
1570             o.request.callback.call(o.request.scope, o, o.request.arg, false);
1571             return;
1572         }
1573         
1574         this.fireEvent("load", this, o, o.request.arg);
1575         o.request.callback.call(o.request.scope, result, o.request.arg, true);
1576     },
1577
1578     // private
1579     update : function(dataSet){
1580
1581     },
1582
1583     // private
1584     updateResponse : function(dataSet){
1585
1586     }
1587 });/*
1588  * Based on:
1589  * Ext JS Library 1.1.1
1590  * Copyright(c) 2006-2007, Ext JS, LLC.
1591  *
1592  * Originally Released Under LGPL - original licence link has changed is not relivant.
1593  *
1594  * Fork - LGPL
1595  * <script type="text/javascript">
1596  */
1597
1598 /**
1599  * @class Roo.data.ScriptTagProxy
1600  * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
1601  * other than the originating domain of the running page.<br><br>
1602  * <p>
1603  * <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
1604  * of the running page, you must use this class, rather than DataProxy.</em><br><br>
1605  * <p>
1606  * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
1607  * source code that is used as the source inside a &lt;script> tag.<br><br>
1608  * <p>
1609  * In order for the browser to process the returned data, the server must wrap the data object
1610  * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
1611  * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
1612  * depending on whether the callback name was passed:
1613  * <p>
1614  * <pre><code>
1615 boolean scriptTag = false;
1616 String cb = request.getParameter("callback");
1617 if (cb != null) {
1618     scriptTag = true;
1619     response.setContentType("text/javascript");
1620 } else {
1621     response.setContentType("application/x-json");
1622 }
1623 Writer out = response.getWriter();
1624 if (scriptTag) {
1625     out.write(cb + "(");
1626 }
1627 out.print(dataBlock.toJsonString());
1628 if (scriptTag) {
1629     out.write(");");
1630 }
1631 </pre></code>
1632  *
1633  * @constructor
1634  * @param {Object} config A configuration object.
1635  */
1636 Roo.data.ScriptTagProxy = function(config){
1637     Roo.data.ScriptTagProxy.superclass.constructor.call(this);
1638     Roo.apply(this, config);
1639     this.head = document.getElementsByTagName("head")[0];
1640 };
1641
1642 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
1643
1644 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
1645     /**
1646      * @cfg {String} url The URL from which to request the data object.
1647      */
1648     /**
1649      * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
1650      */
1651     timeout : 30000,
1652     /**
1653      * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
1654      * the server the name of the callback function set up by the load call to process the returned data object.
1655      * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
1656      * javascript output which calls this named function passing the data object as its only parameter.
1657      */
1658     callbackParam : "callback",
1659     /**
1660      *  @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
1661      * name to the request.
1662      */
1663     nocache : true,
1664
1665     /**
1666      * Load data from the configured URL, read the data object into
1667      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
1668      * process that block using the passed callback.
1669      * @param {Object} params An object containing properties which are to be used as HTTP parameters
1670      * for the request to the remote server.
1671      * @param {Roo.data.DataReader} reader The Reader object which converts the data
1672      * object into a block of Roo.data.Records.
1673      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
1674      * The function must be passed <ul>
1675      * <li>The Record block object</li>
1676      * <li>The "arg" argument from the load function</li>
1677      * <li>A boolean success indicator</li>
1678      * </ul>
1679      * @param {Object} scope The scope in which to call the callback
1680      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1681      */
1682     load : function(params, reader, callback, scope, arg){
1683         if(this.fireEvent("beforeload", this, params) !== false){
1684
1685             var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
1686
1687             var url = this.url;
1688             url += (url.indexOf("?") != -1 ? "&" : "?") + p;
1689             if(this.nocache){
1690                 url += "&_dc=" + (new Date().getTime());
1691             }
1692             var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
1693             var trans = {
1694                 id : transId,
1695                 cb : "stcCallback"+transId,
1696                 scriptId : "stcScript"+transId,
1697                 params : params,
1698                 arg : arg,
1699                 url : url,
1700                 callback : callback,
1701                 scope : scope,
1702                 reader : reader
1703             };
1704             var conn = this;
1705
1706             window[trans.cb] = function(o){
1707                 conn.handleResponse(o, trans);
1708             };
1709
1710             url += String.format("&{0}={1}", this.callbackParam, trans.cb);
1711
1712             if(this.autoAbort !== false){
1713                 this.abort();
1714             }
1715
1716             trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
1717
1718             var script = document.createElement("script");
1719             script.setAttribute("src", url);
1720             script.setAttribute("type", "text/javascript");
1721             script.setAttribute("id", trans.scriptId);
1722             this.head.appendChild(script);
1723
1724             this.trans = trans;
1725         }else{
1726             callback.call(scope||this, null, arg, false);
1727         }
1728     },
1729
1730     // private
1731     isLoading : function(){
1732         return this.trans ? true : false;
1733     },
1734
1735     /**
1736      * Abort the current server request.
1737      */
1738     abort : function(){
1739         if(this.isLoading()){
1740             this.destroyTrans(this.trans);
1741         }
1742     },
1743
1744     // private
1745     destroyTrans : function(trans, isLoaded){
1746         this.head.removeChild(document.getElementById(trans.scriptId));
1747         clearTimeout(trans.timeoutId);
1748         if(isLoaded){
1749             window[trans.cb] = undefined;
1750             try{
1751                 delete window[trans.cb];
1752             }catch(e){}
1753         }else{
1754             // if hasn't been loaded, wait for load to remove it to prevent script error
1755             window[trans.cb] = function(){
1756                 window[trans.cb] = undefined;
1757                 try{
1758                     delete window[trans.cb];
1759                 }catch(e){}
1760             };
1761         }
1762     },
1763
1764     // private
1765     handleResponse : function(o, trans){
1766         this.trans = false;
1767         this.destroyTrans(trans, true);
1768         var result;
1769         try {
1770             result = trans.reader.readRecords(o);
1771         }catch(e){
1772             this.fireEvent("loadexception", this, o, trans.arg, e);
1773             trans.callback.call(trans.scope||window, null, trans.arg, false);
1774             return;
1775         }
1776         this.fireEvent("load", this, o, trans.arg);
1777         trans.callback.call(trans.scope||window, result, trans.arg, true);
1778     },
1779
1780     // private
1781     handleFailure : function(trans){
1782         this.trans = false;
1783         this.destroyTrans(trans, false);
1784         this.fireEvent("loadexception", this, null, trans.arg);
1785         trans.callback.call(trans.scope||window, null, trans.arg, false);
1786     }
1787 });/*
1788  * Based on:
1789  * Ext JS Library 1.1.1
1790  * Copyright(c) 2006-2007, Ext JS, LLC.
1791  *
1792  * Originally Released Under LGPL - original licence link has changed is not relivant.
1793  *
1794  * Fork - LGPL
1795  * <script type="text/javascript">
1796  */
1797
1798 /**
1799  * @class Roo.data.JsonReader
1800  * @extends Roo.data.DataReader
1801  * Data reader class to create an Array of Roo.data.Record objects from a JSON response
1802  * based on mappings in a provided Roo.data.Record constructor.
1803  * 
1804  * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
1805  * in the reply previously. 
1806  * 
1807  * <p>
1808  * Example code:
1809  * <pre><code>
1810 var RecordDef = Roo.data.Record.create([
1811     {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
1812     {name: 'occupation'}                 // This field will use "occupation" as the mapping.
1813 ]);
1814 var myReader = new Roo.data.JsonReader({
1815     totalProperty: "results",    // The property which contains the total dataset size (optional)
1816     root: "rows",                // The property which contains an Array of row objects
1817     id: "id"                     // The property within each row object that provides an ID for the record (optional)
1818 }, RecordDef);
1819 </code></pre>
1820  * <p>
1821  * This would consume a JSON file like this:
1822  * <pre><code>
1823 { 'results': 2, 'rows': [
1824     { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
1825     { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
1826 }
1827 </code></pre>
1828  * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
1829  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
1830  * paged from the remote server.
1831  * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
1832  * @cfg {String} root name of the property which contains the Array of row objects.
1833  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
1834  * @cfg {Array} fields Array of field definition objects
1835  * @constructor
1836  * Create a new JsonReader
1837  * @param {Object} meta Metadata configuration options
1838  * @param {Object} recordType Either an Array of field definition objects,
1839  * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
1840  */
1841 Roo.data.JsonReader = function(meta, recordType){
1842     
1843     meta = meta || {};
1844     // set some defaults:
1845     Roo.applyIf(meta, {
1846         totalProperty: 'total',
1847         successProperty : 'success',
1848         root : 'data',
1849         id : 'id'
1850     });
1851     
1852     Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
1853 };
1854 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
1855     
1856     readerType : 'Json',
1857     
1858     /**
1859      * @prop {Boolean} metaFromRemote  - if the meta data was loaded from the remote source.
1860      * Used by Store query builder to append _requestMeta to params.
1861      * 
1862      */
1863     metaFromRemote : false,
1864     /**
1865      * This method is only used by a DataProxy which has retrieved data from a remote server.
1866      * @param {Object} response The XHR object which contains the JSON data in its responseText.
1867      * @return {Object} data A data block which is used by an Roo.data.Store object as
1868      * a cache of Roo.data.Records.
1869      */
1870     read : function(response){
1871         var json = response.responseText;
1872        
1873         var o = /* eval:var:o */ eval("("+json+")");
1874         if(!o) {
1875             throw {message: "JsonReader.read: Json object not found"};
1876         }
1877         
1878         if(o.metaData){
1879             
1880             delete this.ef;
1881             this.metaFromRemote = true;
1882             this.meta = o.metaData;
1883             this.recordType = Roo.data.Record.create(o.metaData.fields);
1884             this.onMetaChange(this.meta, this.recordType, o);
1885         }
1886         return this.readRecords(o);
1887     },
1888
1889     // private function a store will implement
1890     onMetaChange : function(meta, recordType, o){
1891
1892     },
1893
1894     /**
1895          * @ignore
1896          */
1897     simpleAccess: function(obj, subsc) {
1898         return obj[subsc];
1899     },
1900
1901         /**
1902          * @ignore
1903          */
1904     getJsonAccessor: function(){
1905         var re = /[\[\.]/;
1906         return function(expr) {
1907             try {
1908                 return(re.test(expr))
1909                     ? new Function("obj", "return obj." + expr)
1910                     : function(obj){
1911                         return obj[expr];
1912                     };
1913             } catch(e){}
1914             return Roo.emptyFn;
1915         };
1916     }(),
1917
1918     /**
1919      * Create a data block containing Roo.data.Records from an XML document.
1920      * @param {Object} o An object which contains an Array of row objects in the property specified
1921      * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
1922      * which contains the total size of the dataset.
1923      * @return {Object} data A data block which is used by an Roo.data.Store object as
1924      * a cache of Roo.data.Records.
1925      */
1926     readRecords : function(o){
1927         /**
1928          * After any data loads, the raw JSON data is available for further custom processing.
1929          * @type Object
1930          */
1931         this.o = o;
1932         var s = this.meta, Record = this.recordType,
1933             f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
1934
1935 //      Generate extraction functions for the totalProperty, the root, the id, and for each field
1936         if (!this.ef) {
1937             if(s.totalProperty) {
1938                     this.getTotal = this.getJsonAccessor(s.totalProperty);
1939                 }
1940                 if(s.successProperty) {
1941                     this.getSuccess = this.getJsonAccessor(s.successProperty);
1942                 }
1943                 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
1944                 if (s.id) {
1945                         var g = this.getJsonAccessor(s.id);
1946                         this.getId = function(rec) {
1947                                 var r = g(rec);  
1948                                 return (r === undefined || r === "") ? null : r;
1949                         };
1950                 } else {
1951                         this.getId = function(){return null;};
1952                 }
1953             this.ef = [];
1954             for(var jj = 0; jj < fl; jj++){
1955                 f = fi[jj];
1956                 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
1957                 this.ef[jj] = this.getJsonAccessor(map);
1958             }
1959         }
1960
1961         var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
1962         if(s.totalProperty){
1963             var vt = parseInt(this.getTotal(o), 10);
1964             if(!isNaN(vt)){
1965                 totalRecords = vt;
1966             }
1967         }
1968         if(s.successProperty){
1969             var vs = this.getSuccess(o);
1970             if(vs === false || vs === 'false'){
1971                 success = false;
1972             }
1973         }
1974         var records = [];
1975         for(var i = 0; i < c; i++){
1976             var n = root[i];
1977             var values = {};
1978             var id = this.getId(n);
1979             for(var j = 0; j < fl; j++){
1980                 f = fi[j];
1981                                 var v = this.ef[j](n);
1982                                 if (!f.convert) {
1983                                         Roo.log('missing convert for ' + f.name);
1984                                         Roo.log(f);
1985                                         continue;
1986                                 }
1987                                 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
1988             }
1989                         if (!Record) {
1990                                 return {
1991                                         raw : { errorMsg : "JSON Reader Error: fields or metadata not available to create Record" },
1992                                         success : false,
1993                                         records : [],
1994                                         totalRecords : 0
1995                                 };
1996                         }
1997             var record = new Record(values, id);
1998             record.json = n;
1999             records[i] = record;
2000         }
2001         return {
2002             raw : o,
2003             success : success,
2004             records : records,
2005             totalRecords : totalRecords
2006         };
2007     },
2008     // used when loading children.. @see loadDataFromChildren
2009     toLoadData: function(rec)
2010     {
2011         // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
2012         var data = typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
2013         return { data : data, total : data.length };
2014         
2015     }
2016 });/*
2017  * Based on:
2018  * Ext JS Library 1.1.1
2019  * Copyright(c) 2006-2007, Ext JS, LLC.
2020  *
2021  * Originally Released Under LGPL - original licence link has changed is not relivant.
2022  *
2023  * Fork - LGPL
2024  * <script type="text/javascript">
2025  */
2026
2027 /**
2028  * @class Roo.data.XmlReader
2029  * @extends Roo.data.DataReader
2030  * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
2031  * based on mappings in a provided Roo.data.Record constructor.<br><br>
2032  * <p>
2033  * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
2034  * header in the HTTP response must be set to "text/xml".</em>
2035  * <p>
2036  * Example code:
2037  * <pre><code>
2038 var RecordDef = Roo.data.Record.create([
2039    {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
2040    {name: 'occupation'}                 // This field will use "occupation" as the mapping.
2041 ]);
2042 var myReader = new Roo.data.XmlReader({
2043    totalRecords: "results", // The element which contains the total dataset size (optional)
2044    record: "row",           // The repeated element which contains row information
2045    id: "id"                 // The element within the row that provides an ID for the record (optional)
2046 }, RecordDef);
2047 </code></pre>
2048  * <p>
2049  * This would consume an XML file like this:
2050  * <pre><code>
2051 &lt;?xml?>
2052 &lt;dataset>
2053  &lt;results>2&lt;/results>
2054  &lt;row>
2055    &lt;id>1&lt;/id>
2056    &lt;name>Bill&lt;/name>
2057    &lt;occupation>Gardener&lt;/occupation>
2058  &lt;/row>
2059  &lt;row>
2060    &lt;id>2&lt;/id>
2061    &lt;name>Ben&lt;/name>
2062    &lt;occupation>Horticulturalist&lt;/occupation>
2063  &lt;/row>
2064 &lt;/dataset>
2065 </code></pre>
2066  * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
2067  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
2068  * paged from the remote server.
2069  * @cfg {String} record The DomQuery path to the repeated element which contains record information.
2070  * @cfg {String} success The DomQuery path to the success attribute used by forms.
2071  * @cfg {String} id The DomQuery path relative from the record element to the element that contains
2072  * a record identifier value.
2073  * @constructor
2074  * Create a new XmlReader
2075  * @param {Object} meta Metadata configuration options
2076  * @param {Mixed} recordType The definition of the data record type to produce.  This can be either a valid
2077  * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
2078  * Roo.data.Record.create.  See the {@link Roo.data.Record} class for more details.
2079  */
2080 Roo.data.XmlReader = function(meta, recordType){
2081     meta = meta || {};
2082     Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
2083 };
2084 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
2085     
2086     readerType : 'Xml',
2087     
2088     /**
2089      * This method is only used by a DataProxy which has retrieved data from a remote server.
2090          * @param {Object} response The XHR object which contains the parsed XML document.  The response is expected
2091          * to contain a method called 'responseXML' that returns an XML document object.
2092      * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
2093      * a cache of Roo.data.Records.
2094      */
2095     read : function(response){
2096         var doc = response.responseXML;
2097         if(!doc) {
2098             throw {message: "XmlReader.read: XML Document not available"};
2099         }
2100         return this.readRecords(doc);
2101     },
2102
2103     /**
2104      * Create a data block containing Roo.data.Records from an XML document.
2105          * @param {Object} doc A parsed XML document.
2106      * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
2107      * a cache of Roo.data.Records.
2108      */
2109     readRecords : function(doc){
2110         /**
2111          * After any data loads/reads, the raw XML Document is available for further custom processing.
2112          * @type XMLDocument
2113          */
2114         this.xmlData = doc;
2115         var root = doc.documentElement || doc;
2116         var q = Roo.DomQuery;
2117         var recordType = this.recordType, fields = recordType.prototype.fields;
2118         var sid = this.meta.id;
2119         var totalRecords = 0, success = true;
2120         if(this.meta.totalRecords){
2121             totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
2122         }
2123         
2124         if(this.meta.success){
2125             var sv = q.selectValue(this.meta.success, root, true);
2126             success = sv !== false && sv !== 'false';
2127         }
2128         var records = [];
2129         var ns = q.select(this.meta.record, root);
2130         for(var i = 0, len = ns.length; i < len; i++) {
2131                 var n = ns[i];
2132                 var values = {};
2133                 var id = sid ? q.selectValue(sid, n) : undefined;
2134                 for(var j = 0, jlen = fields.length; j < jlen; j++){
2135                     var f = fields.items[j];
2136                 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
2137                     v = f.convert(v);
2138                     values[f.name] = v;
2139                 }
2140                 var record = new recordType(values, id);
2141                 record.node = n;
2142                 records[records.length] = record;
2143             }
2144
2145             return {
2146                 success : success,
2147                 records : records,
2148                 totalRecords : totalRecords || records.length
2149             };
2150     }
2151 });/*
2152  * Based on:
2153  * Ext JS Library 1.1.1
2154  * Copyright(c) 2006-2007, Ext JS, LLC.
2155  *
2156  * Originally Released Under LGPL - original licence link has changed is not relivant.
2157  *
2158  * Fork - LGPL
2159  * <script type="text/javascript">
2160  */
2161
2162 /**
2163  * @class Roo.data.ArrayReader
2164  * @extends Roo.data.DataReader
2165  * Data reader class to create an Array of Roo.data.Record objects from an Array.
2166  * Each element of that Array represents a row of data fields. The
2167  * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
2168  * of the field definition if it exists, or the field's ordinal position in the definition.<br>
2169  * <p>
2170  * Example code:.
2171  * <pre><code>
2172 var RecordDef = Roo.data.Record.create([
2173     {name: 'name', mapping: 1},         // "mapping" only needed if an "id" field is present which
2174     {name: 'occupation', mapping: 2}    // precludes using the ordinal position as the index.
2175 ]);
2176 var myReader = new Roo.data.ArrayReader({
2177     id: 0                     // The subscript within row Array that provides an ID for the Record (optional)
2178 }, RecordDef);
2179 </code></pre>
2180  * <p>
2181  * This would consume an Array like this:
2182  * <pre><code>
2183 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
2184   </code></pre>
2185  
2186  * @constructor
2187  * Create a new JsonReader
2188  * @param {Object} meta Metadata configuration options.
2189  * @param {Object|Array} recordType Either an Array of field definition objects
2190  * 
2191  * @cfg {Array} fields Array of field definition objects
2192  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
2193  * as specified to {@link Roo.data.Record#create},
2194  * or an {@link Roo.data.Record} object
2195  *
2196  * 
2197  * created using {@link Roo.data.Record#create}.
2198  */
2199 Roo.data.ArrayReader = function(meta, recordType)
2200 {    
2201     Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType||meta.fields);
2202 };
2203
2204 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
2205     
2206       /**
2207      * Create a data block containing Roo.data.Records from an XML document.
2208      * @param {Object} o An Array of row objects which represents the dataset.
2209      * @return {Object} A data block which is used by an {@link Roo.data.Store} object as
2210      * a cache of Roo.data.Records.
2211      */
2212     readRecords : function(o)
2213     {
2214         var sid = this.meta ? this.meta.id : null;
2215         var recordType = this.recordType, fields = recordType.prototype.fields;
2216         var records = [];
2217         var root = o;
2218         for(var i = 0; i < root.length; i++){
2219             var n = root[i];
2220             var values = {};
2221             var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
2222             for(var j = 0, jlen = fields.length; j < jlen; j++){
2223                 var f = fields.items[j];
2224                 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
2225                 var v = n[k] !== undefined ? n[k] : f.defaultValue;
2226                 v = f.convert(v);
2227                 values[f.name] = v;
2228             }
2229             var record = new recordType(values, id);
2230             record.json = n;
2231             records[records.length] = record;
2232         }
2233         return {
2234             records : records,
2235             totalRecords : records.length
2236         };
2237     },
2238     // used when loading children.. @see loadDataFromChildren
2239     toLoadData: function(rec)
2240     {
2241         // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
2242         return typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
2243         
2244     }
2245     
2246     
2247 });/*
2248  * Based on:
2249  * Ext JS Library 1.1.1
2250  * Copyright(c) 2006-2007, Ext JS, LLC.
2251  *
2252  * Originally Released Under LGPL - original licence link has changed is not relivant.
2253  *
2254  * Fork - LGPL
2255  * <script type="text/javascript">
2256  */
2257
2258
2259 /**
2260  * @class Roo.data.Tree
2261  * @extends Roo.util.Observable
2262  * Represents a tree data structure and bubbles all the events for its nodes. The nodes
2263  * in the tree have most standard DOM functionality.
2264  * @constructor
2265  * @param {Node} root (optional) The root node
2266  */
2267 Roo.data.Tree = function(root){
2268    this.nodeHash = {};
2269    /**
2270     * The root node for this tree
2271     * @type Node
2272     */
2273    this.root = null;
2274    if(root){
2275        this.setRootNode(root);
2276    }
2277    this.addEvents({
2278        /**
2279         * @event append
2280         * Fires when a new child node is appended to a node in this tree.
2281         * @param {Tree} tree The owner tree
2282         * @param {Node} parent The parent node
2283         * @param {Node} node The newly appended node
2284         * @param {Number} index The index of the newly appended node
2285         */
2286        "append" : true,
2287        /**
2288         * @event remove
2289         * Fires when a child node is removed from a node in this tree.
2290         * @param {Tree} tree The owner tree
2291         * @param {Node} parent The parent node
2292         * @param {Node} node The child node removed
2293         */
2294        "remove" : true,
2295        /**
2296         * @event move
2297         * Fires when a node is moved to a new location in the tree
2298         * @param {Tree} tree The owner tree
2299         * @param {Node} node The node moved
2300         * @param {Node} oldParent The old parent of this node
2301         * @param {Node} newParent The new parent of this node
2302         * @param {Number} index The index it was moved to
2303         */
2304        "move" : true,
2305        /**
2306         * @event insert
2307         * Fires when a new child node is inserted in a node in this tree.
2308         * @param {Tree} tree The owner tree
2309         * @param {Node} parent The parent node
2310         * @param {Node} node The child node inserted
2311         * @param {Node} refNode The child node the node was inserted before
2312         */
2313        "insert" : true,
2314        /**
2315         * @event beforeappend
2316         * Fires before a new child is appended to a node in this tree, return false to cancel the append.
2317         * @param {Tree} tree The owner tree
2318         * @param {Node} parent The parent node
2319         * @param {Node} node The child node to be appended
2320         */
2321        "beforeappend" : true,
2322        /**
2323         * @event beforeremove
2324         * Fires before a child is removed from a node in this tree, return false to cancel the remove.
2325         * @param {Tree} tree The owner tree
2326         * @param {Node} parent The parent node
2327         * @param {Node} node The child node to be removed
2328         */
2329        "beforeremove" : true,
2330        /**
2331         * @event beforemove
2332         * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
2333         * @param {Tree} tree The owner tree
2334         * @param {Node} node The node being moved
2335         * @param {Node} oldParent The parent of the node
2336         * @param {Node} newParent The new parent the node is moving to
2337         * @param {Number} index The index it is being moved to
2338         */
2339        "beforemove" : true,
2340        /**
2341         * @event beforeinsert
2342         * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
2343         * @param {Tree} tree The owner tree
2344         * @param {Node} parent The parent node
2345         * @param {Node} node The child node to be inserted
2346         * @param {Node} refNode The child node the node is being inserted before
2347         */
2348        "beforeinsert" : true
2349    });
2350
2351     Roo.data.Tree.superclass.constructor.call(this);
2352 };
2353
2354 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
2355     pathSeparator: "/",
2356
2357     proxyNodeEvent : function(){
2358         return this.fireEvent.apply(this, arguments);
2359     },
2360
2361     /**
2362      * Returns the root node for this tree.
2363      * @return {Node}
2364      */
2365     getRootNode : function(){
2366         return this.root;
2367     },
2368
2369     /**
2370      * Sets the root node for this tree.
2371      * @param {Node} node
2372      * @return {Node}
2373      */
2374     setRootNode : function(node){
2375         this.root = node;
2376         node.ownerTree = this;
2377         node.isRoot = true;
2378         this.registerNode(node);
2379         return node;
2380     },
2381
2382     /**
2383      * Gets a node in this tree by its id.
2384      * @param {String} id
2385      * @return {Node}
2386      */
2387     getNodeById : function(id){
2388         return this.nodeHash[id];
2389     },
2390
2391     registerNode : function(node){
2392         this.nodeHash[node.id] = node;
2393     },
2394
2395     unregisterNode : function(node){
2396         delete this.nodeHash[node.id];
2397     },
2398
2399     toString : function(){
2400         return "[Tree"+(this.id?" "+this.id:"")+"]";
2401     }
2402 });
2403
2404 /**
2405  * @class Roo.data.Node
2406  * @extends Roo.util.Observable
2407  * @cfg {Boolean} leaf true if this node is a leaf and does not have children
2408  * @cfg {String} id The id for this node. If one is not specified, one is generated.
2409  * @constructor
2410  * @param {Object} attributes The attributes/config for the node
2411  */
2412 Roo.data.Node = function(attributes){
2413     /**
2414      * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
2415      * @type {Object}
2416      */
2417     this.attributes = attributes || {};
2418     this.leaf = this.attributes.leaf;
2419     /**
2420      * The node id. @type String
2421      */
2422     this.id = this.attributes.id;
2423     if(!this.id){
2424         this.id = Roo.id(null, "ynode-");
2425         this.attributes.id = this.id;
2426     }
2427      
2428     
2429     /**
2430      * All child nodes of this node. @type Array
2431      */
2432     this.childNodes = [];
2433     if(!this.childNodes.indexOf){ // indexOf is a must
2434         this.childNodes.indexOf = function(o){
2435             for(var i = 0, len = this.length; i < len; i++){
2436                 if(this[i] == o) {
2437                     return i;
2438                 }
2439             }
2440             return -1;
2441         };
2442     }
2443     /**
2444      * The parent node for this node. @type Node
2445      */
2446     this.parentNode = null;
2447     /**
2448      * The first direct child node of this node, or null if this node has no child nodes. @type Node
2449      */
2450     this.firstChild = null;
2451     /**
2452      * The last direct child node of this node, or null if this node has no child nodes. @type Node
2453      */
2454     this.lastChild = null;
2455     /**
2456      * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
2457      */
2458     this.previousSibling = null;
2459     /**
2460      * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
2461      */
2462     this.nextSibling = null;
2463
2464     this.addEvents({
2465        /**
2466         * @event append
2467         * Fires when a new child node is appended
2468         * @param {Tree} tree The owner tree
2469         * @param {Node} this This node
2470         * @param {Node} node The newly appended node
2471         * @param {Number} index The index of the newly appended node
2472         */
2473        "append" : true,
2474        /**
2475         * @event remove
2476         * Fires when a child node is removed
2477         * @param {Tree} tree The owner tree
2478         * @param {Node} this This node
2479         * @param {Node} node The removed node
2480         */
2481        "remove" : true,
2482        /**
2483         * @event move
2484         * Fires when this node is moved to a new location in the tree
2485         * @param {Tree} tree The owner tree
2486         * @param {Node} this This node
2487         * @param {Node} oldParent The old parent of this node
2488         * @param {Node} newParent The new parent of this node
2489         * @param {Number} index The index it was moved to
2490         */
2491        "move" : true,
2492        /**
2493         * @event insert
2494         * Fires when a new child node is inserted.
2495         * @param {Tree} tree The owner tree
2496         * @param {Node} this This node
2497         * @param {Node} node The child node inserted
2498         * @param {Node} refNode The child node the node was inserted before
2499         */
2500        "insert" : true,
2501        /**
2502         * @event beforeappend
2503         * Fires before a new child is appended, return false to cancel the append.
2504         * @param {Tree} tree The owner tree
2505         * @param {Node} this This node
2506         * @param {Node} node The child node to be appended
2507         */
2508        "beforeappend" : true,
2509        /**
2510         * @event beforeremove
2511         * Fires before a child is removed, return false to cancel the remove.
2512         * @param {Tree} tree The owner tree
2513         * @param {Node} this This node
2514         * @param {Node} node The child node to be removed
2515         */
2516        "beforeremove" : true,
2517        /**
2518         * @event beforemove
2519         * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
2520         * @param {Tree} tree The owner tree
2521         * @param {Node} this This node
2522         * @param {Node} oldParent The parent of this node
2523         * @param {Node} newParent The new parent this node is moving to
2524         * @param {Number} index The index it is being moved to
2525         */
2526        "beforemove" : true,
2527        /**
2528         * @event beforeinsert
2529         * Fires before a new child is inserted, return false to cancel the insert.
2530         * @param {Tree} tree The owner tree
2531         * @param {Node} this This node
2532         * @param {Node} node The child node to be inserted
2533         * @param {Node} refNode The child node the node is being inserted before
2534         */
2535        "beforeinsert" : true
2536    });
2537     this.listeners = this.attributes.listeners;
2538     Roo.data.Node.superclass.constructor.call(this);
2539 };
2540
2541 Roo.extend(Roo.data.Node, Roo.util.Observable, {
2542     fireEvent : function(evtName){
2543         // first do standard event for this node
2544         if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
2545             return false;
2546         }
2547         // then bubble it up to the tree if the event wasn't cancelled
2548         var ot = this.getOwnerTree();
2549         if(ot){
2550             if(ot.proxyNodeEvent.apply(ot, arguments) === false){
2551                 return false;
2552             }
2553         }
2554         return true;
2555     },
2556
2557     /**
2558      * Returns true if this node is a leaf
2559      * @return {Boolean}
2560      */
2561     isLeaf : function(){
2562         return this.leaf === true;
2563     },
2564
2565     // private
2566     setFirstChild : function(node){
2567         this.firstChild = node;
2568     },
2569
2570     //private
2571     setLastChild : function(node){
2572         this.lastChild = node;
2573     },
2574
2575
2576     /**
2577      * Returns true if this node is the last child of its parent
2578      * @return {Boolean}
2579      */
2580     isLast : function(){
2581        return (!this.parentNode ? true : this.parentNode.lastChild == this);
2582     },
2583
2584     /**
2585      * Returns true if this node is the first child of its parent
2586      * @return {Boolean}
2587      */
2588     isFirst : function(){
2589        return (!this.parentNode ? true : this.parentNode.firstChild == this);
2590     },
2591
2592     hasChildNodes : function(){
2593         return !this.isLeaf() && this.childNodes.length > 0;
2594     },
2595
2596     /**
2597      * Insert node(s) as the last child node of this node.
2598      * @param {Node/Array} node The node or Array of nodes to append
2599      * @return {Node} The appended node if single append, or null if an array was passed
2600      */
2601     appendChild : function(node){
2602         var multi = false;
2603         if(node instanceof Array){
2604             multi = node;
2605         }else if(arguments.length > 1){
2606             multi = arguments;
2607         }
2608         
2609         // if passed an array or multiple args do them one by one
2610         if(multi){
2611             for(var i = 0, len = multi.length; i < len; i++) {
2612                 this.appendChild(multi[i]);
2613             }
2614         }else{
2615             if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
2616                 return false;
2617             }
2618             var index = this.childNodes.length;
2619             var oldParent = node.parentNode;
2620             // it's a move, make sure we move it cleanly
2621             if(oldParent){
2622                 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
2623                     return false;
2624                 }
2625                 oldParent.removeChild(node);
2626             }
2627             
2628             index = this.childNodes.length;
2629             if(index == 0){
2630                 this.setFirstChild(node);
2631             }
2632             this.childNodes.push(node);
2633             node.parentNode = this;
2634             var ps = this.childNodes[index-1];
2635             if(ps){
2636                 node.previousSibling = ps;
2637                 ps.nextSibling = node;
2638             }else{
2639                 node.previousSibling = null;
2640             }
2641             node.nextSibling = null;
2642             this.setLastChild(node);
2643             node.setOwnerTree(this.getOwnerTree());
2644             this.fireEvent("append", this.ownerTree, this, node, index);
2645             if(this.ownerTree) {
2646                 this.ownerTree.fireEvent("appendnode", this, node, index);
2647             }
2648             if(oldParent){
2649                 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
2650             }
2651             return node;
2652         }
2653     },
2654
2655     /**
2656      * Removes a child node from this node.
2657      * @param {Node} node The node to remove
2658      * @return {Node} The removed node
2659      */
2660     removeChild : function(node){
2661         var index = this.childNodes.indexOf(node);
2662         if(index == -1){
2663             return false;
2664         }
2665         if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
2666             return false;
2667         }
2668
2669         // remove it from childNodes collection
2670         this.childNodes.splice(index, 1);
2671
2672         // update siblings
2673         if(node.previousSibling){
2674             node.previousSibling.nextSibling = node.nextSibling;
2675         }
2676         if(node.nextSibling){
2677             node.nextSibling.previousSibling = node.previousSibling;
2678         }
2679
2680         // update child refs
2681         if(this.firstChild == node){
2682             this.setFirstChild(node.nextSibling);
2683         }
2684         if(this.lastChild == node){
2685             this.setLastChild(node.previousSibling);
2686         }
2687
2688         node.setOwnerTree(null);
2689         // clear any references from the node
2690         node.parentNode = null;
2691         node.previousSibling = null;
2692         node.nextSibling = null;
2693         this.fireEvent("remove", this.ownerTree, this, node);
2694         return node;
2695     },
2696
2697     /**
2698      * Inserts the first node before the second node in this nodes childNodes collection.
2699      * @param {Node} node The node to insert
2700      * @param {Node} refNode The node to insert before (if null the node is appended)
2701      * @return {Node} The inserted node
2702      */
2703     insertBefore : function(node, refNode){
2704         if(!refNode){ // like standard Dom, refNode can be null for append
2705             return this.appendChild(node);
2706         }
2707         // nothing to do
2708         if(node == refNode){
2709             return false;
2710         }
2711
2712         if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
2713             return false;
2714         }
2715         var index = this.childNodes.indexOf(refNode);
2716         var oldParent = node.parentNode;
2717         var refIndex = index;
2718
2719         // when moving internally, indexes will change after remove
2720         if(oldParent == this && this.childNodes.indexOf(node) < index){
2721             refIndex--;
2722         }
2723
2724         // it's a move, make sure we move it cleanly
2725         if(oldParent){
2726             if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
2727                 return false;
2728             }
2729             oldParent.removeChild(node);
2730         }
2731         if(refIndex == 0){
2732             this.setFirstChild(node);
2733         }
2734         this.childNodes.splice(refIndex, 0, node);
2735         node.parentNode = this;
2736         var ps = this.childNodes[refIndex-1];
2737         if(ps){
2738             node.previousSibling = ps;
2739             ps.nextSibling = node;
2740         }else{
2741             node.previousSibling = null;
2742         }
2743         node.nextSibling = refNode;
2744         refNode.previousSibling = node;
2745         node.setOwnerTree(this.getOwnerTree());
2746         this.fireEvent("insert", this.ownerTree, this, node, refNode);
2747         if(oldParent){
2748             node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
2749         }
2750         return node;
2751     },
2752
2753     /**
2754      * Returns the child node at the specified index.
2755      * @param {Number} index
2756      * @return {Node}
2757      */
2758     item : function(index){
2759         return this.childNodes[index];
2760     },
2761
2762     /**
2763      * Replaces one child node in this node with another.
2764      * @param {Node} newChild The replacement node
2765      * @param {Node} oldChild The node to replace
2766      * @return {Node} The replaced node
2767      */
2768     replaceChild : function(newChild, oldChild){
2769         this.insertBefore(newChild, oldChild);
2770         this.removeChild(oldChild);
2771         return oldChild;
2772     },
2773
2774     /**
2775      * Returns the index of a child node
2776      * @param {Node} node
2777      * @return {Number} The index of the node or -1 if it was not found
2778      */
2779     indexOf : function(child){
2780         return this.childNodes.indexOf(child);
2781     },
2782
2783     /**
2784      * Returns the tree this node is in.
2785      * @return {Tree}
2786      */
2787     getOwnerTree : function(){
2788         // if it doesn't have one, look for one
2789         if(!this.ownerTree){
2790             var p = this;
2791             while(p){
2792                 if(p.ownerTree){
2793                     this.ownerTree = p.ownerTree;
2794                     break;
2795                 }
2796                 p = p.parentNode;
2797             }
2798         }
2799         return this.ownerTree;
2800     },
2801
2802     /**
2803      * Returns depth of this node (the root node has a depth of 0)
2804      * @return {Number}
2805      */
2806     getDepth : function(){
2807         var depth = 0;
2808         var p = this;
2809         while(p.parentNode){
2810             ++depth;
2811             p = p.parentNode;
2812         }
2813         return depth;
2814     },
2815
2816     // private
2817     setOwnerTree : function(tree){
2818         // if it's move, we need to update everyone
2819         if(tree != this.ownerTree){
2820             if(this.ownerTree){
2821                 this.ownerTree.unregisterNode(this);
2822             }
2823             this.ownerTree = tree;
2824             var cs = this.childNodes;
2825             for(var i = 0, len = cs.length; i < len; i++) {
2826                 cs[i].setOwnerTree(tree);
2827             }
2828             if(tree){
2829                 tree.registerNode(this);
2830             }
2831         }
2832     },
2833
2834     /**
2835      * Returns the path for this node. The path can be used to expand or select this node programmatically.
2836      * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
2837      * @return {String} The path
2838      */
2839     getPath : function(attr){
2840         attr = attr || "id";
2841         var p = this.parentNode;
2842         var b = [this.attributes[attr]];
2843         while(p){
2844             b.unshift(p.attributes[attr]);
2845             p = p.parentNode;
2846         }
2847         var sep = this.getOwnerTree().pathSeparator;
2848         return sep + b.join(sep);
2849     },
2850
2851     /**
2852      * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
2853      * function call will be the scope provided or the current node. The arguments to the function
2854      * will be the args provided or the current node. If the function returns false at any point,
2855      * the bubble is stopped.
2856      * @param {Function} fn The function to call
2857      * @param {Object} scope (optional) The scope of the function (defaults to current node)
2858      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2859      */
2860     bubble : function(fn, scope, args){
2861         var p = this;
2862         while(p){
2863             if(fn.call(scope || p, args || p) === false){
2864                 break;
2865             }
2866             p = p.parentNode;
2867         }
2868     },
2869
2870     /**
2871      * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
2872      * function call will be the scope provided or the current node. The arguments to the function
2873      * will be the args provided or the current node. If the function returns false at any point,
2874      * the cascade is stopped on that branch.
2875      * @param {Function} fn The function to call
2876      * @param {Object} scope (optional) The scope of the function (defaults to current node)
2877      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2878      */
2879     cascade : function(fn, scope, args){
2880         if(fn.call(scope || this, args || this) !== false){
2881             var cs = this.childNodes;
2882             for(var i = 0, len = cs.length; i < len; i++) {
2883                 cs[i].cascade(fn, scope, args);
2884             }
2885         }
2886     },
2887
2888     /**
2889      * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
2890      * function call will be the scope provided or the current node. The arguments to the function
2891      * will be the args provided or the current node. If the function returns false at any point,
2892      * the iteration stops.
2893      * @param {Function} fn The function to call
2894      * @param {Object} scope (optional) The scope of the function (defaults to current node)
2895      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2896      */
2897     eachChild : function(fn, scope, args){
2898         var cs = this.childNodes;
2899         for(var i = 0, len = cs.length; i < len; i++) {
2900                 if(fn.call(scope || this, args || cs[i]) === false){
2901                     break;
2902                 }
2903         }
2904     },
2905
2906     /**
2907      * Finds the first child that has the attribute with the specified value.
2908      * @param {String} attribute The attribute name
2909      * @param {Mixed} value The value to search for
2910      * @return {Node} The found child or null if none was found
2911      */
2912     findChild : function(attribute, value){
2913         var cs = this.childNodes;
2914         for(var i = 0, len = cs.length; i < len; i++) {
2915                 if(cs[i].attributes[attribute] == value){
2916                     return cs[i];
2917                 }
2918         }
2919         return null;
2920     },
2921
2922     /**
2923      * Finds the first child by a custom function. The child matches if the function passed
2924      * returns true.
2925      * @param {Function} fn
2926      * @param {Object} scope (optional)
2927      * @return {Node} The found child or null if none was found
2928      */
2929     findChildBy : function(fn, scope){
2930         var cs = this.childNodes;
2931         for(var i = 0, len = cs.length; i < len; i++) {
2932                 if(fn.call(scope||cs[i], cs[i]) === true){
2933                     return cs[i];
2934                 }
2935         }
2936         return null;
2937     },
2938
2939     /**
2940      * Sorts this nodes children using the supplied sort function
2941      * @param {Function} fn
2942      * @param {Object} scope (optional)
2943      */
2944     sort : function(fn, scope){
2945         var cs = this.childNodes;
2946         var len = cs.length;
2947         if(len > 0){
2948             var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
2949             cs.sort(sortFn);
2950             for(var i = 0; i < len; i++){
2951                 var n = cs[i];
2952                 n.previousSibling = cs[i-1];
2953                 n.nextSibling = cs[i+1];
2954                 if(i == 0){
2955                     this.setFirstChild(n);
2956                 }
2957                 if(i == len-1){
2958                     this.setLastChild(n);
2959                 }
2960             }
2961         }
2962     },
2963
2964     /**
2965      * Returns true if this node is an ancestor (at any point) of the passed node.
2966      * @param {Node} node
2967      * @return {Boolean}
2968      */
2969     contains : function(node){
2970         return node.isAncestor(this);
2971     },
2972
2973     /**
2974      * Returns true if the passed node is an ancestor (at any point) of this node.
2975      * @param {Node} node
2976      * @return {Boolean}
2977      */
2978     isAncestor : function(node){
2979         var p = this.parentNode;
2980         while(p){
2981             if(p == node){
2982                 return true;
2983             }
2984             p = p.parentNode;
2985         }
2986         return false;
2987     },
2988
2989     toString : function(){
2990         return "[Node"+(this.id?" "+this.id:"")+"]";
2991     }
2992 });/*
2993  * Based on:
2994  * Ext JS Library 1.1.1
2995  * Copyright(c) 2006-2007, Ext JS, LLC.
2996  *
2997  * Originally Released Under LGPL - original licence link has changed is not relivant.
2998  *
2999  * Fork - LGPL
3000  * <script type="text/javascript">
3001  */
3002
3003
3004 /**
3005  * @class Roo.Shadow
3006  * Simple class that can provide a shadow effect for any element.  Note that the element MUST be absolutely positioned,
3007  * and the shadow does not provide any shimming.  This should be used only in simple cases -- for more advanced
3008  * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
3009  * @constructor
3010  * Create a new Shadow
3011  * @param {Object} config The config object
3012  */
3013 Roo.Shadow = function(config){
3014     Roo.apply(this, config);
3015     if(typeof this.mode != "string"){
3016         this.mode = this.defaultMode;
3017     }
3018     var o = this.offset, a = {h: 0};
3019     var rad = Math.floor(this.offset/2);
3020     switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
3021         case "drop":
3022             a.w = 0;
3023             a.l = a.t = o;
3024             a.t -= 1;
3025             if(Roo.isIE){
3026                 a.l -= this.offset + rad;
3027                 a.t -= this.offset + rad;
3028                 a.w -= rad;
3029                 a.h -= rad;
3030                 a.t += 1;
3031             }
3032         break;
3033         case "sides":
3034             a.w = (o*2);
3035             a.l = -o;
3036             a.t = o-1;
3037             if(Roo.isIE){
3038                 a.l -= (this.offset - rad);
3039                 a.t -= this.offset + rad;
3040                 a.l += 1;
3041                 a.w -= (this.offset - rad)*2;
3042                 a.w -= rad + 1;
3043                 a.h -= 1;
3044             }
3045         break;
3046         case "frame":
3047             a.w = a.h = (o*2);
3048             a.l = a.t = -o;
3049             a.t += 1;
3050             a.h -= 2;
3051             if(Roo.isIE){
3052                 a.l -= (this.offset - rad);
3053                 a.t -= (this.offset - rad);
3054                 a.l += 1;
3055                 a.w -= (this.offset + rad + 1);
3056                 a.h -= (this.offset + rad);
3057                 a.h += 1;
3058             }
3059         break;
3060     };
3061
3062     this.adjusts = a;
3063 };
3064
3065 Roo.Shadow.prototype = {
3066     /**
3067      * @cfg {String} mode
3068      * The shadow display mode.  Supports the following options:<br />
3069      * sides: Shadow displays on both sides and bottom only<br />
3070      * frame: Shadow displays equally on all four sides<br />
3071      * drop: Traditional bottom-right drop shadow (default)
3072      */
3073     mode: false,
3074     /**
3075      * @cfg {String} offset
3076      * The number of pixels to offset the shadow from the element (defaults to 4)
3077      */
3078     offset: 4,
3079
3080     // private
3081     defaultMode: "drop",
3082
3083     /**
3084      * Displays the shadow under the target element
3085      * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
3086      */
3087     show : function(target){
3088         target = Roo.get(target);
3089         if(!this.el){
3090             this.el = Roo.Shadow.Pool.pull();
3091             if(this.el.dom.nextSibling != target.dom){
3092                 this.el.insertBefore(target);
3093             }
3094         }
3095         this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
3096         if(Roo.isIE){
3097             this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
3098         }
3099         this.realign(
3100             target.getLeft(true),
3101             target.getTop(true),
3102             target.getWidth(),
3103             target.getHeight()
3104         );
3105         this.el.dom.style.display = "block";
3106     },
3107
3108     /**
3109      * Returns true if the shadow is visible, else false
3110      */
3111     isVisible : function(){
3112         return this.el ? true : false;  
3113     },
3114
3115     /**
3116      * Direct alignment when values are already available. Show must be called at least once before
3117      * calling this method to ensure it is initialized.
3118      * @param {Number} left The target element left position
3119      * @param {Number} top The target element top position
3120      * @param {Number} width The target element width
3121      * @param {Number} height The target element height
3122      */
3123     realign : function(l, t, w, h){
3124         if(!this.el){
3125             return;
3126         }
3127         var a = this.adjusts, d = this.el.dom, s = d.style;
3128         var iea = 0;
3129         s.left = (l+a.l)+"px";
3130         s.top = (t+a.t)+"px";
3131         var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
3132  
3133         if(s.width != sws || s.height != shs){
3134             s.width = sws;
3135             s.height = shs;
3136             if(!Roo.isIE){
3137                 var cn = d.childNodes;
3138                 var sww = Math.max(0, (sw-12))+"px";
3139                 cn[0].childNodes[1].style.width = sww;
3140                 cn[1].childNodes[1].style.width = sww;
3141                 cn[2].childNodes[1].style.width = sww;
3142                 cn[1].style.height = Math.max(0, (sh-12))+"px";
3143             }
3144         }
3145     },
3146
3147     /**
3148      * Hides this shadow
3149      */
3150     hide : function(){
3151         if(this.el){
3152             this.el.dom.style.display = "none";
3153             Roo.Shadow.Pool.push(this.el);
3154             delete this.el;
3155         }
3156     },
3157
3158     /**
3159      * Adjust the z-index of this shadow
3160      * @param {Number} zindex The new z-index
3161      */
3162     setZIndex : function(z){
3163         this.zIndex = z;
3164         if(this.el){
3165             this.el.setStyle("z-index", z);
3166         }
3167     }
3168 };
3169
3170 // Private utility class that manages the internal Shadow cache
3171 Roo.Shadow.Pool = function(){
3172     var p = [];
3173     var markup = Roo.isIE ?
3174                  '<div class="x-ie-shadow"></div>' :
3175                  '<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>';
3176     return {
3177         pull : function(){
3178             var sh = p.shift();
3179             if(!sh){
3180                 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
3181                 sh.autoBoxAdjust = false;
3182             }
3183             return sh;
3184         },
3185
3186         push : function(sh){
3187             p.push(sh);
3188         }
3189     };
3190 }();/*
3191  * Based on:
3192  * Ext JS Library 1.1.1
3193  * Copyright(c) 2006-2007, Ext JS, LLC.
3194  *
3195  * Originally Released Under LGPL - original licence link has changed is not relivant.
3196  *
3197  * Fork - LGPL
3198  * <script type="text/javascript">
3199  */
3200
3201
3202 /**
3203  * @class Roo.SplitBar
3204  * @extends Roo.util.Observable
3205  * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
3206  * <br><br>
3207  * Usage:
3208  * <pre><code>
3209 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
3210                    Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
3211 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
3212 split.minSize = 100;
3213 split.maxSize = 600;
3214 split.animate = true;
3215 split.on('moved', splitterMoved);
3216 </code></pre>
3217  * @constructor
3218  * Create a new SplitBar
3219  * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar. 
3220  * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged 
3221  * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
3222  * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or  
3223                         Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
3224                         position of the SplitBar).
3225  */
3226 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
3227     
3228     /** @private */
3229     this.el = Roo.get(dragElement, true);
3230     this.el.dom.unselectable = "on";
3231     /** @private */
3232     this.resizingEl = Roo.get(resizingElement, true);
3233
3234     /**
3235      * @private
3236      * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
3237      * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
3238      * @type Number
3239      */
3240     this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
3241     
3242     /**
3243      * The minimum size of the resizing element. (Defaults to 0)
3244      * @type Number
3245      */
3246     this.minSize = 0;
3247     
3248     /**
3249      * The maximum size of the resizing element. (Defaults to 2000)
3250      * @type Number
3251      */
3252     this.maxSize = 2000;
3253     
3254     /**
3255      * Whether to animate the transition to the new size
3256      * @type Boolean
3257      */
3258     this.animate = false;
3259     
3260     /**
3261      * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
3262      * @type Boolean
3263      */
3264     this.useShim = false;
3265     
3266     /** @private */
3267     this.shim = null;
3268     
3269     if(!existingProxy){
3270         /** @private */
3271         this.proxy = Roo.SplitBar.createProxy(this.orientation);
3272     }else{
3273         this.proxy = Roo.get(existingProxy).dom;
3274     }
3275     /** @private */
3276     this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
3277     
3278     /** @private */
3279     this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
3280     
3281     /** @private */
3282     this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
3283     
3284     /** @private */
3285     this.dragSpecs = {};
3286     
3287     /**
3288      * @private The adapter to use to positon and resize elements
3289      */
3290     this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
3291     this.adapter.init(this);
3292     
3293     if(this.orientation == Roo.SplitBar.HORIZONTAL){
3294         /** @private */
3295         this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
3296         this.el.addClass("x-splitbar-h");
3297     }else{
3298         /** @private */
3299         this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
3300         this.el.addClass("x-splitbar-v");
3301     }
3302     
3303     this.addEvents({
3304         /**
3305          * @event resize
3306          * Fires when the splitter is moved (alias for {@link #event-moved})
3307          * @param {Roo.SplitBar} this
3308          * @param {Number} newSize the new width or height
3309          */
3310         "resize" : true,
3311         /**
3312          * @event moved
3313          * Fires when the splitter is moved
3314          * @param {Roo.SplitBar} this
3315          * @param {Number} newSize the new width or height
3316          */
3317         "moved" : true,
3318         /**
3319          * @event beforeresize
3320          * Fires before the splitter is dragged
3321          * @param {Roo.SplitBar} this
3322          */
3323         "beforeresize" : true,
3324
3325         "beforeapply" : true
3326     });
3327
3328     Roo.util.Observable.call(this);
3329 };
3330
3331 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
3332     onStartProxyDrag : function(x, y){
3333         this.fireEvent("beforeresize", this);
3334         if(!this.overlay){
3335             var o = Roo.DomHelper.insertFirst(document.body,  {cls: "x-drag-overlay", html: "&#160;"}, true);
3336             o.unselectable();
3337             o.enableDisplayMode("block");
3338             // all splitbars share the same overlay
3339             Roo.SplitBar.prototype.overlay = o;
3340         }
3341         this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
3342         this.overlay.show();
3343         Roo.get(this.proxy).setDisplayed("block");
3344         var size = this.adapter.getElementSize(this);
3345         this.activeMinSize = this.getMinimumSize();;
3346         this.activeMaxSize = this.getMaximumSize();;
3347         var c1 = size - this.activeMinSize;
3348         var c2 = Math.max(this.activeMaxSize - size, 0);
3349         if(this.orientation == Roo.SplitBar.HORIZONTAL){
3350             this.dd.resetConstraints();
3351             this.dd.setXConstraint(
3352                 this.placement == Roo.SplitBar.LEFT ? c1 : c2, 
3353                 this.placement == Roo.SplitBar.LEFT ? c2 : c1
3354             );
3355             this.dd.setYConstraint(0, 0);
3356         }else{
3357             this.dd.resetConstraints();
3358             this.dd.setXConstraint(0, 0);
3359             this.dd.setYConstraint(
3360                 this.placement == Roo.SplitBar.TOP ? c1 : c2, 
3361                 this.placement == Roo.SplitBar.TOP ? c2 : c1
3362             );
3363          }
3364         this.dragSpecs.startSize = size;
3365         this.dragSpecs.startPoint = [x, y];
3366         Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
3367     },
3368     
3369     /** 
3370      * @private Called after the drag operation by the DDProxy
3371      */
3372     onEndProxyDrag : function(e){
3373         Roo.get(this.proxy).setDisplayed(false);
3374         var endPoint = Roo.lib.Event.getXY(e);
3375         if(this.overlay){
3376             this.overlay.hide();
3377         }
3378         var newSize;
3379         if(this.orientation == Roo.SplitBar.HORIZONTAL){
3380             newSize = this.dragSpecs.startSize + 
3381                 (this.placement == Roo.SplitBar.LEFT ?
3382                     endPoint[0] - this.dragSpecs.startPoint[0] :
3383                     this.dragSpecs.startPoint[0] - endPoint[0]
3384                 );
3385         }else{
3386             newSize = this.dragSpecs.startSize + 
3387                 (this.placement == Roo.SplitBar.TOP ?
3388                     endPoint[1] - this.dragSpecs.startPoint[1] :
3389                     this.dragSpecs.startPoint[1] - endPoint[1]
3390                 );
3391         }
3392         newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
3393         if(newSize != this.dragSpecs.startSize){
3394             if(this.fireEvent('beforeapply', this, newSize) !== false){
3395                 this.adapter.setElementSize(this, newSize);
3396                 this.fireEvent("moved", this, newSize);
3397                 this.fireEvent("resize", this, newSize);
3398             }
3399         }
3400     },
3401     
3402     /**
3403      * Get the adapter this SplitBar uses
3404      * @return The adapter object
3405      */
3406     getAdapter : function(){
3407         return this.adapter;
3408     },
3409     
3410     /**
3411      * Set the adapter this SplitBar uses
3412      * @param {Object} adapter A SplitBar adapter object
3413      */
3414     setAdapter : function(adapter){
3415         this.adapter = adapter;
3416         this.adapter.init(this);
3417     },
3418     
3419     /**
3420      * Gets the minimum size for the resizing element
3421      * @return {Number} The minimum size
3422      */
3423     getMinimumSize : function(){
3424         return this.minSize;
3425     },
3426     
3427     /**
3428      * Sets the minimum size for the resizing element
3429      * @param {Number} minSize The minimum size
3430      */
3431     setMinimumSize : function(minSize){
3432         this.minSize = minSize;
3433     },
3434     
3435     /**
3436      * Gets the maximum size for the resizing element
3437      * @return {Number} The maximum size
3438      */
3439     getMaximumSize : function(){
3440         return this.maxSize;
3441     },
3442     
3443     /**
3444      * Sets the maximum size for the resizing element
3445      * @param {Number} maxSize The maximum size
3446      */
3447     setMaximumSize : function(maxSize){
3448         this.maxSize = maxSize;
3449     },
3450     
3451     /**
3452      * Sets the initialize size for the resizing element
3453      * @param {Number} size The initial size
3454      */
3455     setCurrentSize : function(size){
3456         var oldAnimate = this.animate;
3457         this.animate = false;
3458         this.adapter.setElementSize(this, size);
3459         this.animate = oldAnimate;
3460     },
3461     
3462     /**
3463      * Destroy this splitbar. 
3464      * @param {Boolean} removeEl True to remove the element
3465      */
3466     destroy : function(removeEl){
3467         if(this.shim){
3468             this.shim.remove();
3469         }
3470         this.dd.unreg();
3471         this.proxy.parentNode.removeChild(this.proxy);
3472         if(removeEl){
3473             this.el.remove();
3474         }
3475     }
3476 });
3477
3478 /**
3479  * @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.
3480  */
3481 Roo.SplitBar.createProxy = function(dir){
3482     var proxy = new Roo.Element(document.createElement("div"));
3483     proxy.unselectable();
3484     var cls = 'x-splitbar-proxy';
3485     proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
3486     document.body.appendChild(proxy.dom);
3487     return proxy.dom;
3488 };
3489
3490 /** 
3491  * @class Roo.SplitBar.BasicLayoutAdapter
3492  * Default Adapter. It assumes the splitter and resizing element are not positioned
3493  * elements and only gets/sets the width of the element. Generally used for table based layouts.
3494  */
3495 Roo.SplitBar.BasicLayoutAdapter = function(){
3496 };
3497
3498 Roo.SplitBar.BasicLayoutAdapter.prototype = {
3499     // do nothing for now
3500     init : function(s){
3501     
3502     },
3503     /**
3504      * Called before drag operations to get the current size of the resizing element. 
3505      * @param {Roo.SplitBar} s The SplitBar using this adapter
3506      */
3507      getElementSize : function(s){
3508         if(s.orientation == Roo.SplitBar.HORIZONTAL){
3509             return s.resizingEl.getWidth();
3510         }else{
3511             return s.resizingEl.getHeight();
3512         }
3513     },
3514     
3515     /**
3516      * Called after drag operations to set the size of the resizing element.
3517      * @param {Roo.SplitBar} s The SplitBar using this adapter
3518      * @param {Number} newSize The new size to set
3519      * @param {Function} onComplete A function to be invoked when resizing is complete
3520      */
3521     setElementSize : function(s, newSize, onComplete){
3522         if(s.orientation == Roo.SplitBar.HORIZONTAL){
3523             if(!s.animate){
3524                 s.resizingEl.setWidth(newSize);
3525                 if(onComplete){
3526                     onComplete(s, newSize);
3527                 }
3528             }else{
3529                 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
3530             }
3531         }else{
3532             
3533             if(!s.animate){
3534                 s.resizingEl.setHeight(newSize);
3535                 if(onComplete){
3536                     onComplete(s, newSize);
3537                 }
3538             }else{
3539                 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
3540             }
3541         }
3542     }
3543 };
3544
3545 /** 
3546  *@class Roo.SplitBar.AbsoluteLayoutAdapter
3547  * @extends Roo.SplitBar.BasicLayoutAdapter
3548  * Adapter that  moves the splitter element to align with the resized sizing element. 
3549  * Used with an absolute positioned SplitBar.
3550  * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
3551  * document.body, make sure you assign an id to the body element.
3552  */
3553 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
3554     this.basic = new Roo.SplitBar.BasicLayoutAdapter();
3555     this.container = Roo.get(container);
3556 };
3557
3558 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
3559     init : function(s){
3560         this.basic.init(s);
3561     },
3562     
3563     getElementSize : function(s){
3564         return this.basic.getElementSize(s);
3565     },
3566     
3567     setElementSize : function(s, newSize, onComplete){
3568         this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
3569     },
3570     
3571     moveSplitter : function(s){
3572         var yes = Roo.SplitBar;
3573         switch(s.placement){
3574             case yes.LEFT:
3575                 s.el.setX(s.resizingEl.getRight());
3576                 break;
3577             case yes.RIGHT:
3578                 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
3579                 break;
3580             case yes.TOP:
3581                 s.el.setY(s.resizingEl.getBottom());
3582                 break;
3583             case yes.BOTTOM:
3584                 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
3585                 break;
3586         }
3587     }
3588 };
3589
3590 /**
3591  * Orientation constant - Create a vertical SplitBar
3592  * @static
3593  * @type Number
3594  */
3595 Roo.SplitBar.VERTICAL = 1;
3596
3597 /**
3598  * Orientation constant - Create a horizontal SplitBar
3599  * @static
3600  * @type Number
3601  */
3602 Roo.SplitBar.HORIZONTAL = 2;
3603
3604 /**
3605  * Placement constant - The resizing element is to the left of the splitter element
3606  * @static
3607  * @type Number
3608  */
3609 Roo.SplitBar.LEFT = 1;
3610
3611 /**
3612  * Placement constant - The resizing element is to the right of the splitter element
3613  * @static
3614  * @type Number
3615  */
3616 Roo.SplitBar.RIGHT = 2;
3617
3618 /**
3619  * Placement constant - The resizing element is positioned above the splitter element
3620  * @static
3621  * @type Number
3622  */
3623 Roo.SplitBar.TOP = 3;
3624
3625 /**
3626  * Placement constant - The resizing element is positioned under splitter element
3627  * @static
3628  * @type Number
3629  */
3630 Roo.SplitBar.BOTTOM = 4;
3631 /*
3632  * Based on:
3633  * Ext JS Library 1.1.1
3634  * Copyright(c) 2006-2007, Ext JS, LLC.
3635  *
3636  * Originally Released Under LGPL - original licence link has changed is not relivant.
3637  *
3638  * Fork - LGPL
3639  * <script type="text/javascript">
3640  */
3641
3642 /**
3643  * @class Roo.View
3644  * @extends Roo.util.Observable
3645  * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template. 
3646  * This class also supports single and multi selection modes. <br>
3647  * Create a data model bound view:
3648  <pre><code>
3649  var store = new Roo.data.Store(...);
3650
3651  var view = new Roo.View({
3652     el : "my-element",
3653     tpl : '&lt;div id="{0}"&gt;{2} - {1}&lt;/div&gt;', // auto create template
3654  
3655     singleSelect: true,
3656     selectedClass: "ydataview-selected",
3657     store: store
3658  });
3659
3660  // listen for node click?
3661  view.on("click", function(vw, index, node, e){
3662  alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
3663  });
3664
3665  // load XML data
3666  dataModel.load("foobar.xml");
3667  </code></pre>
3668  For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
3669  * <br><br>
3670  * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
3671  * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
3672  * 
3673  * Note: old style constructor is still suported (container, template, config)
3674  * 
3675  * @constructor
3676  * Create a new View
3677  * @param {Object} config The config object
3678  * 
3679  */
3680 Roo.View = function(config, depreciated_tpl, depreciated_config){
3681     
3682     this.parent = false;
3683     
3684     if (typeof(depreciated_tpl) == 'undefined') {
3685         // new way.. - universal constructor.
3686         Roo.apply(this, config);
3687         this.el  = Roo.get(this.el);
3688     } else {
3689         // old format..
3690         this.el  = Roo.get(config);
3691         this.tpl = depreciated_tpl;
3692         Roo.apply(this, depreciated_config);
3693     }
3694     this.wrapEl  = this.el.wrap().wrap();
3695     ///this.el = this.wrapEla.appendChild(document.createElement("div"));
3696     
3697     
3698     if(typeof(this.tpl) == "string"){
3699         this.tpl = new Roo.Template(this.tpl);
3700     } else {
3701         // support xtype ctors..
3702         this.tpl = new Roo.factory(this.tpl, Roo);
3703     }
3704     
3705     
3706     this.tpl.compile();
3707     
3708     /** @private */
3709     this.addEvents({
3710         /**
3711          * @event beforeclick
3712          * Fires before a click is processed. Returns false to cancel the default action.
3713          * @param {Roo.View} this
3714          * @param {Number} index The index of the target node
3715          * @param {HTMLElement} node The target node
3716          * @param {Roo.EventObject} e The raw event object
3717          */
3718             "beforeclick" : true,
3719         /**
3720          * @event click
3721          * Fires when a template node is clicked.
3722          * @param {Roo.View} this
3723          * @param {Number} index The index of the target node
3724          * @param {HTMLElement} node The target node
3725          * @param {Roo.EventObject} e The raw event object
3726          */
3727             "click" : true,
3728         /**
3729          * @event dblclick
3730          * Fires when a template node is double clicked.
3731          * @param {Roo.View} this
3732          * @param {Number} index The index of the target node
3733          * @param {HTMLElement} node The target node
3734          * @param {Roo.EventObject} e The raw event object
3735          */
3736             "dblclick" : true,
3737         /**
3738          * @event contextmenu
3739          * Fires when a template node is right clicked.
3740          * @param {Roo.View} this
3741          * @param {Number} index The index of the target node
3742          * @param {HTMLElement} node The target node
3743          * @param {Roo.EventObject} e The raw event object
3744          */
3745             "contextmenu" : true,
3746         /**
3747          * @event selectionchange
3748          * Fires when the selected nodes change.
3749          * @param {Roo.View} this
3750          * @param {Array} selections Array of the selected nodes
3751          */
3752             "selectionchange" : true,
3753     
3754         /**
3755          * @event beforeselect
3756          * Fires before a selection is made. If any handlers return false, the selection is cancelled.
3757          * @param {Roo.View} this
3758          * @param {HTMLElement} node The node to be selected
3759          * @param {Array} selections Array of currently selected nodes
3760          */
3761             "beforeselect" : true,
3762         /**
3763          * @event preparedata
3764          * Fires on every row to render, to allow you to change the data.
3765          * @param {Roo.View} this
3766          * @param {Object} data to be rendered (change this)
3767          */
3768           "preparedata" : true
3769           
3770           
3771         });
3772
3773
3774
3775     this.el.on({
3776         "click": this.onClick,
3777         "dblclick": this.onDblClick,
3778         "contextmenu": this.onContextMenu,
3779         scope:this
3780     });
3781
3782     this.selections = [];
3783     this.nodes = [];
3784     this.cmp = new Roo.CompositeElementLite([]);
3785     if(this.store){
3786         this.store = Roo.factory(this.store, Roo.data);
3787         this.setStore(this.store, true);
3788     }
3789     
3790     if ( this.footer && this.footer.xtype) {
3791            
3792          var fctr = this.wrapEl.appendChild(document.createElement("div"));
3793         
3794         this.footer.dataSource = this.store;
3795         this.footer.container = fctr;
3796         this.footer = Roo.factory(this.footer, Roo);
3797         fctr.insertFirst(this.el);
3798         
3799         // this is a bit insane - as the paging toolbar seems to detach the el..
3800 //        dom.parentNode.parentNode.parentNode
3801          // they get detached?
3802     }
3803     
3804     
3805     Roo.View.superclass.constructor.call(this);
3806     
3807     
3808 };
3809
3810 Roo.extend(Roo.View, Roo.util.Observable, {
3811     
3812      /**
3813      * @cfg {Roo.data.Store} store Data store to load data from.
3814      */
3815     store : false,
3816     
3817     /**
3818      * @cfg {String|Roo.Element} el The container element.
3819      */
3820     el : '',
3821     
3822     /**
3823      * @cfg {String|Roo.Template} tpl The template used by this View 
3824      */
3825     tpl : false,
3826     /**
3827      * @cfg {String} dataName the named area of the template to use as the data area
3828      *                          Works with domtemplates roo-name="name"
3829      */
3830     dataName: false,
3831     /**
3832      * @cfg {String} selectedClass The css class to add to selected nodes
3833      */
3834     selectedClass : "x-view-selected",
3835      /**
3836      * @cfg {String} emptyText The empty text to show when nothing is loaded.
3837      */
3838     emptyText : "",
3839     
3840     /**
3841      * @cfg {String} text to display on mask (default Loading)
3842      */
3843     mask : false,
3844     /**
3845      * @cfg {Boolean} multiSelect Allow multiple selection
3846      */
3847     multiSelect : false,
3848     /**
3849      * @cfg {Boolean} singleSelect Allow single selection
3850      */
3851     singleSelect:  false,
3852     
3853     /**
3854      * @cfg {Boolean} toggleSelect - selecting 
3855      */
3856     toggleSelect : false,
3857     
3858     /**
3859      * @cfg {Boolean} tickable - selecting 
3860      */
3861     tickable : false,
3862     
3863     /**
3864      * Returns the element this view is bound to.
3865      * @return {Roo.Element}
3866      */
3867     getEl : function(){
3868         return this.wrapEl;
3869     },
3870     
3871     
3872
3873     /**
3874      * Refreshes the view. - called by datachanged on the store. - do not call directly.
3875      */
3876     refresh : function(){
3877         //Roo.log('refresh');
3878         var t = this.tpl;
3879         
3880         // if we are using something like 'domtemplate', then
3881         // the what gets used is:
3882         // t.applySubtemplate(NAME, data, wrapping data..)
3883         // the outer template then get' applied with
3884         //     the store 'extra data'
3885         // and the body get's added to the
3886         //      roo-name="data" node?
3887         //      <span class='roo-tpl-{name}'></span> ?????
3888         
3889         
3890         
3891         this.clearSelections();
3892         this.el.update("");
3893         var html = [];
3894         var records = this.store.getRange();
3895         if(records.length < 1) {
3896             
3897             // is this valid??  = should it render a template??
3898             
3899             this.el.update(this.emptyText);
3900             return;
3901         }
3902         var el = this.el;
3903         if (this.dataName) {
3904             this.el.update(t.apply(this.store.meta)); //????
3905             el = this.el.child('.roo-tpl-' + this.dataName);
3906         }
3907         
3908         for(var i = 0, len = records.length; i < len; i++){
3909             var data = this.prepareData(records[i].data, i, records[i]);
3910             this.fireEvent("preparedata", this, data, i, records[i]);
3911             
3912             var d = Roo.apply({}, data);
3913             
3914             if(this.tickable){
3915                 Roo.apply(d, {'roo-id' : Roo.id()});
3916                 
3917                 var _this = this;
3918             
3919                 Roo.each(this.parent.item, function(item){
3920                     if(item[_this.parent.valueField] != data[_this.parent.valueField]){
3921                         return;
3922                     }
3923                     Roo.apply(d, {'roo-data-checked' : 'checked'});
3924                 });
3925             }
3926             
3927             html[html.length] = Roo.util.Format.trim(
3928                 this.dataName ?
3929                     t.applySubtemplate(this.dataName, d, this.store.meta) :
3930                     t.apply(d)
3931             );
3932         }
3933         
3934         
3935         
3936         el.update(html.join(""));
3937         this.nodes = el.dom.childNodes;
3938         this.updateIndexes(0);
3939     },
3940     
3941
3942     /**
3943      * Function to override to reformat the data that is sent to
3944      * the template for each node.
3945      * DEPRICATED - use the preparedata event handler.
3946      * @param {Array/Object} data The raw data (array of colData for a data model bound view or
3947      * a JSON object for an UpdateManager bound view).
3948      */
3949     prepareData : function(data, index, record)
3950     {
3951         this.fireEvent("preparedata", this, data, index, record);
3952         return data;
3953     },
3954
3955     onUpdate : function(ds, record){
3956         // Roo.log('on update');   
3957         this.clearSelections();
3958         var index = this.store.indexOf(record);
3959         var n = this.nodes[index];
3960         this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
3961         n.parentNode.removeChild(n);
3962         this.updateIndexes(index, index);
3963     },
3964
3965     
3966     
3967 // --------- FIXME     
3968     onAdd : function(ds, records, index)
3969     {
3970         //Roo.log(['on Add', ds, records, index] );        
3971         this.clearSelections();
3972         if(this.nodes.length == 0){
3973             this.refresh();
3974             return;
3975         }
3976         var n = this.nodes[index];
3977         for(var i = 0, len = records.length; i < len; i++){
3978             var d = this.prepareData(records[i].data, i, records[i]);
3979             if(n){
3980                 this.tpl.insertBefore(n, d);
3981             }else{
3982                 
3983                 this.tpl.append(this.el, d);
3984             }
3985         }
3986         this.updateIndexes(index);
3987     },
3988
3989     onRemove : function(ds, record, index){
3990        // Roo.log('onRemove');
3991         this.clearSelections();
3992         var el = this.dataName  ?
3993             this.el.child('.roo-tpl-' + this.dataName) :
3994             this.el; 
3995         
3996         el.dom.removeChild(this.nodes[index]);
3997         this.updateIndexes(index);
3998     },
3999
4000     /**
4001      * Refresh an individual node.
4002      * @param {Number} index
4003      */
4004     refreshNode : function(index){
4005         this.onUpdate(this.store, this.store.getAt(index));
4006     },
4007
4008     updateIndexes : function(startIndex, endIndex){
4009         var ns = this.nodes;
4010         startIndex = startIndex || 0;
4011         endIndex = endIndex || ns.length - 1;
4012         for(var i = startIndex; i <= endIndex; i++){
4013             ns[i].nodeIndex = i;
4014         }
4015     },
4016
4017     /**
4018      * Changes the data store this view uses and refresh the view.
4019      * @param {Store} store
4020      */
4021     setStore : function(store, initial){
4022         if(!initial && this.store){
4023             this.store.un("datachanged", this.refresh);
4024             this.store.un("add", this.onAdd);
4025             this.store.un("remove", this.onRemove);
4026             this.store.un("update", this.onUpdate);
4027             this.store.un("clear", this.refresh);
4028             this.store.un("beforeload", this.onBeforeLoad);
4029             this.store.un("load", this.onLoad);
4030             this.store.un("loadexception", this.onLoad);
4031         }
4032         if(store){
4033           
4034             store.on("datachanged", this.refresh, this);
4035             store.on("add", this.onAdd, this);
4036             store.on("remove", this.onRemove, this);
4037             store.on("update", this.onUpdate, this);
4038             store.on("clear", this.refresh, this);
4039             store.on("beforeload", this.onBeforeLoad, this);
4040             store.on("load", this.onLoad, this);
4041             store.on("loadexception", this.onLoad, this);
4042         }
4043         
4044         if(store){
4045             this.refresh();
4046         }
4047     },
4048     /**
4049      * onbeforeLoad - masks the loading area.
4050      *
4051      */
4052     onBeforeLoad : function(store,opts)
4053     {
4054          //Roo.log('onBeforeLoad');   
4055         if (!opts.add) {
4056             this.el.update("");
4057         }
4058         this.el.mask(this.mask ? this.mask : "Loading" ); 
4059     },
4060     onLoad : function ()
4061     {
4062         this.el.unmask();
4063     },
4064     
4065
4066     /**
4067      * Returns the template node the passed child belongs to or null if it doesn't belong to one.
4068      * @param {HTMLElement} node
4069      * @return {HTMLElement} The template node
4070      */
4071     findItemFromChild : function(node){
4072         var el = this.dataName  ?
4073             this.el.child('.roo-tpl-' + this.dataName,true) :
4074             this.el.dom; 
4075         
4076         if(!node || node.parentNode == el){
4077                     return node;
4078             }
4079             var p = node.parentNode;
4080             while(p && p != el){
4081             if(p.parentNode == el){
4082                 return p;
4083             }
4084             p = p.parentNode;
4085         }
4086             return null;
4087     },
4088
4089     /** @ignore */
4090     onClick : function(e){
4091         var item = this.findItemFromChild(e.getTarget());
4092         if(item){
4093             var index = this.indexOf(item);
4094             if(this.onItemClick(item, index, e) !== false){
4095                 this.fireEvent("click", this, index, item, e);
4096             }
4097         }else{
4098             this.clearSelections();
4099         }
4100     },
4101
4102     /** @ignore */
4103     onContextMenu : function(e){
4104         var item = this.findItemFromChild(e.getTarget());
4105         if(item){
4106             this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
4107         }
4108     },
4109
4110     /** @ignore */
4111     onDblClick : function(e){
4112         var item = this.findItemFromChild(e.getTarget());
4113         if(item){
4114             this.fireEvent("dblclick", this, this.indexOf(item), item, e);
4115         }
4116     },
4117
4118     onItemClick : function(item, index, e)
4119     {
4120         if(this.fireEvent("beforeclick", this, index, item, e) === false){
4121             return false;
4122         }
4123         if (this.toggleSelect) {
4124             var m = this.isSelected(item) ? 'unselect' : 'select';
4125             //Roo.log(m);
4126             var _t = this;
4127             _t[m](item, true, false);
4128             return true;
4129         }
4130         if(this.multiSelect || this.singleSelect){
4131             if(this.multiSelect && e.shiftKey && this.lastSelection){
4132                 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
4133             }else{
4134                 this.select(item, this.multiSelect && e.ctrlKey);
4135                 this.lastSelection = item;
4136             }
4137             
4138             if(!this.tickable){
4139                 e.preventDefault();
4140             }
4141             
4142         }
4143         return true;
4144     },
4145
4146     /**
4147      * Get the number of selected nodes.
4148      * @return {Number}
4149      */
4150     getSelectionCount : function(){
4151         return this.selections.length;
4152     },
4153
4154     /**
4155      * Get the currently selected nodes.
4156      * @return {Array} An array of HTMLElements
4157      */
4158     getSelectedNodes : function(){
4159         return this.selections;
4160     },
4161
4162     /**
4163      * Get the indexes of the selected nodes.
4164      * @return {Array}
4165      */
4166     getSelectedIndexes : function(){
4167         var indexes = [], s = this.selections;
4168         for(var i = 0, len = s.length; i < len; i++){
4169             indexes.push(s[i].nodeIndex);
4170         }
4171         return indexes;
4172     },
4173
4174     /**
4175      * Clear all selections
4176      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
4177      */
4178     clearSelections : function(suppressEvent){
4179         if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
4180             this.cmp.elements = this.selections;
4181             this.cmp.removeClass(this.selectedClass);
4182             this.selections = [];
4183             if(!suppressEvent){
4184                 this.fireEvent("selectionchange", this, this.selections);
4185             }
4186         }
4187     },
4188
4189     /**
4190      * Returns true if the passed node is selected
4191      * @param {HTMLElement/Number} node The node or node index
4192      * @return {Boolean}
4193      */
4194     isSelected : function(node){
4195         var s = this.selections;
4196         if(s.length < 1){
4197             return false;
4198         }
4199         node = this.getNode(node);
4200         return s.indexOf(node) !== -1;
4201     },
4202
4203     /**
4204      * Selects nodes.
4205      * @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
4206      * @param {Boolean} keepExisting (optional) true to keep existing selections
4207      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
4208      */
4209     select : function(nodeInfo, keepExisting, suppressEvent){
4210         if(nodeInfo instanceof Array){
4211             if(!keepExisting){
4212                 this.clearSelections(true);
4213             }
4214             for(var i = 0, len = nodeInfo.length; i < len; i++){
4215                 this.select(nodeInfo[i], true, true);
4216             }
4217             return;
4218         } 
4219         var node = this.getNode(nodeInfo);
4220         if(!node || this.isSelected(node)){
4221             return; // already selected.
4222         }
4223         if(!keepExisting){
4224             this.clearSelections(true);
4225         }
4226         
4227         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
4228             Roo.fly(node).addClass(this.selectedClass);
4229             this.selections.push(node);
4230             if(!suppressEvent){
4231                 this.fireEvent("selectionchange", this, this.selections);
4232             }
4233         }
4234         
4235         
4236     },
4237       /**
4238      * Unselects nodes.
4239      * @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
4240      * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
4241      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
4242      */
4243     unselect : function(nodeInfo, keepExisting, suppressEvent)
4244     {
4245         if(nodeInfo instanceof Array){
4246             Roo.each(this.selections, function(s) {
4247                 this.unselect(s, nodeInfo);
4248             }, this);
4249             return;
4250         }
4251         var node = this.getNode(nodeInfo);
4252         if(!node || !this.isSelected(node)){
4253             //Roo.log("not selected");
4254             return; // not selected.
4255         }
4256         // fireevent???
4257         var ns = [];
4258         Roo.each(this.selections, function(s) {
4259             if (s == node ) {
4260                 Roo.fly(node).removeClass(this.selectedClass);
4261
4262                 return;
4263             }
4264             ns.push(s);
4265         },this);
4266         
4267         this.selections= ns;
4268         this.fireEvent("selectionchange", this, this.selections);
4269     },
4270
4271     /**
4272      * Gets a template node.
4273      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
4274      * @return {HTMLElement} The node or null if it wasn't found
4275      */
4276     getNode : function(nodeInfo){
4277         if(typeof nodeInfo == "string"){
4278             return document.getElementById(nodeInfo);
4279         }else if(typeof nodeInfo == "number"){
4280             return this.nodes[nodeInfo];
4281         }
4282         return nodeInfo;
4283     },
4284
4285     /**
4286      * Gets a range template nodes.
4287      * @param {Number} startIndex
4288      * @param {Number} endIndex
4289      * @return {Array} An array of nodes
4290      */
4291     getNodes : function(start, end){
4292         var ns = this.nodes;
4293         start = start || 0;
4294         end = typeof end == "undefined" ? ns.length - 1 : end;
4295         var nodes = [];
4296         if(start <= end){
4297             for(var i = start; i <= end; i++){
4298                 nodes.push(ns[i]);
4299             }
4300         } else{
4301             for(var i = start; i >= end; i--){
4302                 nodes.push(ns[i]);
4303             }
4304         }
4305         return nodes;
4306     },
4307
4308     /**
4309      * Finds the index of the passed node
4310      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
4311      * @return {Number} The index of the node or -1
4312      */
4313     indexOf : function(node){
4314         node = this.getNode(node);
4315         if(typeof node.nodeIndex == "number"){
4316             return node.nodeIndex;
4317         }
4318         var ns = this.nodes;
4319         for(var i = 0, len = ns.length; i < len; i++){
4320             if(ns[i] == node){
4321                 return i;
4322             }
4323         }
4324         return -1;
4325     }
4326 });
4327 /*
4328  * Based on:
4329  * Ext JS Library 1.1.1
4330  * Copyright(c) 2006-2007, Ext JS, LLC.
4331  *
4332  * Originally Released Under LGPL - original licence link has changed is not relivant.
4333  *
4334  * Fork - LGPL
4335  * <script type="text/javascript">
4336  */
4337
4338 /**
4339  * @class Roo.JsonView
4340  * @extends Roo.View
4341  * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
4342 <pre><code>
4343 var view = new Roo.JsonView({
4344     container: "my-element",
4345     tpl: '&lt;div id="{id}"&gt;{foo} - {bar}&lt;/div&gt;', // auto create template
4346     multiSelect: true, 
4347     jsonRoot: "data" 
4348 });
4349
4350 // listen for node click?
4351 view.on("click", function(vw, index, node, e){
4352     alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
4353 });
4354
4355 // direct load of JSON data
4356 view.load("foobar.php");
4357
4358 // Example from my blog list
4359 var tpl = new Roo.Template(
4360     '&lt;div class="entry"&gt;' +
4361     '&lt;a class="entry-title" href="{link}"&gt;{title}&lt;/a&gt;' +
4362     "&lt;h4&gt;{date} by {author} | {comments} Comments&lt;/h4&gt;{description}" +
4363     "&lt;/div&gt;&lt;hr /&gt;"
4364 );
4365
4366 var moreView = new Roo.JsonView({
4367     container :  "entry-list", 
4368     template : tpl,
4369     jsonRoot: "posts"
4370 });
4371 moreView.on("beforerender", this.sortEntries, this);
4372 moreView.load({
4373     url: "/blog/get-posts.php",
4374     params: "allposts=true",
4375     text: "Loading Blog Entries..."
4376 });
4377 </code></pre>
4378
4379 * Note: old code is supported with arguments : (container, template, config)
4380
4381
4382  * @constructor
4383  * Create a new JsonView
4384  * 
4385  * @param {Object} config The config object
4386  * 
4387  */
4388 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
4389     
4390     
4391     Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
4392
4393     var um = this.el.getUpdateManager();
4394     um.setRenderer(this);
4395     um.on("update", this.onLoad, this);
4396     um.on("failure", this.onLoadException, this);
4397
4398     /**
4399      * @event beforerender
4400      * Fires before rendering of the downloaded JSON data.
4401      * @param {Roo.JsonView} this
4402      * @param {Object} data The JSON data loaded
4403      */
4404     /**
4405      * @event load
4406      * Fires when data is loaded.
4407      * @param {Roo.JsonView} this
4408      * @param {Object} data The JSON data loaded
4409      * @param {Object} response The raw Connect response object
4410      */
4411     /**
4412      * @event loadexception
4413      * Fires when loading fails.
4414      * @param {Roo.JsonView} this
4415      * @param {Object} response The raw Connect response object
4416      */
4417     this.addEvents({
4418         'beforerender' : true,
4419         'load' : true,
4420         'loadexception' : true
4421     });
4422 };
4423 Roo.extend(Roo.JsonView, Roo.View, {
4424     /**
4425      * @type {String} The root property in the loaded JSON object that contains the data
4426      */
4427     jsonRoot : "",
4428
4429     /**
4430      * Refreshes the view.
4431      */
4432     refresh : function(){
4433         this.clearSelections();
4434         this.el.update("");
4435         var html = [];
4436         var o = this.jsonData;
4437         if(o && o.length > 0){
4438             for(var i = 0, len = o.length; i < len; i++){
4439                 var data = this.prepareData(o[i], i, o);
4440                 html[html.length] = this.tpl.apply(data);
4441             }
4442         }else{
4443             html.push(this.emptyText);
4444         }
4445         this.el.update(html.join(""));
4446         this.nodes = this.el.dom.childNodes;
4447         this.updateIndexes(0);
4448     },
4449
4450     /**
4451      * 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.
4452      * @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:
4453      <pre><code>
4454      view.load({
4455          url: "your-url.php",
4456          params: {param1: "foo", param2: "bar"}, // or a URL encoded string
4457          callback: yourFunction,
4458          scope: yourObject, //(optional scope)
4459          discardUrl: false,
4460          nocache: false,
4461          text: "Loading...",
4462          timeout: 30,
4463          scripts: false
4464      });
4465      </code></pre>
4466      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
4467      * 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.
4468      * @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}
4469      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
4470      * @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.
4471      */
4472     load : function(){
4473         var um = this.el.getUpdateManager();
4474         um.update.apply(um, arguments);
4475     },
4476
4477     // note - render is a standard framework call...
4478     // using it for the response is really flaky... - it's called by UpdateManager normally, except when called by the XComponent/addXtype.
4479     render : function(el, response){
4480         
4481         this.clearSelections();
4482         this.el.update("");
4483         var o;
4484         try{
4485             if (response != '') {
4486                 o = Roo.util.JSON.decode(response.responseText);
4487                 if(this.jsonRoot){
4488                     
4489                     o = o[this.jsonRoot];
4490                 }
4491             }
4492         } catch(e){
4493         }
4494         /**
4495          * The current JSON data or null
4496          */
4497         this.jsonData = o;
4498         this.beforeRender();
4499         this.refresh();
4500     },
4501
4502 /**
4503  * Get the number of records in the current JSON dataset
4504  * @return {Number}
4505  */
4506     getCount : function(){
4507         return this.jsonData ? this.jsonData.length : 0;
4508     },
4509
4510 /**
4511  * Returns the JSON object for the specified node(s)
4512  * @param {HTMLElement/Array} node The node or an array of nodes
4513  * @return {Object/Array} If you pass in an array, you get an array back, otherwise
4514  * you get the JSON object for the node
4515  */
4516     getNodeData : function(node){
4517         if(node instanceof Array){
4518             var data = [];
4519             for(var i = 0, len = node.length; i < len; i++){
4520                 data.push(this.getNodeData(node[i]));
4521             }
4522             return data;
4523         }
4524         return this.jsonData[this.indexOf(node)] || null;
4525     },
4526
4527     beforeRender : function(){
4528         this.snapshot = this.jsonData;
4529         if(this.sortInfo){
4530             this.sort.apply(this, this.sortInfo);
4531         }
4532         this.fireEvent("beforerender", this, this.jsonData);
4533     },
4534
4535     onLoad : function(el, o){
4536         this.fireEvent("load", this, this.jsonData, o);
4537     },
4538
4539     onLoadException : function(el, o){
4540         this.fireEvent("loadexception", this, o);
4541     },
4542
4543 /**
4544  * Filter the data by a specific property.
4545  * @param {String} property A property on your JSON objects
4546  * @param {String/RegExp} value Either string that the property values
4547  * should start with, or a RegExp to test against the property
4548  */
4549     filter : function(property, value){
4550         if(this.jsonData){
4551             var data = [];
4552             var ss = this.snapshot;
4553             if(typeof value == "string"){
4554                 var vlen = value.length;
4555                 if(vlen == 0){
4556                     this.clearFilter();
4557                     return;
4558                 }
4559                 value = value.toLowerCase();
4560                 for(var i = 0, len = ss.length; i < len; i++){
4561                     var o = ss[i];
4562                     if(o[property].substr(0, vlen).toLowerCase() == value){
4563                         data.push(o);
4564                     }
4565                 }
4566             } else if(value.exec){ // regex?
4567                 for(var i = 0, len = ss.length; i < len; i++){
4568                     var o = ss[i];
4569                     if(value.test(o[property])){
4570                         data.push(o);
4571                     }
4572                 }
4573             } else{
4574                 return;
4575             }
4576             this.jsonData = data;
4577             this.refresh();
4578         }
4579     },
4580
4581 /**
4582  * Filter by a function. The passed function will be called with each
4583  * object in the current dataset. If the function returns true the value is kept,
4584  * otherwise it is filtered.
4585  * @param {Function} fn
4586  * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
4587  */
4588     filterBy : function(fn, scope){
4589         if(this.jsonData){
4590             var data = [];
4591             var ss = this.snapshot;
4592             for(var i = 0, len = ss.length; i < len; i++){
4593                 var o = ss[i];
4594                 if(fn.call(scope || this, o)){
4595                     data.push(o);
4596                 }
4597             }
4598             this.jsonData = data;
4599             this.refresh();
4600         }
4601     },
4602
4603 /**
4604  * Clears the current filter.
4605  */
4606     clearFilter : function(){
4607         if(this.snapshot && this.jsonData != this.snapshot){
4608             this.jsonData = this.snapshot;
4609             this.refresh();
4610         }
4611     },
4612
4613
4614 /**
4615  * Sorts the data for this view and refreshes it.
4616  * @param {String} property A property on your JSON objects to sort on
4617  * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
4618  * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
4619  */
4620     sort : function(property, dir, sortType){
4621         this.sortInfo = Array.prototype.slice.call(arguments, 0);
4622         if(this.jsonData){
4623             var p = property;
4624             var dsc = dir && dir.toLowerCase() == "desc";
4625             var f = function(o1, o2){
4626                 var v1 = sortType ? sortType(o1[p]) : o1[p];
4627                 var v2 = sortType ? sortType(o2[p]) : o2[p];
4628                 ;
4629                 if(v1 < v2){
4630                     return dsc ? +1 : -1;
4631                 } else if(v1 > v2){
4632                     return dsc ? -1 : +1;
4633                 } else{
4634                     return 0;
4635                 }
4636             };
4637             this.jsonData.sort(f);
4638             this.refresh();
4639             if(this.jsonData != this.snapshot){
4640                 this.snapshot.sort(f);
4641             }
4642         }
4643     }
4644 });/*
4645  * Based on:
4646  * Ext JS Library 1.1.1
4647  * Copyright(c) 2006-2007, Ext JS, LLC.
4648  *
4649  * Originally Released Under LGPL - original licence link has changed is not relivant.
4650  *
4651  * Fork - LGPL
4652  * <script type="text/javascript">
4653  */
4654  
4655
4656 /**
4657  * @class Roo.ColorPalette
4658  * @extends Roo.Component
4659  * Simple color palette class for choosing colors.  The palette can be rendered to any container.<br />
4660  * Here's an example of typical usage:
4661  * <pre><code>
4662 var cp = new Roo.ColorPalette({value:'993300'});  // initial selected color
4663 cp.render('my-div');
4664
4665 cp.on('select', function(palette, selColor){
4666     // do something with selColor
4667 });
4668 </code></pre>
4669  * @constructor
4670  * Create a new ColorPalette
4671  * @param {Object} config The config object
4672  */
4673 Roo.ColorPalette = function(config){
4674     Roo.ColorPalette.superclass.constructor.call(this, config);
4675     this.addEvents({
4676         /**
4677              * @event select
4678              * Fires when a color is selected
4679              * @param {ColorPalette} this
4680              * @param {String} color The 6-digit color hex code (without the # symbol)
4681              */
4682         select: true
4683     });
4684
4685     if(this.handler){
4686         this.on("select", this.handler, this.scope, true);
4687     }
4688 };
4689 Roo.extend(Roo.ColorPalette, Roo.Component, {
4690     /**
4691      * @cfg {String} itemCls
4692      * The CSS class to apply to the containing element (defaults to "x-color-palette")
4693      */
4694     itemCls : "x-color-palette",
4695     /**
4696      * @cfg {String} value
4697      * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol).  Note that
4698      * the hex codes are case-sensitive.
4699      */
4700     value : null,
4701     clickEvent:'click',
4702     // private
4703     ctype: "Roo.ColorPalette",
4704
4705     /**
4706      * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
4707      */
4708     allowReselect : false,
4709
4710     /**
4711      * <p>An array of 6-digit color hex code strings (without the # symbol).  This array can contain any number
4712      * of colors, and each hex code should be unique.  The width of the palette is controlled via CSS by adjusting
4713      * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
4714      * of colors with the width setting until the box is symmetrical.</p>
4715      * <p>You can override individual colors if needed:</p>
4716      * <pre><code>
4717 var cp = new Roo.ColorPalette();
4718 cp.colors[0] = "FF0000";  // change the first box to red
4719 </code></pre>
4720
4721 Or you can provide a custom array of your own for complete control:
4722 <pre><code>
4723 var cp = new Roo.ColorPalette();
4724 cp.colors = ["000000", "993300", "333300"];
4725 </code></pre>
4726      * @type Array
4727      */
4728     colors : [
4729         "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
4730         "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
4731         "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
4732         "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
4733         "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
4734     ],
4735
4736     // private
4737     onRender : function(container, position){
4738         var t = new Roo.MasterTemplate(
4739             '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on">&#160;</span></em></a></tpl>'
4740         );
4741         var c = this.colors;
4742         for(var i = 0, len = c.length; i < len; i++){
4743             t.add([c[i]]);
4744         }
4745         var el = document.createElement("div");
4746         el.className = this.itemCls;
4747         t.overwrite(el);
4748         container.dom.insertBefore(el, position);
4749         this.el = Roo.get(el);
4750         this.el.on(this.clickEvent, this.handleClick,  this, {delegate: "a"});
4751         if(this.clickEvent != 'click'){
4752             this.el.on('click', Roo.emptyFn,  this, {delegate: "a", preventDefault:true});
4753         }
4754     },
4755
4756     // private
4757     afterRender : function(){
4758         Roo.ColorPalette.superclass.afterRender.call(this);
4759         if(this.value){
4760             var s = this.value;
4761             this.value = null;
4762             this.select(s);
4763         }
4764     },
4765
4766     // private
4767     handleClick : function(e, t){
4768         e.preventDefault();
4769         if(!this.disabled){
4770             var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
4771             this.select(c.toUpperCase());
4772         }
4773     },
4774
4775     /**
4776      * Selects the specified color in the palette (fires the select event)
4777      * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
4778      */
4779     select : function(color){
4780         color = color.replace("#", "");
4781         if(color != this.value || this.allowReselect){
4782             var el = this.el;
4783             if(this.value){
4784                 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
4785             }
4786             el.child("a.color-"+color).addClass("x-color-palette-sel");
4787             this.value = color;
4788             this.fireEvent("select", this, color);
4789         }
4790     }
4791 });/*
4792  * Based on:
4793  * Ext JS Library 1.1.1
4794  * Copyright(c) 2006-2007, Ext JS, LLC.
4795  *
4796  * Originally Released Under LGPL - original licence link has changed is not relivant.
4797  *
4798  * Fork - LGPL
4799  * <script type="text/javascript">
4800  */
4801  
4802 /**
4803  * @class Roo.DatePicker
4804  * @extends Roo.Component
4805  * Simple date picker class.
4806  * @constructor
4807  * Create a new DatePicker
4808  * @param {Object} config The config object
4809  */
4810 Roo.DatePicker = function(config){
4811     Roo.DatePicker.superclass.constructor.call(this, config);
4812
4813     this.value = config && config.value ?
4814                  config.value.clearTime() : new Date().clearTime();
4815
4816     this.addEvents({
4817         /**
4818              * @event select
4819              * Fires when a date is selected
4820              * @param {DatePicker} this
4821              * @param {Date} date The selected date
4822              */
4823         'select': true,
4824         /**
4825              * @event monthchange
4826              * Fires when the displayed month changes 
4827              * @param {DatePicker} this
4828              * @param {Date} date The selected month
4829              */
4830         'monthchange': true
4831     });
4832
4833     if(this.handler){
4834         this.on("select", this.handler,  this.scope || this);
4835     }
4836     // build the disabledDatesRE
4837     if(!this.disabledDatesRE && this.disabledDates){
4838         var dd = this.disabledDates;
4839         var re = "(?:";
4840         for(var i = 0; i < dd.length; i++){
4841             re += dd[i];
4842             if(i != dd.length-1) {
4843                 re += "|";
4844             }
4845         }
4846         this.disabledDatesRE = new RegExp(re + ")");
4847     }
4848 };
4849
4850 Roo.extend(Roo.DatePicker, Roo.Component, {
4851     /**
4852      * @cfg {String} todayText
4853      * The text to display on the button that selects the current date (defaults to "Today")
4854      */
4855     todayText : "Today",
4856     /**
4857      * @cfg {String} okText
4858      * The text to display on the ok button
4859      */
4860     okText : "&#160;OK&#160;", // &#160; to give the user extra clicking room
4861     /**
4862      * @cfg {String} cancelText
4863      * The text to display on the cancel button
4864      */
4865     cancelText : "Cancel",
4866     /**
4867      * @cfg {String} todayTip
4868      * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
4869      */
4870     todayTip : "{0} (Spacebar)",
4871     /**
4872      * @cfg {Date} minDate
4873      * Minimum allowable date (JavaScript date object, defaults to null)
4874      */
4875     minDate : null,
4876     /**
4877      * @cfg {Date} maxDate
4878      * Maximum allowable date (JavaScript date object, defaults to null)
4879      */
4880     maxDate : null,
4881     /**
4882      * @cfg {String} minText
4883      * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
4884      */
4885     minText : "This date is before the minimum date",
4886     /**
4887      * @cfg {String} maxText
4888      * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
4889      */
4890     maxText : "This date is after the maximum date",
4891     /**
4892      * @cfg {String} format
4893      * The default date format string which can be overriden for localization support.  The format must be
4894      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
4895      */
4896     format : "m/d/y",
4897     /**
4898      * @cfg {Array} disabledDays
4899      * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
4900      */
4901     disabledDays : null,
4902     /**
4903      * @cfg {String} disabledDaysText
4904      * The tooltip to display when the date falls on a disabled day (defaults to "")
4905      */
4906     disabledDaysText : "",
4907     /**
4908      * @cfg {RegExp} disabledDatesRE
4909      * JavaScript regular expression used to disable a pattern of dates (defaults to null)
4910      */
4911     disabledDatesRE : null,
4912     /**
4913      * @cfg {String} disabledDatesText
4914      * The tooltip text to display when the date falls on a disabled date (defaults to "")
4915      */
4916     disabledDatesText : "",
4917     /**
4918      * @cfg {Boolean} constrainToViewport
4919      * True to constrain the date picker to the viewport (defaults to true)
4920      */
4921     constrainToViewport : true,
4922     /**
4923      * @cfg {Array} monthNames
4924      * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
4925      */
4926     monthNames : Date.monthNames,
4927     /**
4928      * @cfg {Array} dayNames
4929      * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
4930      */
4931     dayNames : Date.dayNames,
4932     /**
4933      * @cfg {String} nextText
4934      * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
4935      */
4936     nextText: 'Next Month (Control+Right)',
4937     /**
4938      * @cfg {String} prevText
4939      * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
4940      */
4941     prevText: 'Previous Month (Control+Left)',
4942     /**
4943      * @cfg {String} monthYearText
4944      * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
4945      */
4946     monthYearText: 'Choose a month (Control+Up/Down to move years)',
4947     /**
4948      * @cfg {Number} startDay
4949      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
4950      */
4951     startDay : 0,
4952     /**
4953      * @cfg {Bool} showClear
4954      * Show a clear button (usefull for date form elements that can be blank.)
4955      */
4956     
4957     showClear: false,
4958     
4959     /**
4960      * Sets the value of the date field
4961      * @param {Date} value The date to set
4962      */
4963     setValue : function(value){
4964         var old = this.value;
4965         
4966         if (typeof(value) == 'string') {
4967          
4968             value = Date.parseDate(value, this.format);
4969         }
4970         if (!value) {
4971             value = new Date();
4972         }
4973         
4974         this.value = value.clearTime(true);
4975         if(this.el){
4976             this.update(this.value);
4977         }
4978     },
4979
4980     /**
4981      * Gets the current selected value of the date field
4982      * @return {Date} The selected date
4983      */
4984     getValue : function(){
4985         return this.value;
4986     },
4987
4988     // private
4989     focus : function(){
4990         if(this.el){
4991             this.update(this.activeDate);
4992         }
4993     },
4994
4995     // privateval
4996     onRender : function(container, position){
4997         
4998         var m = [
4999              '<table cellspacing="0">',
5000                 '<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>',
5001                 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
5002         var dn = this.dayNames;
5003         for(var i = 0; i < 7; i++){
5004             var d = this.startDay+i;
5005             if(d > 6){
5006                 d = d-7;
5007             }
5008             m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
5009         }
5010         m[m.length] = "</tr></thead><tbody><tr>";
5011         for(var i = 0; i < 42; i++) {
5012             if(i % 7 == 0 && i != 0){
5013                 m[m.length] = "</tr><tr>";
5014             }
5015             m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
5016         }
5017         m[m.length] = '</tr></tbody></table></td></tr><tr>'+
5018             '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
5019
5020         var el = document.createElement("div");
5021         el.className = "x-date-picker";
5022         el.innerHTML = m.join("");
5023
5024         container.dom.insertBefore(el, position);
5025
5026         this.el = Roo.get(el);
5027         this.eventEl = Roo.get(el.firstChild);
5028
5029         new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
5030             handler: this.showPrevMonth,
5031             scope: this,
5032             preventDefault:true,
5033             stopDefault:true
5034         });
5035
5036         new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
5037             handler: this.showNextMonth,
5038             scope: this,
5039             preventDefault:true,
5040             stopDefault:true
5041         });
5042
5043         this.eventEl.on("mousewheel", this.handleMouseWheel,  this);
5044
5045         this.monthPicker = this.el.down('div.x-date-mp');
5046         this.monthPicker.enableDisplayMode('block');
5047         
5048         var kn = new Roo.KeyNav(this.eventEl, {
5049             "left" : function(e){
5050                 e.ctrlKey ?
5051                     this.showPrevMonth() :
5052                     this.update(this.activeDate.add("d", -1));
5053             },
5054
5055             "right" : function(e){
5056                 e.ctrlKey ?
5057                     this.showNextMonth() :
5058                     this.update(this.activeDate.add("d", 1));
5059             },
5060
5061             "up" : function(e){
5062                 e.ctrlKey ?
5063                     this.showNextYear() :
5064                     this.update(this.activeDate.add("d", -7));
5065             },
5066
5067             "down" : function(e){
5068                 e.ctrlKey ?
5069                     this.showPrevYear() :
5070                     this.update(this.activeDate.add("d", 7));
5071             },
5072
5073             "pageUp" : function(e){
5074                 this.showNextMonth();
5075             },
5076
5077             "pageDown" : function(e){
5078                 this.showPrevMonth();
5079             },
5080
5081             "enter" : function(e){
5082                 e.stopPropagation();
5083                 return true;
5084             },
5085
5086             scope : this
5087         });
5088
5089         this.eventEl.on("click", this.handleDateClick,  this, {delegate: "a.x-date-date"});
5090
5091         this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday,  this);
5092
5093         this.el.unselectable();
5094         
5095         this.cells = this.el.select("table.x-date-inner tbody td");
5096         this.textNodes = this.el.query("table.x-date-inner tbody span");
5097
5098         this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
5099             text: "&#160;",
5100             tooltip: this.monthYearText
5101         });
5102
5103         this.mbtn.on('click', this.showMonthPicker, this);
5104         this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
5105
5106
5107         var today = (new Date()).dateFormat(this.format);
5108         
5109         var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
5110         if (this.showClear) {
5111             baseTb.add( new Roo.Toolbar.Fill());
5112         }
5113         baseTb.add({
5114             text: String.format(this.todayText, today),
5115             tooltip: String.format(this.todayTip, today),
5116             handler: this.selectToday,
5117             scope: this
5118         });
5119         
5120         //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
5121             
5122         //});
5123         if (this.showClear) {
5124             
5125             baseTb.add( new Roo.Toolbar.Fill());
5126             baseTb.add({
5127                 text: '&#160;',
5128                 cls: 'x-btn-icon x-btn-clear',
5129                 handler: function() {
5130                     //this.value = '';
5131                     this.fireEvent("select", this, '');
5132                 },
5133                 scope: this
5134             });
5135         }
5136         
5137         
5138         if(Roo.isIE){
5139             this.el.repaint();
5140         }
5141         this.update(this.value);
5142     },
5143
5144     createMonthPicker : function(){
5145         if(!this.monthPicker.dom.firstChild){
5146             var buf = ['<table border="0" cellspacing="0">'];
5147             for(var i = 0; i < 6; i++){
5148                 buf.push(
5149                     '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
5150                     '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
5151                     i == 0 ?
5152                     '<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>' :
5153                     '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
5154                 );
5155             }
5156             buf.push(
5157                 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
5158                     this.okText,
5159                     '</button><button type="button" class="x-date-mp-cancel">',
5160                     this.cancelText,
5161                     '</button></td></tr>',
5162                 '</table>'
5163             );
5164             this.monthPicker.update(buf.join(''));
5165             this.monthPicker.on('click', this.onMonthClick, this);
5166             this.monthPicker.on('dblclick', this.onMonthDblClick, this);
5167
5168             this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
5169             this.mpYears = this.monthPicker.select('td.x-date-mp-year');
5170
5171             this.mpMonths.each(function(m, a, i){
5172                 i += 1;
5173                 if((i%2) == 0){
5174                     m.dom.xmonth = 5 + Math.round(i * .5);
5175                 }else{
5176                     m.dom.xmonth = Math.round((i-1) * .5);
5177                 }
5178             });
5179         }
5180     },
5181
5182     showMonthPicker : function(){
5183         this.createMonthPicker();
5184         var size = this.el.getSize();
5185         this.monthPicker.setSize(size);
5186         this.monthPicker.child('table').setSize(size);
5187
5188         this.mpSelMonth = (this.activeDate || this.value).getMonth();
5189         this.updateMPMonth(this.mpSelMonth);
5190         this.mpSelYear = (this.activeDate || this.value).getFullYear();
5191         this.updateMPYear(this.mpSelYear);
5192
5193         this.monthPicker.slideIn('t', {duration:.2});
5194     },
5195
5196     updateMPYear : function(y){
5197         this.mpyear = y;
5198         var ys = this.mpYears.elements;
5199         for(var i = 1; i <= 10; i++){
5200             var td = ys[i-1], y2;
5201             if((i%2) == 0){
5202                 y2 = y + Math.round(i * .5);
5203                 td.firstChild.innerHTML = y2;
5204                 td.xyear = y2;
5205             }else{
5206                 y2 = y - (5-Math.round(i * .5));
5207                 td.firstChild.innerHTML = y2;
5208                 td.xyear = y2;
5209             }
5210             this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
5211         }
5212     },
5213
5214     updateMPMonth : function(sm){
5215         this.mpMonths.each(function(m, a, i){
5216             m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
5217         });
5218     },
5219
5220     selectMPMonth: function(m){
5221         
5222     },
5223
5224     onMonthClick : function(e, t){
5225         e.stopEvent();
5226         var el = new Roo.Element(t), pn;
5227         if(el.is('button.x-date-mp-cancel')){
5228             this.hideMonthPicker();
5229         }
5230         else if(el.is('button.x-date-mp-ok')){
5231             this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
5232             this.hideMonthPicker();
5233         }
5234         else if(pn = el.up('td.x-date-mp-month', 2)){
5235             this.mpMonths.removeClass('x-date-mp-sel');
5236             pn.addClass('x-date-mp-sel');
5237             this.mpSelMonth = pn.dom.xmonth;
5238         }
5239         else if(pn = el.up('td.x-date-mp-year', 2)){
5240             this.mpYears.removeClass('x-date-mp-sel');
5241             pn.addClass('x-date-mp-sel');
5242             this.mpSelYear = pn.dom.xyear;
5243         }
5244         else if(el.is('a.x-date-mp-prev')){
5245             this.updateMPYear(this.mpyear-10);
5246         }
5247         else if(el.is('a.x-date-mp-next')){
5248             this.updateMPYear(this.mpyear+10);
5249         }
5250     },
5251
5252     onMonthDblClick : function(e, t){
5253         e.stopEvent();
5254         var el = new Roo.Element(t), pn;
5255         if(pn = el.up('td.x-date-mp-month', 2)){
5256             this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
5257             this.hideMonthPicker();
5258         }
5259         else if(pn = el.up('td.x-date-mp-year', 2)){
5260             this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
5261             this.hideMonthPicker();
5262         }
5263     },
5264
5265     hideMonthPicker : function(disableAnim){
5266         if(this.monthPicker){
5267             if(disableAnim === true){
5268                 this.monthPicker.hide();
5269             }else{
5270                 this.monthPicker.slideOut('t', {duration:.2});
5271             }
5272         }
5273     },
5274
5275     // private
5276     showPrevMonth : function(e){
5277         this.update(this.activeDate.add("mo", -1));
5278     },
5279
5280     // private
5281     showNextMonth : function(e){
5282         this.update(this.activeDate.add("mo", 1));
5283     },
5284
5285     // private
5286     showPrevYear : function(){
5287         this.update(this.activeDate.add("y", -1));
5288     },
5289
5290     // private
5291     showNextYear : function(){
5292         this.update(this.activeDate.add("y", 1));
5293     },
5294
5295     // private
5296     handleMouseWheel : function(e){
5297         var delta = e.getWheelDelta();
5298         if(delta > 0){
5299             this.showPrevMonth();
5300             e.stopEvent();
5301         } else if(delta < 0){
5302             this.showNextMonth();
5303             e.stopEvent();
5304         }
5305     },
5306
5307     // private
5308     handleDateClick : function(e, t){
5309         e.stopEvent();
5310         if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
5311             this.setValue(new Date(t.dateValue));
5312             this.fireEvent("select", this, this.value);
5313         }
5314     },
5315
5316     // private
5317     selectToday : function(){
5318         this.setValue(new Date().clearTime());
5319         this.fireEvent("select", this, this.value);
5320     },
5321
5322     // private
5323     update : function(date)
5324     {
5325         var vd = this.activeDate;
5326         this.activeDate = date;
5327         if(vd && this.el){
5328             var t = date.getTime();
5329             if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
5330                 this.cells.removeClass("x-date-selected");
5331                 this.cells.each(function(c){
5332                    if(c.dom.firstChild.dateValue == t){
5333                        c.addClass("x-date-selected");
5334                        setTimeout(function(){
5335                             try{c.dom.firstChild.focus();}catch(e){}
5336                        }, 50);
5337                        return false;
5338                    }
5339                 });
5340                 return;
5341             }
5342         }
5343         
5344         var days = date.getDaysInMonth();
5345         var firstOfMonth = date.getFirstDateOfMonth();
5346         var startingPos = firstOfMonth.getDay()-this.startDay;
5347
5348         if(startingPos <= this.startDay){
5349             startingPos += 7;
5350         }
5351
5352         var pm = date.add("mo", -1);
5353         var prevStart = pm.getDaysInMonth()-startingPos;
5354
5355         var cells = this.cells.elements;
5356         var textEls = this.textNodes;
5357         days += startingPos;
5358
5359         // convert everything to numbers so it's fast
5360         var day = 86400000;
5361         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
5362         var today = new Date().clearTime().getTime();
5363         var sel = date.clearTime().getTime();
5364         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
5365         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
5366         var ddMatch = this.disabledDatesRE;
5367         var ddText = this.disabledDatesText;
5368         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
5369         var ddaysText = this.disabledDaysText;
5370         var format = this.format;
5371
5372         var setCellClass = function(cal, cell){
5373             cell.title = "";
5374             var t = d.getTime();
5375             cell.firstChild.dateValue = t;
5376             if(t == today){
5377                 cell.className += " x-date-today";
5378                 cell.title = cal.todayText;
5379             }
5380             if(t == sel){
5381                 cell.className += " x-date-selected";
5382                 setTimeout(function(){
5383                     try{cell.firstChild.focus();}catch(e){}
5384                 }, 50);
5385             }
5386             // disabling
5387             if(t < min) {
5388                 cell.className = " x-date-disabled";
5389                 cell.title = cal.minText;
5390                 return;
5391             }
5392             if(t > max) {
5393                 cell.className = " x-date-disabled";
5394                 cell.title = cal.maxText;
5395                 return;
5396             }
5397             if(ddays){
5398                 if(ddays.indexOf(d.getDay()) != -1){
5399                     cell.title = ddaysText;
5400                     cell.className = " x-date-disabled";
5401                 }
5402             }
5403             if(ddMatch && format){
5404                 var fvalue = d.dateFormat(format);
5405                 if(ddMatch.test(fvalue)){
5406                     cell.title = ddText.replace("%0", fvalue);
5407                     cell.className = " x-date-disabled";
5408                 }
5409             }
5410         };
5411
5412         var i = 0;
5413         for(; i < startingPos; i++) {
5414             textEls[i].innerHTML = (++prevStart);
5415             d.setDate(d.getDate()+1);
5416             cells[i].className = "x-date-prevday";
5417             setCellClass(this, cells[i]);
5418         }
5419         for(; i < days; i++){
5420             intDay = i - startingPos + 1;
5421             textEls[i].innerHTML = (intDay);
5422             d.setDate(d.getDate()+1);
5423             cells[i].className = "x-date-active";
5424             setCellClass(this, cells[i]);
5425         }
5426         var extraDays = 0;
5427         for(; i < 42; i++) {
5428              textEls[i].innerHTML = (++extraDays);
5429              d.setDate(d.getDate()+1);
5430              cells[i].className = "x-date-nextday";
5431              setCellClass(this, cells[i]);
5432         }
5433
5434         this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
5435         this.fireEvent('monthchange', this, date);
5436         
5437         if(!this.internalRender){
5438             var main = this.el.dom.firstChild;
5439             var w = main.offsetWidth;
5440             this.el.setWidth(w + this.el.getBorderWidth("lr"));
5441             Roo.fly(main).setWidth(w);
5442             this.internalRender = true;
5443             // opera does not respect the auto grow header center column
5444             // then, after it gets a width opera refuses to recalculate
5445             // without a second pass
5446             if(Roo.isOpera && !this.secondPass){
5447                 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
5448                 this.secondPass = true;
5449                 this.update.defer(10, this, [date]);
5450             }
5451         }
5452         
5453         
5454     }
5455 });        /*
5456  * Based on:
5457  * Ext JS Library 1.1.1
5458  * Copyright(c) 2006-2007, Ext JS, LLC.
5459  *
5460  * Originally Released Under LGPL - original licence link has changed is not relivant.
5461  *
5462  * Fork - LGPL
5463  * <script type="text/javascript">
5464  */
5465 /**
5466  * @class Roo.TabPanel
5467  * @extends Roo.util.Observable
5468  * A lightweight tab container.
5469  * <br><br>
5470  * Usage:
5471  * <pre><code>
5472 // basic tabs 1, built from existing content
5473 var tabs = new Roo.TabPanel("tabs1");
5474 tabs.addTab("script", "View Script");
5475 tabs.addTab("markup", "View Markup");
5476 tabs.activate("script");
5477
5478 // more advanced tabs, built from javascript
5479 var jtabs = new Roo.TabPanel("jtabs");
5480 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
5481
5482 // set up the UpdateManager
5483 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
5484 var updater = tab2.getUpdateManager();
5485 updater.setDefaultUrl("ajax1.htm");
5486 tab2.on('activate', updater.refresh, updater, true);
5487
5488 // Use setUrl for Ajax loading
5489 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
5490 tab3.setUrl("ajax2.htm", null, true);
5491
5492 // Disabled tab
5493 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
5494 tab4.disable();
5495
5496 jtabs.activate("jtabs-1");
5497  * </code></pre>
5498  * @constructor
5499  * Create a new TabPanel.
5500  * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
5501  * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
5502  */
5503 Roo.TabPanel = function(container, config){
5504     /**
5505     * The container element for this TabPanel.
5506     * @type Roo.Element
5507     */
5508     this.el = Roo.get(container, true);
5509     if(config){
5510         if(typeof config == "boolean"){
5511             this.tabPosition = config ? "bottom" : "top";
5512         }else{
5513             Roo.apply(this, config);
5514         }
5515     }
5516     if(this.tabPosition == "bottom"){
5517         this.bodyEl = Roo.get(this.createBody(this.el.dom));
5518         this.el.addClass("x-tabs-bottom");
5519     }
5520     this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
5521     this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
5522     this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
5523     if(Roo.isIE){
5524         Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
5525     }
5526     if(this.tabPosition != "bottom"){
5527         /** The body element that contains {@link Roo.TabPanelItem} bodies. +
5528          * @type Roo.Element
5529          */
5530         this.bodyEl = Roo.get(this.createBody(this.el.dom));
5531         this.el.addClass("x-tabs-top");
5532     }
5533     this.items = [];
5534
5535     this.bodyEl.setStyle("position", "relative");
5536
5537     this.active = null;
5538     this.activateDelegate = this.activate.createDelegate(this);
5539
5540     this.addEvents({
5541         /**
5542          * @event tabchange
5543          * Fires when the active tab changes
5544          * @param {Roo.TabPanel} this
5545          * @param {Roo.TabPanelItem} activePanel The new active tab
5546          */
5547         "tabchange": true,
5548         /**
5549          * @event beforetabchange
5550          * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
5551          * @param {Roo.TabPanel} this
5552          * @param {Object} e Set cancel to true on this object to cancel the tab change
5553          * @param {Roo.TabPanelItem} tab The tab being changed to
5554          */
5555         "beforetabchange" : true
5556     });
5557
5558     Roo.EventManager.onWindowResize(this.onResize, this);
5559     this.cpad = this.el.getPadding("lr");
5560     this.hiddenCount = 0;
5561
5562
5563     // toolbar on the tabbar support...
5564     if (this.toolbar) {
5565         var tcfg = this.toolbar;
5566         tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');  
5567         this.toolbar = new Roo.Toolbar(tcfg);
5568         if (Roo.isSafari) {
5569             var tbl = tcfg.container.child('table', true);
5570             tbl.setAttribute('width', '100%');
5571         }
5572         
5573     }
5574    
5575
5576
5577     Roo.TabPanel.superclass.constructor.call(this);
5578 };
5579
5580 Roo.extend(Roo.TabPanel, Roo.util.Observable, {
5581     /*
5582      *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
5583      */
5584     tabPosition : "top",
5585     /*
5586      *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
5587      */
5588     currentTabWidth : 0,
5589     /*
5590      *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
5591      */
5592     minTabWidth : 40,
5593     /*
5594      *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
5595      */
5596     maxTabWidth : 250,
5597     /*
5598      *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
5599      */
5600     preferredTabWidth : 175,
5601     /*
5602      *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
5603      */
5604     resizeTabs : false,
5605     /*
5606      *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
5607      */
5608     monitorResize : true,
5609     /*
5610      *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar. 
5611      */
5612     toolbar : false,
5613
5614     /**
5615      * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
5616      * @param {String} id The id of the div to use <b>or create</b>
5617      * @param {String} text The text for the tab
5618      * @param {String} content (optional) Content to put in the TabPanelItem body
5619      * @param {Boolean} closable (optional) True to create a close icon on the tab
5620      * @return {Roo.TabPanelItem} The created TabPanelItem
5621      */
5622     addTab : function(id, text, content, closable){
5623         var item = new Roo.TabPanelItem(this, id, text, closable);
5624         this.addTabItem(item);
5625         if(content){
5626             item.setContent(content);
5627         }
5628         return item;
5629     },
5630
5631     /**
5632      * Returns the {@link Roo.TabPanelItem} with the specified id/index
5633      * @param {String/Number} id The id or index of the TabPanelItem to fetch.
5634      * @return {Roo.TabPanelItem}
5635      */
5636     getTab : function(id){
5637         return this.items[id];
5638     },
5639
5640     /**
5641      * Hides the {@link Roo.TabPanelItem} with the specified id/index
5642      * @param {String/Number} id The id or index of the TabPanelItem to hide.
5643      */
5644     hideTab : function(id){
5645         var t = this.items[id];
5646         if(!t.isHidden()){
5647            t.setHidden(true);
5648            this.hiddenCount++;
5649            this.autoSizeTabs();
5650         }
5651     },
5652
5653     /**
5654      * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
5655      * @param {String/Number} id The id or index of the TabPanelItem to unhide.
5656      */
5657     unhideTab : function(id){
5658         var t = this.items[id];
5659         if(t.isHidden()){
5660            t.setHidden(false);
5661            this.hiddenCount--;
5662            this.autoSizeTabs();
5663         }
5664     },
5665
5666     /**
5667      * Adds an existing {@link Roo.TabPanelItem}.
5668      * @param {Roo.TabPanelItem} item The TabPanelItem to add
5669      */
5670     addTabItem : function(item){
5671         this.items[item.id] = item;
5672         this.items.push(item);
5673         if(this.resizeTabs){
5674            item.setWidth(this.currentTabWidth || this.preferredTabWidth);
5675            this.autoSizeTabs();
5676         }else{
5677             item.autoSize();
5678         }
5679     },
5680
5681     /**
5682      * Removes a {@link Roo.TabPanelItem}.
5683      * @param {String/Number} id The id or index of the TabPanelItem to remove.
5684      */
5685     removeTab : function(id){
5686         var items = this.items;
5687         var tab = items[id];
5688         if(!tab) { return; }
5689         var index = items.indexOf(tab);
5690         if(this.active == tab && items.length > 1){
5691             var newTab = this.getNextAvailable(index);
5692             if(newTab) {
5693                 newTab.activate();
5694             }
5695         }
5696         this.stripEl.dom.removeChild(tab.pnode.dom);
5697         if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
5698             this.bodyEl.dom.removeChild(tab.bodyEl.dom);
5699         }
5700         items.splice(index, 1);
5701         delete this.items[tab.id];
5702         tab.fireEvent("close", tab);
5703         tab.purgeListeners();
5704         this.autoSizeTabs();
5705     },
5706
5707     getNextAvailable : function(start){
5708         var items = this.items;
5709         var index = start;
5710         // look for a next tab that will slide over to
5711         // replace the one being removed
5712         while(index < items.length){
5713             var item = items[++index];
5714             if(item && !item.isHidden()){
5715                 return item;
5716             }
5717         }
5718         // if one isn't found select the previous tab (on the left)
5719         index = start;
5720         while(index >= 0){
5721             var item = items[--index];
5722             if(item && !item.isHidden()){
5723                 return item;
5724             }
5725         }
5726         return null;
5727     },
5728
5729     /**
5730      * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
5731      * @param {String/Number} id The id or index of the TabPanelItem to disable.
5732      */
5733     disableTab : function(id){
5734         var tab = this.items[id];
5735         if(tab && this.active != tab){
5736             tab.disable();
5737         }
5738     },
5739
5740     /**
5741      * Enables a {@link Roo.TabPanelItem} that is disabled.
5742      * @param {String/Number} id The id or index of the TabPanelItem to enable.
5743      */
5744     enableTab : function(id){
5745         var tab = this.items[id];
5746         tab.enable();
5747     },
5748
5749     /**
5750      * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
5751      * @param {String/Number} id The id or index of the TabPanelItem to activate.
5752      * @return {Roo.TabPanelItem} The TabPanelItem.
5753      */
5754     activate : function(id){
5755         var tab = this.items[id];
5756         if(!tab){
5757             return null;
5758         }
5759         if(tab == this.active || tab.disabled){
5760             return tab;
5761         }
5762         var e = {};
5763         this.fireEvent("beforetabchange", this, e, tab);
5764         if(e.cancel !== true && !tab.disabled){
5765             if(this.active){
5766                 this.active.hide();
5767             }
5768             this.active = this.items[id];
5769             this.active.show();
5770             this.fireEvent("tabchange", this, this.active);
5771         }
5772         return tab;
5773     },
5774
5775     /**
5776      * Gets the active {@link Roo.TabPanelItem}.
5777      * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
5778      */
5779     getActiveTab : function(){
5780         return this.active;
5781     },
5782
5783     /**
5784      * Updates the tab body element to fit the height of the container element
5785      * for overflow scrolling
5786      * @param {Number} targetHeight (optional) Override the starting height from the elements height
5787      */
5788     syncHeight : function(targetHeight){
5789         var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
5790         var bm = this.bodyEl.getMargins();
5791         var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
5792         this.bodyEl.setHeight(newHeight);
5793         return newHeight;
5794     },
5795
5796     onResize : function(){
5797         if(this.monitorResize){
5798             this.autoSizeTabs();
5799         }
5800     },
5801
5802     /**
5803      * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
5804      */
5805     beginUpdate : function(){
5806         this.updating = true;
5807     },
5808
5809     /**
5810      * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
5811      */
5812     endUpdate : function(){
5813         this.updating = false;
5814         this.autoSizeTabs();
5815     },
5816
5817     /**
5818      * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
5819      */
5820     autoSizeTabs : function(){
5821         var count = this.items.length;
5822         var vcount = count - this.hiddenCount;
5823         if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
5824             return;
5825         }
5826         var w = Math.max(this.el.getWidth() - this.cpad, 10);
5827         var availWidth = Math.floor(w / vcount);
5828         var b = this.stripBody;
5829         if(b.getWidth() > w){
5830             var tabs = this.items;
5831             this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
5832             if(availWidth < this.minTabWidth){
5833                 /*if(!this.sleft){    // incomplete scrolling code
5834                     this.createScrollButtons();
5835                 }
5836                 this.showScroll();
5837                 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
5838             }
5839         }else{
5840             if(this.currentTabWidth < this.preferredTabWidth){
5841                 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
5842             }
5843         }
5844     },
5845
5846     /**
5847      * Returns the number of tabs in this TabPanel.
5848      * @return {Number}
5849      */
5850      getCount : function(){
5851          return this.items.length;
5852      },
5853
5854     /**
5855      * Resizes all the tabs to the passed width
5856      * @param {Number} The new width
5857      */
5858     setTabWidth : function(width){
5859         this.currentTabWidth = width;
5860         for(var i = 0, len = this.items.length; i < len; i++) {
5861                 if(!this.items[i].isHidden()) {
5862                 this.items[i].setWidth(width);
5863             }
5864         }
5865     },
5866
5867     /**
5868      * Destroys this TabPanel
5869      * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
5870      */
5871     destroy : function(removeEl){
5872         Roo.EventManager.removeResizeListener(this.onResize, this);
5873         for(var i = 0, len = this.items.length; i < len; i++){
5874             this.items[i].purgeListeners();
5875         }
5876         if(removeEl === true){
5877             this.el.update("");
5878             this.el.remove();
5879         }
5880     }
5881 });
5882
5883 /**
5884  * @class Roo.TabPanelItem
5885  * @extends Roo.util.Observable
5886  * Represents an individual item (tab plus body) in a TabPanel.
5887  * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
5888  * @param {String} id The id of this TabPanelItem
5889  * @param {String} text The text for the tab of this TabPanelItem
5890  * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
5891  */
5892 Roo.TabPanelItem = function(tabPanel, id, text, closable){
5893     /**
5894      * The {@link Roo.TabPanel} this TabPanelItem belongs to
5895      * @type Roo.TabPanel
5896      */
5897     this.tabPanel = tabPanel;
5898     /**
5899      * The id for this TabPanelItem
5900      * @type String
5901      */
5902     this.id = id;
5903     /** @private */
5904     this.disabled = false;
5905     /** @private */
5906     this.text = text;
5907     /** @private */
5908     this.loaded = false;
5909     this.closable = closable;
5910
5911     /**
5912      * The body element for this TabPanelItem.
5913      * @type Roo.Element
5914      */
5915     this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
5916     this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
5917     this.bodyEl.setStyle("display", "block");
5918     this.bodyEl.setStyle("zoom", "1");
5919     this.hideAction();
5920
5921     var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
5922     /** @private */
5923     this.el = Roo.get(els.el, true);
5924     this.inner = Roo.get(els.inner, true);
5925     this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
5926     this.pnode = Roo.get(els.el.parentNode, true);
5927     this.el.on("mousedown", this.onTabMouseDown, this);
5928     this.el.on("click", this.onTabClick, this);
5929     /** @private */
5930     if(closable){
5931         var c = Roo.get(els.close, true);
5932         c.dom.title = this.closeText;
5933         c.addClassOnOver("close-over");
5934         c.on("click", this.closeClick, this);
5935      }
5936
5937     this.addEvents({
5938          /**
5939          * @event activate
5940          * Fires when this tab becomes the active tab.
5941          * @param {Roo.TabPanel} tabPanel The parent TabPanel
5942          * @param {Roo.TabPanelItem} this
5943          */
5944         "activate": true,
5945         /**
5946          * @event beforeclose
5947          * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
5948          * @param {Roo.TabPanelItem} this
5949          * @param {Object} e Set cancel to true on this object to cancel the close.
5950          */
5951         "beforeclose": true,
5952         /**
5953          * @event close
5954          * Fires when this tab is closed.
5955          * @param {Roo.TabPanelItem} this
5956          */
5957          "close": true,
5958         /**
5959          * @event deactivate
5960          * Fires when this tab is no longer the active tab.
5961          * @param {Roo.TabPanel} tabPanel The parent TabPanel
5962          * @param {Roo.TabPanelItem} this
5963          */
5964          "deactivate" : true
5965     });
5966     this.hidden = false;
5967
5968     Roo.TabPanelItem.superclass.constructor.call(this);
5969 };
5970
5971 Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
5972     purgeListeners : function(){
5973        Roo.util.Observable.prototype.purgeListeners.call(this);
5974        this.el.removeAllListeners();
5975     },
5976     /**
5977      * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
5978      */
5979     show : function(){
5980         this.pnode.addClass("on");
5981         this.showAction();
5982         if(Roo.isOpera){
5983             this.tabPanel.stripWrap.repaint();
5984         }
5985         this.fireEvent("activate", this.tabPanel, this);
5986     },
5987
5988     /**
5989      * Returns true if this tab is the active tab.
5990      * @return {Boolean}
5991      */
5992     isActive : function(){
5993         return this.tabPanel.getActiveTab() == this;
5994     },
5995
5996     /**
5997      * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
5998      */
5999     hide : function(){
6000         this.pnode.removeClass("on");
6001         this.hideAction();
6002         this.fireEvent("deactivate", this.tabPanel, this);
6003     },
6004
6005     hideAction : function(){
6006         this.bodyEl.hide();
6007         this.bodyEl.setStyle("position", "absolute");
6008         this.bodyEl.setLeft("-20000px");
6009         this.bodyEl.setTop("-20000px");
6010     },
6011
6012     showAction : function(){
6013         this.bodyEl.setStyle("position", "relative");
6014         this.bodyEl.setTop("");
6015         this.bodyEl.setLeft("");
6016         this.bodyEl.show();
6017     },
6018
6019     /**
6020      * Set the tooltip for the tab.
6021      * @param {String} tooltip The tab's tooltip
6022      */
6023     setTooltip : function(text){
6024         if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
6025             this.textEl.dom.qtip = text;
6026             this.textEl.dom.removeAttribute('title');
6027         }else{
6028             this.textEl.dom.title = text;
6029         }
6030     },
6031
6032     onTabClick : function(e){
6033         e.preventDefault();
6034         this.tabPanel.activate(this.id);
6035     },
6036
6037     onTabMouseDown : function(e){
6038         e.preventDefault();
6039         this.tabPanel.activate(this.id);
6040     },
6041
6042     getWidth : function(){
6043         return this.inner.getWidth();
6044     },
6045
6046     setWidth : function(width){
6047         var iwidth = width - this.pnode.getPadding("lr");
6048         this.inner.setWidth(iwidth);
6049         this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
6050         this.pnode.setWidth(width);
6051     },
6052
6053     /**
6054      * Show or hide the tab
6055      * @param {Boolean} hidden True to hide or false to show.
6056      */
6057     setHidden : function(hidden){
6058         this.hidden = hidden;
6059         this.pnode.setStyle("display", hidden ? "none" : "");
6060     },
6061
6062     /**
6063      * Returns true if this tab is "hidden"
6064      * @return {Boolean}
6065      */
6066     isHidden : function(){
6067         return this.hidden;
6068     },
6069
6070     /**
6071      * Returns the text for this tab
6072      * @return {String}
6073      */
6074     getText : function(){
6075         return this.text;
6076     },
6077
6078     autoSize : function(){
6079         //this.el.beginMeasure();
6080         this.textEl.setWidth(1);
6081         /*
6082          *  #2804 [new] Tabs in Roojs
6083          *  increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
6084          */
6085         this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
6086         //this.el.endMeasure();
6087     },
6088
6089     /**
6090      * Sets the text for the tab (Note: this also sets the tooltip text)
6091      * @param {String} text The tab's text and tooltip
6092      */
6093     setText : function(text){
6094         this.text = text;
6095         this.textEl.update(text);
6096         this.setTooltip(text);
6097         if(!this.tabPanel.resizeTabs){
6098             this.autoSize();
6099         }
6100     },
6101     /**
6102      * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
6103      */
6104     activate : function(){
6105         this.tabPanel.activate(this.id);
6106     },
6107
6108     /**
6109      * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
6110      */
6111     disable : function(){
6112         if(this.tabPanel.active != this){
6113             this.disabled = true;
6114             this.pnode.addClass("disabled");
6115         }
6116     },
6117
6118     /**
6119      * Enables this TabPanelItem if it was previously disabled.
6120      */
6121     enable : function(){
6122         this.disabled = false;
6123         this.pnode.removeClass("disabled");
6124     },
6125
6126     /**
6127      * Sets the content for this TabPanelItem.
6128      * @param {String} content The content
6129      * @param {Boolean} loadScripts true to look for and load scripts
6130      */
6131     setContent : function(content, loadScripts){
6132         this.bodyEl.update(content, loadScripts);
6133     },
6134
6135     /**
6136      * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
6137      * @return {Roo.UpdateManager} The UpdateManager
6138      */
6139     getUpdateManager : function(){
6140         return this.bodyEl.getUpdateManager();
6141     },
6142
6143     /**
6144      * Set a URL to be used to load the content for this TabPanelItem.
6145      * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
6146      * @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)
6147      * @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)
6148      * @return {Roo.UpdateManager} The UpdateManager
6149      */
6150     setUrl : function(url, params, loadOnce){
6151         if(this.refreshDelegate){
6152             this.un('activate', this.refreshDelegate);
6153         }
6154         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
6155         this.on("activate", this.refreshDelegate);
6156         return this.bodyEl.getUpdateManager();
6157     },
6158
6159     /** @private */
6160     _handleRefresh : function(url, params, loadOnce){
6161         if(!loadOnce || !this.loaded){
6162             var updater = this.bodyEl.getUpdateManager();
6163             updater.update(url, params, this._setLoaded.createDelegate(this));
6164         }
6165     },
6166
6167     /**
6168      *   Forces a content refresh from the URL specified in the {@link #setUrl} method.
6169      *   Will fail silently if the setUrl method has not been called.
6170      *   This does not activate the panel, just updates its content.
6171      */
6172     refresh : function(){
6173         if(this.refreshDelegate){
6174            this.loaded = false;
6175            this.refreshDelegate();
6176         }
6177     },
6178
6179     /** @private */
6180     _setLoaded : function(){
6181         this.loaded = true;
6182     },
6183
6184     /** @private */
6185     closeClick : function(e){
6186         var o = {};
6187         e.stopEvent();
6188         this.fireEvent("beforeclose", this, o);
6189         if(o.cancel !== true){
6190             this.tabPanel.removeTab(this.id);
6191         }
6192     },
6193     /**
6194      * The text displayed in the tooltip for the close icon.
6195      * @type String
6196      */
6197     closeText : "Close this tab"
6198 });
6199
6200 /** @private */
6201 Roo.TabPanel.prototype.createStrip = function(container){
6202     var strip = document.createElement("div");
6203     strip.className = "x-tabs-wrap";
6204     container.appendChild(strip);
6205     return strip;
6206 };
6207 /** @private */
6208 Roo.TabPanel.prototype.createStripList = function(strip){
6209     // div wrapper for retard IE
6210     // returns the "tr" element.
6211     strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
6212         '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
6213         '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
6214     return strip.firstChild.firstChild.firstChild.firstChild;
6215 };
6216 /** @private */
6217 Roo.TabPanel.prototype.createBody = function(container){
6218     var body = document.createElement("div");
6219     Roo.id(body, "tab-body");
6220     Roo.fly(body).addClass("x-tabs-body");
6221     container.appendChild(body);
6222     return body;
6223 };
6224 /** @private */
6225 Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
6226     var body = Roo.getDom(id);
6227     if(!body){
6228         body = document.createElement("div");
6229         body.id = id;
6230     }
6231     Roo.fly(body).addClass("x-tabs-item-body");
6232     bodyEl.insertBefore(body, bodyEl.firstChild);
6233     return body;
6234 };
6235 /** @private */
6236 Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
6237     var td = document.createElement("td");
6238     stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
6239     //stripEl.appendChild(td);
6240     if(closable){
6241         td.className = "x-tabs-closable";
6242         if(!this.closeTpl){
6243             this.closeTpl = new Roo.Template(
6244                '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
6245                '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
6246                '<div unselectable="on" class="close-icon">&#160;</div></em></span></a>'
6247             );
6248         }
6249         var el = this.closeTpl.overwrite(td, {"text": text});
6250         var close = el.getElementsByTagName("div")[0];
6251         var inner = el.getElementsByTagName("em")[0];
6252         return {"el": el, "close": close, "inner": inner};
6253     } else {
6254         if(!this.tabTpl){
6255             this.tabTpl = new Roo.Template(
6256                '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
6257                '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
6258             );
6259         }
6260         var el = this.tabTpl.overwrite(td, {"text": text});
6261         var inner = el.getElementsByTagName("em")[0];
6262         return {"el": el, "inner": inner};
6263     }
6264 };/*
6265  * Based on:
6266  * Ext JS Library 1.1.1
6267  * Copyright(c) 2006-2007, Ext JS, LLC.
6268  *
6269  * Originally Released Under LGPL - original licence link has changed is not relivant.
6270  *
6271  * Fork - LGPL
6272  * <script type="text/javascript">
6273  */
6274
6275 /**
6276  * @class Roo.Button
6277  * @extends Roo.util.Observable
6278  * Simple Button class
6279  * @cfg {String} text The button text
6280  * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
6281  * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
6282  * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
6283  * @cfg {Object} scope The scope of the handler
6284  * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
6285  * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
6286  * @cfg {Boolean} hidden True to start hidden (defaults to false)
6287  * @cfg {Boolean} disabled True to start disabled (defaults to false)
6288  * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
6289  * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
6290    applies if enableToggle = true)
6291  * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
6292  * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
6293   an {@link Roo.util.ClickRepeater} config object (defaults to false).
6294  * @constructor
6295  * Create a new button
6296  * @param {Object} config The config object
6297  */
6298 Roo.Button = function(renderTo, config)
6299 {
6300     if (!config) {
6301         config = renderTo;
6302         renderTo = config.renderTo || false;
6303     }
6304     
6305     Roo.apply(this, config);
6306     this.addEvents({
6307         /**
6308              * @event click
6309              * Fires when this button is clicked
6310              * @param {Button} this
6311              * @param {EventObject} e The click event
6312              */
6313             "click" : true,
6314         /**
6315              * @event toggle
6316              * Fires when the "pressed" state of this button changes (only if enableToggle = true)
6317              * @param {Button} this
6318              * @param {Boolean} pressed
6319              */
6320             "toggle" : true,
6321         /**
6322              * @event mouseover
6323              * Fires when the mouse hovers over the button
6324              * @param {Button} this
6325              * @param {Event} e The event object
6326              */
6327         'mouseover' : true,
6328         /**
6329              * @event mouseout
6330              * Fires when the mouse exits the button
6331              * @param {Button} this
6332              * @param {Event} e The event object
6333              */
6334         'mouseout': true,
6335          /**
6336              * @event render
6337              * Fires when the button is rendered
6338              * @param {Button} this
6339              */
6340         'render': true
6341     });
6342     if(this.menu){
6343         this.menu = Roo.menu.MenuMgr.get(this.menu);
6344     }
6345     // register listeners first!!  - so render can be captured..
6346     Roo.util.Observable.call(this);
6347     if(renderTo){
6348         this.render(renderTo);
6349     }
6350     
6351   
6352 };
6353
6354 Roo.extend(Roo.Button, Roo.util.Observable, {
6355     /**
6356      * 
6357      */
6358     
6359     /**
6360      * Read-only. True if this button is hidden
6361      * @type Boolean
6362      */
6363     hidden : false,
6364     /**
6365      * Read-only. True if this button is disabled
6366      * @type Boolean
6367      */
6368     disabled : false,
6369     /**
6370      * Read-only. True if this button is pressed (only if enableToggle = true)
6371      * @type Boolean
6372      */
6373     pressed : false,
6374
6375     /**
6376      * @cfg {Number} tabIndex 
6377      * The DOM tabIndex for this button (defaults to undefined)
6378      */
6379     tabIndex : undefined,
6380
6381     /**
6382      * @cfg {Boolean} enableToggle
6383      * True to enable pressed/not pressed toggling (defaults to false)
6384      */
6385     enableToggle: false,
6386     /**
6387      * @cfg {Roo.menu.Menu} menu
6388      * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
6389      */
6390     menu : undefined,
6391     /**
6392      * @cfg {String} menuAlign
6393      * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
6394      */
6395     menuAlign : "tl-bl?",
6396
6397     /**
6398      * @cfg {String} iconCls
6399      * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
6400      */
6401     iconCls : undefined,
6402     /**
6403      * @cfg {String} type
6404      * The button's type, corresponding to the DOM input element type attribute.  Either "submit," "reset" or "button" (default).
6405      */
6406     type : 'button',
6407
6408     // private
6409     menuClassTarget: 'tr',
6410
6411     /**
6412      * @cfg {String} clickEvent
6413      * The type of event to map to the button's event handler (defaults to 'click')
6414      */
6415     clickEvent : 'click',
6416
6417     /**
6418      * @cfg {Boolean} handleMouseEvents
6419      * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
6420      */
6421     handleMouseEvents : true,
6422
6423     /**
6424      * @cfg {String} tooltipType
6425      * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
6426      */
6427     tooltipType : 'qtip',
6428
6429     /**
6430      * @cfg {String} cls
6431      * A CSS class to apply to the button's main element.
6432      */
6433     
6434     /**
6435      * @cfg {Roo.Template} template (Optional)
6436      * An {@link Roo.Template} with which to create the Button's main element. This Template must
6437      * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
6438      * require code modifications if required elements (e.g. a button) aren't present.
6439      */
6440
6441     // private
6442     render : function(renderTo){
6443         var btn;
6444         if(this.hideParent){
6445             this.parentEl = Roo.get(renderTo);
6446         }
6447         if(!this.dhconfig){
6448             if(!this.template){
6449                 if(!Roo.Button.buttonTemplate){
6450                     // hideous table template
6451                     Roo.Button.buttonTemplate = new Roo.Template(
6452                         '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
6453                         '<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>',
6454                         "</tr></tbody></table>");
6455                 }
6456                 this.template = Roo.Button.buttonTemplate;
6457             }
6458             btn = this.template.append(renderTo, [this.text || '&#160;', this.type], true);
6459             var btnEl = btn.child("button:first");
6460             btnEl.on('focus', this.onFocus, this);
6461             btnEl.on('blur', this.onBlur, this);
6462             if(this.cls){
6463                 btn.addClass(this.cls);
6464             }
6465             if(this.icon){
6466                 btnEl.setStyle('background-image', 'url(' +this.icon +')');
6467             }
6468             if(this.iconCls){
6469                 btnEl.addClass(this.iconCls);
6470                 if(!this.cls){
6471                     btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
6472                 }
6473             }
6474             if(this.tabIndex !== undefined){
6475                 btnEl.dom.tabIndex = this.tabIndex;
6476             }
6477             if(this.tooltip){
6478                 if(typeof this.tooltip == 'object'){
6479                     Roo.QuickTips.tips(Roo.apply({
6480                           target: btnEl.id
6481                     }, this.tooltip));
6482                 } else {
6483                     btnEl.dom[this.tooltipType] = this.tooltip;
6484                 }
6485             }
6486         }else{
6487             btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
6488         }
6489         this.el = btn;
6490         if(this.id){
6491             this.el.dom.id = this.el.id = this.id;
6492         }
6493         if(this.menu){
6494             this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
6495             this.menu.on("show", this.onMenuShow, this);
6496             this.menu.on("hide", this.onMenuHide, this);
6497         }
6498         btn.addClass("x-btn");
6499         if(Roo.isIE && !Roo.isIE7){
6500             this.autoWidth.defer(1, this);
6501         }else{
6502             this.autoWidth();
6503         }
6504         if(this.handleMouseEvents){
6505             btn.on("mouseover", this.onMouseOver, this);
6506             btn.on("mouseout", this.onMouseOut, this);
6507             btn.on("mousedown", this.onMouseDown, this);
6508         }
6509         btn.on(this.clickEvent, this.onClick, this);
6510         //btn.on("mouseup", this.onMouseUp, this);
6511         if(this.hidden){
6512             this.hide();
6513         }
6514         if(this.disabled){
6515             this.disable();
6516         }
6517         Roo.ButtonToggleMgr.register(this);
6518         if(this.pressed){
6519             this.el.addClass("x-btn-pressed");
6520         }
6521         if(this.repeat){
6522             var repeater = new Roo.util.ClickRepeater(btn,
6523                 typeof this.repeat == "object" ? this.repeat : {}
6524             );
6525             repeater.on("click", this.onClick,  this);
6526         }
6527         
6528         this.fireEvent('render', this);
6529         
6530     },
6531     /**
6532      * Returns the button's underlying element
6533      * @return {Roo.Element} The element
6534      */
6535     getEl : function(){
6536         return this.el;  
6537     },
6538     
6539     /**
6540      * Destroys this Button and removes any listeners.
6541      */
6542     destroy : function(){
6543         Roo.ButtonToggleMgr.unregister(this);
6544         this.el.removeAllListeners();
6545         this.purgeListeners();
6546         this.el.remove();
6547     },
6548
6549     // private
6550     autoWidth : function(){
6551         if(this.el){
6552             this.el.setWidth("auto");
6553             if(Roo.isIE7 && Roo.isStrict){
6554                 var ib = this.el.child('button');
6555                 if(ib && ib.getWidth() > 20){
6556                     ib.clip();
6557                     ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
6558                 }
6559             }
6560             if(this.minWidth){
6561                 if(this.hidden){
6562                     this.el.beginMeasure();
6563                 }
6564                 if(this.el.getWidth() < this.minWidth){
6565                     this.el.setWidth(this.minWidth);
6566                 }
6567                 if(this.hidden){
6568                     this.el.endMeasure();
6569                 }
6570             }
6571         }
6572     },
6573
6574     /**
6575      * Assigns this button's click handler
6576      * @param {Function} handler The function to call when the button is clicked
6577      * @param {Object} scope (optional) Scope for the function passed in
6578      */
6579     setHandler : function(handler, scope){
6580         this.handler = handler;
6581         this.scope = scope;  
6582     },
6583     
6584     /**
6585      * Sets this button's text
6586      * @param {String} text The button text
6587      */
6588     setText : function(text){
6589         this.text = text;
6590         if(this.el){
6591             this.el.child("td.x-btn-center button.x-btn-text").update(text);
6592         }
6593         this.autoWidth();
6594     },
6595     
6596     /**
6597      * Gets the text for this button
6598      * @return {String} The button text
6599      */
6600     getText : function(){
6601         return this.text;  
6602     },
6603     
6604     /**
6605      * Show this button
6606      */
6607     show: function(){
6608         this.hidden = false;
6609         if(this.el){
6610             this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
6611         }
6612     },
6613     
6614     /**
6615      * Hide this button
6616      */
6617     hide: function(){
6618         this.hidden = true;
6619         if(this.el){
6620             this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
6621         }
6622     },
6623     
6624     /**
6625      * Convenience function for boolean show/hide
6626      * @param {Boolean} visible True to show, false to hide
6627      */
6628     setVisible: function(visible){
6629         if(visible) {
6630             this.show();
6631         }else{
6632             this.hide();
6633         }
6634     },
6635     
6636     /**
6637      * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
6638      * @param {Boolean} state (optional) Force a particular state
6639      */
6640     toggle : function(state){
6641         state = state === undefined ? !this.pressed : state;
6642         if(state != this.pressed){
6643             if(state){
6644                 this.el.addClass("x-btn-pressed");
6645                 this.pressed = true;
6646                 this.fireEvent("toggle", this, true);
6647             }else{
6648                 this.el.removeClass("x-btn-pressed");
6649                 this.pressed = false;
6650                 this.fireEvent("toggle", this, false);
6651             }
6652             if(this.toggleHandler){
6653                 this.toggleHandler.call(this.scope || this, this, state);
6654             }
6655         }
6656     },
6657     
6658     /**
6659      * Focus the button
6660      */
6661     focus : function(){
6662         this.el.child('button:first').focus();
6663     },
6664     
6665     /**
6666      * Disable this button
6667      */
6668     disable : function(){
6669         if(this.el){
6670             this.el.addClass("x-btn-disabled");
6671         }
6672         this.disabled = true;
6673     },
6674     
6675     /**
6676      * Enable this button
6677      */
6678     enable : function(){
6679         if(this.el){
6680             this.el.removeClass("x-btn-disabled");
6681         }
6682         this.disabled = false;
6683     },
6684
6685     /**
6686      * Convenience function for boolean enable/disable
6687      * @param {Boolean} enabled True to enable, false to disable
6688      */
6689     setDisabled : function(v){
6690         this[v !== true ? "enable" : "disable"]();
6691     },
6692
6693     // private
6694     onClick : function(e)
6695     {
6696         if(e){
6697             e.preventDefault();
6698         }
6699         if(e.button != 0){
6700             return;
6701         }
6702         if(!this.disabled){
6703             if(this.enableToggle){
6704                 this.toggle();
6705             }
6706             if(this.menu && !this.menu.isVisible()){
6707                 this.menu.show(this.el, this.menuAlign);
6708             }
6709             this.fireEvent("click", this, e);
6710             if(this.handler){
6711                 this.el.removeClass("x-btn-over");
6712                 this.handler.call(this.scope || this, this, e);
6713             }
6714         }
6715     },
6716     // private
6717     onMouseOver : function(e){
6718         if(!this.disabled){
6719             this.el.addClass("x-btn-over");
6720             this.fireEvent('mouseover', this, e);
6721         }
6722     },
6723     // private
6724     onMouseOut : function(e){
6725         if(!e.within(this.el,  true)){
6726             this.el.removeClass("x-btn-over");
6727             this.fireEvent('mouseout', this, e);
6728         }
6729     },
6730     // private
6731     onFocus : function(e){
6732         if(!this.disabled){
6733             this.el.addClass("x-btn-focus");
6734         }
6735     },
6736     // private
6737     onBlur : function(e){
6738         this.el.removeClass("x-btn-focus");
6739     },
6740     // private
6741     onMouseDown : function(e){
6742         if(!this.disabled && e.button == 0){
6743             this.el.addClass("x-btn-click");
6744             Roo.get(document).on('mouseup', this.onMouseUp, this);
6745         }
6746     },
6747     // private
6748     onMouseUp : function(e){
6749         if(e.button == 0){
6750             this.el.removeClass("x-btn-click");
6751             Roo.get(document).un('mouseup', this.onMouseUp, this);
6752         }
6753     },
6754     // private
6755     onMenuShow : function(e){
6756         this.el.addClass("x-btn-menu-active");
6757     },
6758     // private
6759     onMenuHide : function(e){
6760         this.el.removeClass("x-btn-menu-active");
6761     }   
6762 });
6763
6764 // Private utility class used by Button
6765 Roo.ButtonToggleMgr = function(){
6766    var groups = {};
6767    
6768    function toggleGroup(btn, state){
6769        if(state){
6770            var g = groups[btn.toggleGroup];
6771            for(var i = 0, l = g.length; i < l; i++){
6772                if(g[i] != btn){
6773                    g[i].toggle(false);
6774                }
6775            }
6776        }
6777    }
6778    
6779    return {
6780        register : function(btn){
6781            if(!btn.toggleGroup){
6782                return;
6783            }
6784            var g = groups[btn.toggleGroup];
6785            if(!g){
6786                g = groups[btn.toggleGroup] = [];
6787            }
6788            g.push(btn);
6789            btn.on("toggle", toggleGroup);
6790        },
6791        
6792        unregister : function(btn){
6793            if(!btn.toggleGroup){
6794                return;
6795            }
6796            var g = groups[btn.toggleGroup];
6797            if(g){
6798                g.remove(btn);
6799                btn.un("toggle", toggleGroup);
6800            }
6801        }
6802    };
6803 }();/*
6804  * Based on:
6805  * Ext JS Library 1.1.1
6806  * Copyright(c) 2006-2007, Ext JS, LLC.
6807  *
6808  * Originally Released Under LGPL - original licence link has changed is not relivant.
6809  *
6810  * Fork - LGPL
6811  * <script type="text/javascript">
6812  */
6813  
6814 /**
6815  * @class Roo.SplitButton
6816  * @extends Roo.Button
6817  * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
6818  * click event of the button.  Typically this would be used to display a dropdown menu that provides additional
6819  * options to the primary button action, but any custom handler can provide the arrowclick implementation.
6820  * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
6821  * @cfg {String} arrowTooltip The title attribute of the arrow
6822  * @constructor
6823  * Create a new menu button
6824  * @param {String/HTMLElement/Element} renderTo The element to append the button to
6825  * @param {Object} config The config object
6826  */
6827 Roo.SplitButton = function(renderTo, config){
6828     Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
6829     /**
6830      * @event arrowclick
6831      * Fires when this button's arrow is clicked
6832      * @param {SplitButton} this
6833      * @param {EventObject} e The click event
6834      */
6835     this.addEvents({"arrowclick":true});
6836 };
6837
6838 Roo.extend(Roo.SplitButton, Roo.Button, {
6839     render : function(renderTo){
6840         // this is one sweet looking template!
6841         var tpl = new Roo.Template(
6842             '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
6843             '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
6844             '<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>',
6845             "</tbody></table></td><td>",
6846             '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
6847             '<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>',
6848             "</tbody></table></td></tr></table>"
6849         );
6850         var btn = tpl.append(renderTo, [this.text, this.type], true);
6851         var btnEl = btn.child("button");
6852         if(this.cls){
6853             btn.addClass(this.cls);
6854         }
6855         if(this.icon){
6856             btnEl.setStyle('background-image', 'url(' +this.icon +')');
6857         }
6858         if(this.iconCls){
6859             btnEl.addClass(this.iconCls);
6860             if(!this.cls){
6861                 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
6862             }
6863         }
6864         this.el = btn;
6865         if(this.handleMouseEvents){
6866             btn.on("mouseover", this.onMouseOver, this);
6867             btn.on("mouseout", this.onMouseOut, this);
6868             btn.on("mousedown", this.onMouseDown, this);
6869             btn.on("mouseup", this.onMouseUp, this);
6870         }
6871         btn.on(this.clickEvent, this.onClick, this);
6872         if(this.tooltip){
6873             if(typeof this.tooltip == 'object'){
6874                 Roo.QuickTips.tips(Roo.apply({
6875                       target: btnEl.id
6876                 }, this.tooltip));
6877             } else {
6878                 btnEl.dom[this.tooltipType] = this.tooltip;
6879             }
6880         }
6881         if(this.arrowTooltip){
6882             btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
6883         }
6884         if(this.hidden){
6885             this.hide();
6886         }
6887         if(this.disabled){
6888             this.disable();
6889         }
6890         if(this.pressed){
6891             this.el.addClass("x-btn-pressed");
6892         }
6893         if(Roo.isIE && !Roo.isIE7){
6894             this.autoWidth.defer(1, this);
6895         }else{
6896             this.autoWidth();
6897         }
6898         if(this.menu){
6899             this.menu.on("show", this.onMenuShow, this);
6900             this.menu.on("hide", this.onMenuHide, this);
6901         }
6902         this.fireEvent('render', this);
6903     },
6904
6905     // private
6906     autoWidth : function(){
6907         if(this.el){
6908             var tbl = this.el.child("table:first");
6909             var tbl2 = this.el.child("table:last");
6910             this.el.setWidth("auto");
6911             tbl.setWidth("auto");
6912             if(Roo.isIE7 && Roo.isStrict){
6913                 var ib = this.el.child('button:first');
6914                 if(ib && ib.getWidth() > 20){
6915                     ib.clip();
6916                     ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
6917                 }
6918             }
6919             if(this.minWidth){
6920                 if(this.hidden){
6921                     this.el.beginMeasure();
6922                 }
6923                 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
6924                     tbl.setWidth(this.minWidth-tbl2.getWidth());
6925                 }
6926                 if(this.hidden){
6927                     this.el.endMeasure();
6928                 }
6929             }
6930             this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
6931         } 
6932     },
6933     /**
6934      * Sets this button's click handler
6935      * @param {Function} handler The function to call when the button is clicked
6936      * @param {Object} scope (optional) Scope for the function passed above
6937      */
6938     setHandler : function(handler, scope){
6939         this.handler = handler;
6940         this.scope = scope;  
6941     },
6942     
6943     /**
6944      * Sets this button's arrow click handler
6945      * @param {Function} handler The function to call when the arrow is clicked
6946      * @param {Object} scope (optional) Scope for the function passed above
6947      */
6948     setArrowHandler : function(handler, scope){
6949         this.arrowHandler = handler;
6950         this.scope = scope;  
6951     },
6952     
6953     /**
6954      * Focus the button
6955      */
6956     focus : function(){
6957         if(this.el){
6958             this.el.child("button:first").focus();
6959         }
6960     },
6961
6962     // private
6963     onClick : function(e){
6964         e.preventDefault();
6965         if(!this.disabled){
6966             if(e.getTarget(".x-btn-menu-arrow-wrap")){
6967                 if(this.menu && !this.menu.isVisible()){
6968                     this.menu.show(this.el, this.menuAlign);
6969                 }
6970                 this.fireEvent("arrowclick", this, e);
6971                 if(this.arrowHandler){
6972                     this.arrowHandler.call(this.scope || this, this, e);
6973                 }
6974             }else{
6975                 this.fireEvent("click", this, e);
6976                 if(this.handler){
6977                     this.handler.call(this.scope || this, this, e);
6978                 }
6979             }
6980         }
6981     },
6982     // private
6983     onMouseDown : function(e){
6984         if(!this.disabled){
6985             Roo.fly(e.getTarget("table")).addClass("x-btn-click");
6986         }
6987     },
6988     // private
6989     onMouseUp : function(e){
6990         Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
6991     }   
6992 });
6993
6994
6995 // backwards compat
6996 Roo.MenuButton = Roo.SplitButton;/*
6997  * Based on:
6998  * Ext JS Library 1.1.1
6999  * Copyright(c) 2006-2007, Ext JS, LLC.
7000  *
7001  * Originally Released Under LGPL - original licence link has changed is not relivant.
7002  *
7003  * Fork - LGPL
7004  * <script type="text/javascript">
7005  */
7006
7007 /**
7008  * @class Roo.Toolbar
7009  * @children   Roo.Toolbar.Item Roo.form.Field
7010  * Basic Toolbar class.
7011  * @constructor
7012  * Creates a new Toolbar
7013  * @param {Object} container The config object
7014  */ 
7015 Roo.Toolbar = function(container, buttons, config)
7016 {
7017     /// old consturctor format still supported..
7018     if(container instanceof Array){ // omit the container for later rendering
7019         buttons = container;
7020         config = buttons;
7021         container = null;
7022     }
7023     if (typeof(container) == 'object' && container.xtype) {
7024         config = container;
7025         container = config.container;
7026         buttons = config.buttons || []; // not really - use items!!
7027     }
7028     var xitems = [];
7029     if (config && config.items) {
7030         xitems = config.items;
7031         delete config.items;
7032     }
7033     Roo.apply(this, config);
7034     this.buttons = buttons;
7035     
7036     if(container){
7037         this.render(container);
7038     }
7039     this.xitems = xitems;
7040     Roo.each(xitems, function(b) {
7041         this.add(b);
7042     }, this);
7043     
7044 };
7045
7046 Roo.Toolbar.prototype = {
7047     /**
7048      * @cfg {Array} items
7049      * array of button configs or elements to add (will be converted to a MixedCollection)
7050      */
7051     items: false,
7052     /**
7053      * @cfg {String/HTMLElement/Element} container
7054      * The id or element that will contain the toolbar
7055      */
7056     // private
7057     render : function(ct){
7058         this.el = Roo.get(ct);
7059         if(this.cls){
7060             this.el.addClass(this.cls);
7061         }
7062         // using a table allows for vertical alignment
7063         // 100% width is needed by Safari...
7064         this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
7065         this.tr = this.el.child("tr", true);
7066         var autoId = 0;
7067         this.items = new Roo.util.MixedCollection(false, function(o){
7068             return o.id || ("item" + (++autoId));
7069         });
7070         if(this.buttons){
7071             this.add.apply(this, this.buttons);
7072             delete this.buttons;
7073         }
7074     },
7075
7076     /**
7077      * Adds element(s) to the toolbar -- this function takes a variable number of 
7078      * arguments of mixed type and adds them to the toolbar.
7079      * @param {Mixed} arg1 The following types of arguments are all valid:<br />
7080      * <ul>
7081      * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
7082      * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
7083      * <li>Field: Any form field (equivalent to {@link #addField})</li>
7084      * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
7085      * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
7086      * Note that there are a few special strings that are treated differently as explained nRoo.</li>
7087      * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
7088      * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
7089      * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
7090      * </ul>
7091      * @param {Mixed} arg2
7092      * @param {Mixed} etc.
7093      */
7094     add : function(){
7095         var a = arguments, l = a.length;
7096         for(var i = 0; i < l; i++){
7097             this._add(a[i]);
7098         }
7099     },
7100     // private..
7101     _add : function(el) {
7102         
7103         if (el.xtype) {
7104             el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
7105         }
7106         
7107         if (el.applyTo){ // some kind of form field
7108             return this.addField(el);
7109         } 
7110         if (el.render){ // some kind of Toolbar.Item
7111             return this.addItem(el);
7112         }
7113         if (typeof el == "string"){ // string
7114             if(el == "separator" || el == "-"){
7115                 return this.addSeparator();
7116             }
7117             if (el == " "){
7118                 return this.addSpacer();
7119             }
7120             if(el == "->"){
7121                 return this.addFill();
7122             }
7123             return this.addText(el);
7124             
7125         }
7126         if(el.tagName){ // element
7127             return this.addElement(el);
7128         }
7129         if(typeof el == "object"){ // must be button config?
7130             return this.addButton(el);
7131         }
7132         // and now what?!?!
7133         return false;
7134         
7135     },
7136     
7137     /**
7138      * Add an Xtype element
7139      * @param {Object} xtype Xtype Object
7140      * @return {Object} created Object
7141      */
7142     addxtype : function(e){
7143         return this.add(e);  
7144     },
7145     
7146     /**
7147      * Returns the Element for this toolbar.
7148      * @return {Roo.Element}
7149      */
7150     getEl : function(){
7151         return this.el;  
7152     },
7153     
7154     /**
7155      * Adds a separator
7156      * @return {Roo.Toolbar.Item} The separator item
7157      */
7158     addSeparator : function(){
7159         return this.addItem(new Roo.Toolbar.Separator());
7160     },
7161
7162     /**
7163      * Adds a spacer element
7164      * @return {Roo.Toolbar.Spacer} The spacer item
7165      */
7166     addSpacer : function(){
7167         return this.addItem(new Roo.Toolbar.Spacer());
7168     },
7169
7170     /**
7171      * Adds a fill element that forces subsequent additions to the right side of the toolbar
7172      * @return {Roo.Toolbar.Fill} The fill item
7173      */
7174     addFill : function(){
7175         return this.addItem(new Roo.Toolbar.Fill());
7176     },
7177
7178     /**
7179      * Adds any standard HTML element to the toolbar
7180      * @param {String/HTMLElement/Element} el The element or id of the element to add
7181      * @return {Roo.Toolbar.Item} The element's item
7182      */
7183     addElement : function(el){
7184         return this.addItem(new Roo.Toolbar.Item(el));
7185     },
7186     /**
7187      * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
7188      * @type Roo.util.MixedCollection  
7189      */
7190     items : false,
7191      
7192     /**
7193      * Adds any Toolbar.Item or subclass
7194      * @param {Roo.Toolbar.Item} item
7195      * @return {Roo.Toolbar.Item} The item
7196      */
7197     addItem : function(item){
7198         var td = this.nextBlock();
7199         item.render(td);
7200         this.items.add(item);
7201         return item;
7202     },
7203     
7204     /**
7205      * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
7206      * @param {Object/Array} config A button config or array of configs
7207      * @return {Roo.Toolbar.Button/Array}
7208      */
7209     addButton : function(config){
7210         if(config instanceof Array){
7211             var buttons = [];
7212             for(var i = 0, len = config.length; i < len; i++) {
7213                 buttons.push(this.addButton(config[i]));
7214             }
7215             return buttons;
7216         }
7217         var b = config;
7218         if(!(config instanceof Roo.Toolbar.Button)){
7219             b = config.split ?
7220                 new Roo.Toolbar.SplitButton(config) :
7221                 new Roo.Toolbar.Button(config);
7222         }
7223         var td = this.nextBlock();
7224         b.render(td);
7225         this.items.add(b);
7226         return b;
7227     },
7228     
7229     /**
7230      * Adds text to the toolbar
7231      * @param {String} text The text to add
7232      * @return {Roo.Toolbar.Item} The element's item
7233      */
7234     addText : function(text){
7235         return this.addItem(new Roo.Toolbar.TextItem(text));
7236     },
7237     
7238     /**
7239      * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
7240      * @param {Number} index The index where the item is to be inserted
7241      * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
7242      * @return {Roo.Toolbar.Button/Item}
7243      */
7244     insertButton : function(index, item){
7245         if(item instanceof Array){
7246             var buttons = [];
7247             for(var i = 0, len = item.length; i < len; i++) {
7248                buttons.push(this.insertButton(index + i, item[i]));
7249             }
7250             return buttons;
7251         }
7252         if (!(item instanceof Roo.Toolbar.Button)){
7253            item = new Roo.Toolbar.Button(item);
7254         }
7255         var td = document.createElement("td");
7256         this.tr.insertBefore(td, this.tr.childNodes[index]);
7257         item.render(td);
7258         this.items.insert(index, item);
7259         return item;
7260     },
7261     
7262     /**
7263      * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
7264      * @param {Object} config
7265      * @return {Roo.Toolbar.Item} The element's item
7266      */
7267     addDom : function(config, returnEl){
7268         var td = this.nextBlock();
7269         Roo.DomHelper.overwrite(td, config);
7270         var ti = new Roo.Toolbar.Item(td.firstChild);
7271         ti.render(td);
7272         this.items.add(ti);
7273         return ti;
7274     },
7275
7276     /**
7277      * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
7278      * @type Roo.util.MixedCollection  
7279      */
7280     fields : false,
7281     
7282     /**
7283      * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
7284      * Note: the field should not have been rendered yet. For a field that has already been
7285      * rendered, use {@link #addElement}.
7286      * @param {Roo.form.Field} field
7287      * @return {Roo.ToolbarItem}
7288      */
7289      
7290       
7291     addField : function(field) {
7292         if (!this.fields) {
7293             var autoId = 0;
7294             this.fields = new Roo.util.MixedCollection(false, function(o){
7295                 return o.id || ("item" + (++autoId));
7296             });
7297
7298         }
7299         
7300         var td = this.nextBlock();
7301         field.render(td);
7302         var ti = new Roo.Toolbar.Item(td.firstChild);
7303         ti.render(td);
7304         this.items.add(ti);
7305         this.fields.add(field);
7306         return ti;
7307     },
7308     /**
7309      * Hide the toolbar
7310      * @method hide
7311      */
7312      
7313       
7314     hide : function()
7315     {
7316         this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
7317         this.el.child('div').hide();
7318     },
7319     /**
7320      * Show the toolbar
7321      * @method show
7322      */
7323     show : function()
7324     {
7325         this.el.child('div').show();
7326     },
7327       
7328     // private
7329     nextBlock : function(){
7330         var td = document.createElement("td");
7331         this.tr.appendChild(td);
7332         return td;
7333     },
7334
7335     // private
7336     destroy : function(){
7337         if(this.items){ // rendered?
7338             Roo.destroy.apply(Roo, this.items.items);
7339         }
7340         if(this.fields){ // rendered?
7341             Roo.destroy.apply(Roo, this.fields.items);
7342         }
7343         Roo.Element.uncache(this.el, this.tr);
7344     }
7345 };
7346
7347 /**
7348  * @class Roo.Toolbar.Item
7349  * The base class that other classes should extend in order to get some basic common toolbar item functionality.
7350  * @constructor
7351  * Creates a new Item
7352  * @param {HTMLElement} el 
7353  */
7354 Roo.Toolbar.Item = function(el){
7355     var cfg = {};
7356     if (typeof (el.xtype) != 'undefined') {
7357         cfg = el;
7358         el = cfg.el;
7359     }
7360     
7361     this.el = Roo.getDom(el);
7362     this.id = Roo.id(this.el);
7363     this.hidden = false;
7364     
7365     this.addEvents({
7366          /**
7367              * @event render
7368              * Fires when the button is rendered
7369              * @param {Button} this
7370              */
7371         'render': true
7372     });
7373     Roo.Toolbar.Item.superclass.constructor.call(this,cfg);
7374 };
7375 Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
7376 //Roo.Toolbar.Item.prototype = {
7377     
7378     /**
7379      * Get this item's HTML Element
7380      * @return {HTMLElement}
7381      */
7382     getEl : function(){
7383        return this.el;  
7384     },
7385
7386     // private
7387     render : function(td){
7388         
7389          this.td = td;
7390         td.appendChild(this.el);
7391         
7392         this.fireEvent('render', this);
7393     },
7394     
7395     /**
7396      * Removes and destroys this item.
7397      */
7398     destroy : function(){
7399         this.td.parentNode.removeChild(this.td);
7400     },
7401     
7402     /**
7403      * Shows this item.
7404      */
7405     show: function(){
7406         this.hidden = false;
7407         this.td.style.display = "";
7408     },
7409     
7410     /**
7411      * Hides this item.
7412      */
7413     hide: function(){
7414         this.hidden = true;
7415         this.td.style.display = "none";
7416     },
7417     
7418     /**
7419      * Convenience function for boolean show/hide.
7420      * @param {Boolean} visible true to show/false to hide
7421      */
7422     setVisible: function(visible){
7423         if(visible) {
7424             this.show();
7425         }else{
7426             this.hide();
7427         }
7428     },
7429     
7430     /**
7431      * Try to focus this item.
7432      */
7433     focus : function(){
7434         Roo.fly(this.el).focus();
7435     },
7436     
7437     /**
7438      * Disables this item.
7439      */
7440     disable : function(){
7441         Roo.fly(this.td).addClass("x-item-disabled");
7442         this.disabled = true;
7443         this.el.disabled = true;
7444     },
7445     
7446     /**
7447      * Enables this item.
7448      */
7449     enable : function(){
7450         Roo.fly(this.td).removeClass("x-item-disabled");
7451         this.disabled = false;
7452         this.el.disabled = false;
7453     }
7454 });
7455
7456
7457 /**
7458  * @class Roo.Toolbar.Separator
7459  * @extends Roo.Toolbar.Item
7460  * A simple toolbar separator class
7461  * @constructor
7462  * Creates a new Separator
7463  */
7464 Roo.Toolbar.Separator = function(cfg){
7465     
7466     var s = document.createElement("span");
7467     s.className = "ytb-sep";
7468     if (cfg) {
7469         cfg.el = s;
7470     }
7471     
7472     Roo.Toolbar.Separator.superclass.constructor.call(this, cfg || s);
7473 };
7474 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
7475     enable:Roo.emptyFn,
7476     disable:Roo.emptyFn,
7477     focus:Roo.emptyFn
7478 });
7479
7480 /**
7481  * @class Roo.Toolbar.Spacer
7482  * @extends Roo.Toolbar.Item
7483  * A simple element that adds extra horizontal space to a toolbar.
7484  * @constructor
7485  * Creates a new Spacer
7486  */
7487 Roo.Toolbar.Spacer = function(cfg){
7488     var s = document.createElement("div");
7489     s.className = "ytb-spacer";
7490     if (cfg) {
7491         cfg.el = s;
7492     }
7493     Roo.Toolbar.Spacer.superclass.constructor.call(this, cfg || s);
7494 };
7495 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
7496     enable:Roo.emptyFn,
7497     disable:Roo.emptyFn,
7498     focus:Roo.emptyFn
7499 });
7500
7501 /**
7502  * @class Roo.Toolbar.Fill
7503  * @extends Roo.Toolbar.Spacer
7504  * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
7505  * @constructor
7506  * Creates a new Spacer
7507  */
7508 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
7509     // private
7510     render : function(td){
7511         td.style.width = '100%';
7512         Roo.Toolbar.Fill.superclass.render.call(this, td);
7513     }
7514 });
7515
7516 /**
7517  * @class Roo.Toolbar.TextItem
7518  * @extends Roo.Toolbar.Item
7519  * A simple class that renders text directly into a toolbar.
7520  * @constructor
7521  * Creates a new TextItem
7522  * @cfg {string} text 
7523  */
7524 Roo.Toolbar.TextItem = function(cfg){
7525     var  text = cfg || "";
7526     if (typeof(cfg) == 'object') {
7527         text = cfg.text || "";
7528     }  else {
7529         cfg = null;
7530     }
7531     var s = document.createElement("span");
7532     s.className = "ytb-text";
7533     s.innerHTML = text;
7534     if (cfg) {
7535         cfg.el  = s;
7536     }
7537     
7538     Roo.Toolbar.TextItem.superclass.constructor.call(this, cfg ||  s);
7539 };
7540 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
7541     
7542      
7543     enable:Roo.emptyFn,
7544     disable:Roo.emptyFn,
7545     focus:Roo.emptyFn
7546 });
7547
7548 /**
7549  * @class Roo.Toolbar.Button
7550  * @extends Roo.Button
7551  * A button that renders into a toolbar.
7552  * @constructor
7553  * Creates a new Button
7554  * @param {Object} config A standard {@link Roo.Button} config object
7555  */
7556 Roo.Toolbar.Button = function(config){
7557     Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
7558 };
7559 Roo.extend(Roo.Toolbar.Button, Roo.Button,
7560 {
7561     
7562     
7563     render : function(td){
7564         this.td = td;
7565         Roo.Toolbar.Button.superclass.render.call(this, td);
7566     },
7567     
7568     /**
7569      * Removes and destroys this button
7570      */
7571     destroy : function(){
7572         Roo.Toolbar.Button.superclass.destroy.call(this);
7573         this.td.parentNode.removeChild(this.td);
7574     },
7575     
7576     /**
7577      * Shows this button
7578      */
7579     show: function(){
7580         this.hidden = false;
7581         this.td.style.display = "";
7582     },
7583     
7584     /**
7585      * Hides this button
7586      */
7587     hide: function(){
7588         this.hidden = true;
7589         this.td.style.display = "none";
7590     },
7591
7592     /**
7593      * Disables this item
7594      */
7595     disable : function(){
7596         Roo.fly(this.td).addClass("x-item-disabled");
7597         this.disabled = true;
7598     },
7599
7600     /**
7601      * Enables this item
7602      */
7603     enable : function(){
7604         Roo.fly(this.td).removeClass("x-item-disabled");
7605         this.disabled = false;
7606     }
7607 });
7608 // backwards compat
7609 Roo.ToolbarButton = Roo.Toolbar.Button;
7610
7611 /**
7612  * @class Roo.Toolbar.SplitButton
7613  * @extends Roo.SplitButton
7614  * A menu button that renders into a toolbar.
7615  * @constructor
7616  * Creates a new SplitButton
7617  * @param {Object} config A standard {@link Roo.SplitButton} config object
7618  */
7619 Roo.Toolbar.SplitButton = function(config){
7620     Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
7621 };
7622 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
7623     render : function(td){
7624         this.td = td;
7625         Roo.Toolbar.SplitButton.superclass.render.call(this, td);
7626     },
7627     
7628     /**
7629      * Removes and destroys this button
7630      */
7631     destroy : function(){
7632         Roo.Toolbar.SplitButton.superclass.destroy.call(this);
7633         this.td.parentNode.removeChild(this.td);
7634     },
7635     
7636     /**
7637      * Shows this button
7638      */
7639     show: function(){
7640         this.hidden = false;
7641         this.td.style.display = "";
7642     },
7643     
7644     /**
7645      * Hides this button
7646      */
7647     hide: function(){
7648         this.hidden = true;
7649         this.td.style.display = "none";
7650     }
7651 });
7652
7653 // backwards compat
7654 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
7655  * Based on:
7656  * Ext JS Library 1.1.1
7657  * Copyright(c) 2006-2007, Ext JS, LLC.
7658  *
7659  * Originally Released Under LGPL - original licence link has changed is not relivant.
7660  *
7661  * Fork - LGPL
7662  * <script type="text/javascript">
7663  */
7664  
7665 /**
7666  * @class Roo.PagingToolbar
7667  * @extends Roo.Toolbar
7668  * @children   Roo.Toolbar.Item Roo.form.Field
7669  * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
7670  * @constructor
7671  * Create a new PagingToolbar
7672  * @param {Object} config The config object
7673  */
7674 Roo.PagingToolbar = function(el, ds, config)
7675 {
7676     // old args format still supported... - xtype is prefered..
7677     if (typeof(el) == 'object' && el.xtype) {
7678         // created from xtype...
7679         config = el;
7680         ds = el.dataSource;
7681         el = config.container;
7682     }
7683     var items = [];
7684     if (config.items) {
7685         items = config.items;
7686         config.items = [];
7687     }
7688     
7689     Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
7690     this.ds = ds;
7691     this.cursor = 0;
7692     this.renderButtons(this.el);
7693     this.bind(ds);
7694     
7695     // supprot items array.
7696    
7697     Roo.each(items, function(e) {
7698         this.add(Roo.factory(e));
7699     },this);
7700     
7701 };
7702
7703 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
7704    
7705     /**
7706      * @cfg {String/HTMLElement/Element} container
7707      * container The id or element that will contain the toolbar
7708      */
7709     /**
7710      * @cfg {Boolean} displayInfo
7711      * True to display the displayMsg (defaults to false)
7712      */
7713     
7714     
7715     /**
7716      * @cfg {Number} pageSize
7717      * The number of records to display per page (defaults to 20)
7718      */
7719     pageSize: 20,
7720     /**
7721      * @cfg {String} displayMsg
7722      * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
7723      */
7724     displayMsg : 'Displaying {0} - {1} of {2}',
7725     /**
7726      * @cfg {String} emptyMsg
7727      * The message to display when no records are found (defaults to "No data to display")
7728      */
7729     emptyMsg : 'No data to display',
7730     /**
7731      * Customizable piece of the default paging text (defaults to "Page")
7732      * @type String
7733      */
7734     beforePageText : "Page",
7735     /**
7736      * Customizable piece of the default paging text (defaults to "of %0")
7737      * @type String
7738      */
7739     afterPageText : "of {0}",
7740     /**
7741      * Customizable piece of the default paging text (defaults to "First Page")
7742      * @type String
7743      */
7744     firstText : "First Page",
7745     /**
7746      * Customizable piece of the default paging text (defaults to "Previous Page")
7747      * @type String
7748      */
7749     prevText : "Previous Page",
7750     /**
7751      * Customizable piece of the default paging text (defaults to "Next Page")
7752      * @type String
7753      */
7754     nextText : "Next Page",
7755     /**
7756      * Customizable piece of the default paging text (defaults to "Last Page")
7757      * @type String
7758      */
7759     lastText : "Last Page",
7760     /**
7761      * Customizable piece of the default paging text (defaults to "Refresh")
7762      * @type String
7763      */
7764     refreshText : "Refresh",
7765
7766     // private
7767     renderButtons : function(el){
7768         Roo.PagingToolbar.superclass.render.call(this, el);
7769         this.first = this.addButton({
7770             tooltip: this.firstText,
7771             cls: "x-btn-icon x-grid-page-first",
7772             disabled: true,
7773             handler: this.onClick.createDelegate(this, ["first"])
7774         });
7775         this.prev = this.addButton({
7776             tooltip: this.prevText,
7777             cls: "x-btn-icon x-grid-page-prev",
7778             disabled: true,
7779             handler: this.onClick.createDelegate(this, ["prev"])
7780         });
7781         //this.addSeparator();
7782         this.add(this.beforePageText);
7783         this.field = Roo.get(this.addDom({
7784            tag: "input",
7785            type: "text",
7786            size: "3",
7787            value: "1",
7788            cls: "x-grid-page-number"
7789         }).el);
7790         this.field.on("keydown", this.onPagingKeydown, this);
7791         this.field.on("focus", function(){this.dom.select();});
7792         this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
7793         this.field.setHeight(18);
7794         //this.addSeparator();
7795         this.next = this.addButton({
7796             tooltip: this.nextText,
7797             cls: "x-btn-icon x-grid-page-next",
7798             disabled: true,
7799             handler: this.onClick.createDelegate(this, ["next"])
7800         });
7801         this.last = this.addButton({
7802             tooltip: this.lastText,
7803             cls: "x-btn-icon x-grid-page-last",
7804             disabled: true,
7805             handler: this.onClick.createDelegate(this, ["last"])
7806         });
7807         //this.addSeparator();
7808         this.loading = this.addButton({
7809             tooltip: this.refreshText,
7810             cls: "x-btn-icon x-grid-loading",
7811             handler: this.onClick.createDelegate(this, ["refresh"])
7812         });
7813
7814         if(this.displayInfo){
7815             this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
7816         }
7817     },
7818
7819     // private
7820     updateInfo : function(){
7821         if(this.displayEl){
7822             var count = this.ds.getCount();
7823             var msg = count == 0 ?
7824                 this.emptyMsg :
7825                 String.format(
7826                     this.displayMsg,
7827                     this.cursor+1, this.cursor+count, this.ds.getTotalCount()    
7828                 );
7829             this.displayEl.update(msg);
7830         }
7831     },
7832
7833     // private
7834     onLoad : function(ds, r, o){
7835        this.cursor = o.params ? o.params.start : 0;
7836        var d = this.getPageData(), ap = d.activePage, ps = d.pages;
7837
7838        this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
7839        this.field.dom.value = ap;
7840        this.first.setDisabled(ap == 1);
7841        this.prev.setDisabled(ap == 1);
7842        this.next.setDisabled(ap == ps);
7843        this.last.setDisabled(ap == ps);
7844        this.loading.enable();
7845        this.updateInfo();
7846     },
7847
7848     // private
7849     getPageData : function(){
7850         var total = this.ds.getTotalCount();
7851         return {
7852             total : total,
7853             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
7854             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
7855         };
7856     },
7857
7858     // private
7859     onLoadError : function(){
7860         this.loading.enable();
7861     },
7862
7863     // private
7864     onPagingKeydown : function(e){
7865         var k = e.getKey();
7866         var d = this.getPageData();
7867         if(k == e.RETURN){
7868             var v = this.field.dom.value, pageNum;
7869             if(!v || isNaN(pageNum = parseInt(v, 10))){
7870                 this.field.dom.value = d.activePage;
7871                 return;
7872             }
7873             pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
7874             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
7875             e.stopEvent();
7876         }
7877         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))
7878         {
7879           var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
7880           this.field.dom.value = pageNum;
7881           this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
7882           e.stopEvent();
7883         }
7884         else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
7885         {
7886           var v = this.field.dom.value, pageNum; 
7887           var increment = (e.shiftKey) ? 10 : 1;
7888           if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
7889             increment *= -1;
7890           }
7891           if(!v || isNaN(pageNum = parseInt(v, 10))) {
7892             this.field.dom.value = d.activePage;
7893             return;
7894           }
7895           else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
7896           {
7897             this.field.dom.value = parseInt(v, 10) + increment;
7898             pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
7899             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
7900           }
7901           e.stopEvent();
7902         }
7903     },
7904
7905     // private
7906     beforeLoad : function(){
7907         if(this.loading){
7908             this.loading.disable();
7909         }
7910     },
7911
7912     // private
7913     onClick : function(which){
7914         var ds = this.ds;
7915         switch(which){
7916             case "first":
7917                 ds.load({params:{start: 0, limit: this.pageSize}});
7918             break;
7919             case "prev":
7920                 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
7921             break;
7922             case "next":
7923                 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
7924             break;
7925             case "last":
7926                 var total = ds.getTotalCount();
7927                 var extra = total % this.pageSize;
7928                 var lastStart = extra ? (total - extra) : total-this.pageSize;
7929                 ds.load({params:{start: lastStart, limit: this.pageSize}});
7930             break;
7931             case "refresh":
7932                 ds.load({params:{start: this.cursor, limit: this.pageSize}});
7933             break;
7934         }
7935     },
7936
7937     /**
7938      * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
7939      * @param {Roo.data.Store} store The data store to unbind
7940      */
7941     unbind : function(ds){
7942         ds.un("beforeload", this.beforeLoad, this);
7943         ds.un("load", this.onLoad, this);
7944         ds.un("loadexception", this.onLoadError, this);
7945         ds.un("remove", this.updateInfo, this);
7946         ds.un("add", this.updateInfo, this);
7947         this.ds = undefined;
7948     },
7949
7950     /**
7951      * Binds the paging toolbar to the specified {@link Roo.data.Store}
7952      * @param {Roo.data.Store} store The data store to bind
7953      */
7954     bind : function(ds){
7955         ds.on("beforeload", this.beforeLoad, this);
7956         ds.on("load", this.onLoad, this);
7957         ds.on("loadexception", this.onLoadError, this);
7958         ds.on("remove", this.updateInfo, this);
7959         ds.on("add", this.updateInfo, this);
7960         this.ds = ds;
7961     }
7962 });/*
7963  * Based on:
7964  * Ext JS Library 1.1.1
7965  * Copyright(c) 2006-2007, Ext JS, LLC.
7966  *
7967  * Originally Released Under LGPL - original licence link has changed is not relivant.
7968  *
7969  * Fork - LGPL
7970  * <script type="text/javascript">
7971  */
7972
7973 /**
7974  * @class Roo.Resizable
7975  * @extends Roo.util.Observable
7976  * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
7977  * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
7978  * 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
7979  * the element will be wrapped for you automatically.</p>
7980  * <p>Here is the list of valid resize handles:</p>
7981  * <pre>
7982 Value   Description
7983 ------  -------------------
7984  'n'     north
7985  's'     south
7986  'e'     east
7987  'w'     west
7988  'nw'    northwest
7989  'sw'    southwest
7990  'se'    southeast
7991  'ne'    northeast
7992  'hd'    horizontal drag
7993  'all'   all
7994 </pre>
7995  * <p>Here's an example showing the creation of a typical Resizable:</p>
7996  * <pre><code>
7997 var resizer = new Roo.Resizable("element-id", {
7998     handles: 'all',
7999     minWidth: 200,
8000     minHeight: 100,
8001     maxWidth: 500,
8002     maxHeight: 400,
8003     pinned: true
8004 });
8005 resizer.on("resize", myHandler);
8006 </code></pre>
8007  * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
8008  * resizer.east.setDisplayed(false);</p>
8009  * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
8010  * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
8011  * resize operation's new size (defaults to [0, 0])
8012  * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
8013  * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
8014  * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
8015  * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
8016  * @cfg {Boolean} enabled False to disable resizing (defaults to true)
8017  * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
8018  * @cfg {Number} width The width of the element in pixels (defaults to null)
8019  * @cfg {Number} height The height of the element in pixels (defaults to null)
8020  * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
8021  * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
8022  * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
8023  * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
8024  * @cfg {Boolean} multiDirectional <b>Deprecated</b>.  The old style of adding multi-direction resize handles, deprecated
8025  * in favor of the handles config option (defaults to false)
8026  * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
8027  * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
8028  * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
8029  * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
8030  * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
8031  * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
8032  * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
8033  * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
8034  * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
8035  * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
8036  * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
8037  * @constructor
8038  * Create a new resizable component
8039  * @param {String/HTMLElement/Roo.Element} el The id or element to resize
8040  * @param {Object} config configuration options
8041   */
8042 Roo.Resizable = function(el, config)
8043 {
8044     this.el = Roo.get(el);
8045
8046     if(config && config.wrap){
8047         config.resizeChild = this.el;
8048         this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
8049         this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
8050         this.el.setStyle("overflow", "hidden");
8051         this.el.setPositioning(config.resizeChild.getPositioning());
8052         config.resizeChild.clearPositioning();
8053         if(!config.width || !config.height){
8054             var csize = config.resizeChild.getSize();
8055             this.el.setSize(csize.width, csize.height);
8056         }
8057         if(config.pinned && !config.adjustments){
8058             config.adjustments = "auto";
8059         }
8060     }
8061
8062     this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
8063     this.proxy.unselectable();
8064     this.proxy.enableDisplayMode('block');
8065
8066     Roo.apply(this, config);
8067
8068     if(this.pinned){
8069         this.disableTrackOver = true;
8070         this.el.addClass("x-resizable-pinned");
8071     }
8072     // if the element isn't positioned, make it relative
8073     var position = this.el.getStyle("position");
8074     if(position != "absolute" && position != "fixed"){
8075         this.el.setStyle("position", "relative");
8076     }
8077     if(!this.handles){ // no handles passed, must be legacy style
8078         this.handles = 's,e,se';
8079         if(this.multiDirectional){
8080             this.handles += ',n,w';
8081         }
8082     }
8083     if(this.handles == "all"){
8084         this.handles = "n s e w ne nw se sw";
8085     }
8086     var hs = this.handles.split(/\s*?[,;]\s*?| /);
8087     var ps = Roo.Resizable.positions;
8088     for(var i = 0, len = hs.length; i < len; i++){
8089         if(hs[i] && ps[hs[i]]){
8090             var pos = ps[hs[i]];
8091             this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
8092         }
8093     }
8094     // legacy
8095     this.corner = this.southeast;
8096     
8097     // updateBox = the box can move..
8098     if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
8099         this.updateBox = true;
8100     }
8101
8102     this.activeHandle = null;
8103
8104     if(this.resizeChild){
8105         if(typeof this.resizeChild == "boolean"){
8106             this.resizeChild = Roo.get(this.el.dom.firstChild, true);
8107         }else{
8108             this.resizeChild = Roo.get(this.resizeChild, true);
8109         }
8110     }
8111     
8112     if(this.adjustments == "auto"){
8113         var rc = this.resizeChild;
8114         var hw = this.west, he = this.east, hn = this.north, hs = this.south;
8115         if(rc && (hw || hn)){
8116             rc.position("relative");
8117             rc.setLeft(hw ? hw.el.getWidth() : 0);
8118             rc.setTop(hn ? hn.el.getHeight() : 0);
8119         }
8120         this.adjustments = [
8121             (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
8122             (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
8123         ];
8124     }
8125
8126     if(this.draggable){
8127         this.dd = this.dynamic ?
8128             this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
8129         this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
8130     }
8131
8132     // public events
8133     this.addEvents({
8134         /**
8135          * @event beforeresize
8136          * Fired before resize is allowed. Set enabled to false to cancel resize.
8137          * @param {Roo.Resizable} this
8138          * @param {Roo.EventObject} e The mousedown event
8139          */
8140         "beforeresize" : true,
8141         /**
8142          * @event resizing
8143          * Fired a resizing.
8144          * @param {Roo.Resizable} this
8145          * @param {Number} x The new x position
8146          * @param {Number} y The new y position
8147          * @param {Number} w The new w width
8148          * @param {Number} h The new h hight
8149          * @param {Roo.EventObject} e The mouseup event
8150          */
8151         "resizing" : true,
8152         /**
8153          * @event resize
8154          * Fired after a resize.
8155          * @param {Roo.Resizable} this
8156          * @param {Number} width The new width
8157          * @param {Number} height The new height
8158          * @param {Roo.EventObject} e The mouseup event
8159          */
8160         "resize" : true
8161     });
8162
8163     if(this.width !== null && this.height !== null){
8164         this.resizeTo(this.width, this.height);
8165     }else{
8166         this.updateChildSize();
8167     }
8168     if(Roo.isIE){
8169         this.el.dom.style.zoom = 1;
8170     }
8171     Roo.Resizable.superclass.constructor.call(this);
8172 };
8173
8174 Roo.extend(Roo.Resizable, Roo.util.Observable, {
8175         resizeChild : false,
8176         adjustments : [0, 0],
8177         minWidth : 5,
8178         minHeight : 5,
8179         maxWidth : 10000,
8180         maxHeight : 10000,
8181         enabled : true,
8182         animate : false,
8183         duration : .35,
8184         dynamic : false,
8185         handles : false,
8186         multiDirectional : false,
8187         disableTrackOver : false,
8188         easing : 'easeOutStrong',
8189         widthIncrement : 0,
8190         heightIncrement : 0,
8191         pinned : false,
8192         width : null,
8193         height : null,
8194         preserveRatio : false,
8195         transparent: false,
8196         minX: 0,
8197         minY: 0,
8198         draggable: false,
8199
8200         /**
8201          * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
8202          */
8203         constrainTo: undefined,
8204         /**
8205          * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
8206          */
8207         resizeRegion: undefined,
8208
8209
8210     /**
8211      * Perform a manual resize
8212      * @param {Number} width
8213      * @param {Number} height
8214      */
8215     resizeTo : function(width, height){
8216         this.el.setSize(width, height);
8217         this.updateChildSize();
8218         this.fireEvent("resize", this, width, height, null);
8219     },
8220
8221     // private
8222     startSizing : function(e, handle){
8223         this.fireEvent("beforeresize", this, e);
8224         if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
8225
8226             if(!this.overlay){
8227                 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: "&#160;"});
8228                 this.overlay.unselectable();
8229                 this.overlay.enableDisplayMode("block");
8230                 this.overlay.on("mousemove", this.onMouseMove, this);
8231                 this.overlay.on("mouseup", this.onMouseUp, this);
8232             }
8233             this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
8234
8235             this.resizing = true;
8236             this.startBox = this.el.getBox();
8237             this.startPoint = e.getXY();
8238             this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
8239                             (this.startBox.y + this.startBox.height) - this.startPoint[1]];
8240
8241             this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
8242             this.overlay.show();
8243
8244             if(this.constrainTo) {
8245                 var ct = Roo.get(this.constrainTo);
8246                 this.resizeRegion = ct.getRegion().adjust(
8247                     ct.getFrameWidth('t'),
8248                     ct.getFrameWidth('l'),
8249                     -ct.getFrameWidth('b'),
8250                     -ct.getFrameWidth('r')
8251                 );
8252             }
8253
8254             this.proxy.setStyle('visibility', 'hidden'); // workaround display none
8255             this.proxy.show();
8256             this.proxy.setBox(this.startBox);
8257             if(!this.dynamic){
8258                 this.proxy.setStyle('visibility', 'visible');
8259             }
8260         }
8261     },
8262
8263     // private
8264     onMouseDown : function(handle, e){
8265         if(this.enabled){
8266             e.stopEvent();
8267             this.activeHandle = handle;
8268             this.startSizing(e, handle);
8269         }
8270     },
8271
8272     // private
8273     onMouseUp : function(e){
8274         var size = this.resizeElement();
8275         this.resizing = false;
8276         this.handleOut();
8277         this.overlay.hide();
8278         this.proxy.hide();
8279         this.fireEvent("resize", this, size.width, size.height, e);
8280     },
8281
8282     // private
8283     updateChildSize : function(){
8284         
8285         if(this.resizeChild){
8286             var el = this.el;
8287             var child = this.resizeChild;
8288             var adj = this.adjustments;
8289             if(el.dom.offsetWidth){
8290                 var b = el.getSize(true);
8291                 child.setSize(b.width+adj[0], b.height+adj[1]);
8292             }
8293             // Second call here for IE
8294             // The first call enables instant resizing and
8295             // the second call corrects scroll bars if they
8296             // exist
8297             if(Roo.isIE){
8298                 setTimeout(function(){
8299                     if(el.dom.offsetWidth){
8300                         var b = el.getSize(true);
8301                         child.setSize(b.width+adj[0], b.height+adj[1]);
8302                     }
8303                 }, 10);
8304             }
8305         }
8306     },
8307
8308     // private
8309     snap : function(value, inc, min){
8310         if(!inc || !value) {
8311             return value;
8312         }
8313         var newValue = value;
8314         var m = value % inc;
8315         if(m > 0){
8316             if(m > (inc/2)){
8317                 newValue = value + (inc-m);
8318             }else{
8319                 newValue = value - m;
8320             }
8321         }
8322         return Math.max(min, newValue);
8323     },
8324
8325     // private
8326     resizeElement : function(){
8327         var box = this.proxy.getBox();
8328         if(this.updateBox){
8329             this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
8330         }else{
8331             this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
8332         }
8333         this.updateChildSize();
8334         if(!this.dynamic){
8335             this.proxy.hide();
8336         }
8337         return box;
8338     },
8339
8340     // private
8341     constrain : function(v, diff, m, mx){
8342         if(v - diff < m){
8343             diff = v - m;
8344         }else if(v - diff > mx){
8345             diff = mx - v;
8346         }
8347         return diff;
8348     },
8349
8350     // private
8351     onMouseMove : function(e){
8352         
8353         if(this.enabled){
8354             try{// try catch so if something goes wrong the user doesn't get hung
8355
8356             if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
8357                 return;
8358             }
8359
8360             //var curXY = this.startPoint;
8361             var curSize = this.curSize || this.startBox;
8362             var x = this.startBox.x, y = this.startBox.y;
8363             var ox = x, oy = y;
8364             var w = curSize.width, h = curSize.height;
8365             var ow = w, oh = h;
8366             var mw = this.minWidth, mh = this.minHeight;
8367             var mxw = this.maxWidth, mxh = this.maxHeight;
8368             var wi = this.widthIncrement;
8369             var hi = this.heightIncrement;
8370
8371             var eventXY = e.getXY();
8372             var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
8373             var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
8374
8375             var pos = this.activeHandle.position;
8376
8377             switch(pos){
8378                 case "east":
8379                     w += diffX;
8380                     w = Math.min(Math.max(mw, w), mxw);
8381                     break;
8382              
8383                 case "south":
8384                     h += diffY;
8385                     h = Math.min(Math.max(mh, h), mxh);
8386                     break;
8387                 case "southeast":
8388                     w += diffX;
8389                     h += diffY;
8390                     w = Math.min(Math.max(mw, w), mxw);
8391                     h = Math.min(Math.max(mh, h), mxh);
8392                     break;
8393                 case "north":
8394                     diffY = this.constrain(h, diffY, mh, mxh);
8395                     y += diffY;
8396                     h -= diffY;
8397                     break;
8398                 case "hdrag":
8399                     
8400                     if (wi) {
8401                         var adiffX = Math.abs(diffX);
8402                         var sub = (adiffX % wi); // how much 
8403                         if (sub > (wi/2)) { // far enough to snap
8404                             diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
8405                         } else {
8406                             // remove difference.. 
8407                             diffX = (diffX > 0) ? diffX-sub : diffX+sub;
8408                         }
8409                     }
8410                     x += diffX;
8411                     x = Math.max(this.minX, x);
8412                     break;
8413                 case "west":
8414                     diffX = this.constrain(w, diffX, mw, mxw);
8415                     x += diffX;
8416                     w -= diffX;
8417                     break;
8418                 case "northeast":
8419                     w += diffX;
8420                     w = Math.min(Math.max(mw, w), mxw);
8421                     diffY = this.constrain(h, diffY, mh, mxh);
8422                     y += diffY;
8423                     h -= diffY;
8424                     break;
8425                 case "northwest":
8426                     diffX = this.constrain(w, diffX, mw, mxw);
8427                     diffY = this.constrain(h, diffY, mh, mxh);
8428                     y += diffY;
8429                     h -= diffY;
8430                     x += diffX;
8431                     w -= diffX;
8432                     break;
8433                case "southwest":
8434                     diffX = this.constrain(w, diffX, mw, mxw);
8435                     h += diffY;
8436                     h = Math.min(Math.max(mh, h), mxh);
8437                     x += diffX;
8438                     w -= diffX;
8439                     break;
8440             }
8441
8442             var sw = this.snap(w, wi, mw);
8443             var sh = this.snap(h, hi, mh);
8444             if(sw != w || sh != h){
8445                 switch(pos){
8446                     case "northeast":
8447                         y -= sh - h;
8448                     break;
8449                     case "north":
8450                         y -= sh - h;
8451                         break;
8452                     case "southwest":
8453                         x -= sw - w;
8454                     break;
8455                     case "west":
8456                         x -= sw - w;
8457                         break;
8458                     case "northwest":
8459                         x -= sw - w;
8460                         y -= sh - h;
8461                     break;
8462                 }
8463                 w = sw;
8464                 h = sh;
8465             }
8466
8467             if(this.preserveRatio){
8468                 switch(pos){
8469                     case "southeast":
8470                     case "east":
8471                         h = oh * (w/ow);
8472                         h = Math.min(Math.max(mh, h), mxh);
8473                         w = ow * (h/oh);
8474                        break;
8475                     case "south":
8476                         w = ow * (h/oh);
8477                         w = Math.min(Math.max(mw, w), mxw);
8478                         h = oh * (w/ow);
8479                         break;
8480                     case "northeast":
8481                         w = ow * (h/oh);
8482                         w = Math.min(Math.max(mw, w), mxw);
8483                         h = oh * (w/ow);
8484                     break;
8485                     case "north":
8486                         var tw = w;
8487                         w = ow * (h/oh);
8488                         w = Math.min(Math.max(mw, w), mxw);
8489                         h = oh * (w/ow);
8490                         x += (tw - w) / 2;
8491                         break;
8492                     case "southwest":
8493                         h = oh * (w/ow);
8494                         h = Math.min(Math.max(mh, h), mxh);
8495                         var tw = w;
8496                         w = ow * (h/oh);
8497                         x += tw - w;
8498                         break;
8499                     case "west":
8500                         var th = h;
8501                         h = oh * (w/ow);
8502                         h = Math.min(Math.max(mh, h), mxh);
8503                         y += (th - h) / 2;
8504                         var tw = w;
8505                         w = ow * (h/oh);
8506                         x += tw - w;
8507                        break;
8508                     case "northwest":
8509                         var tw = w;
8510                         var th = h;
8511                         h = oh * (w/ow);
8512                         h = Math.min(Math.max(mh, h), mxh);
8513                         w = ow * (h/oh);
8514                         y += th - h;
8515                         x += tw - w;
8516                        break;
8517
8518                 }
8519             }
8520             if (pos == 'hdrag') {
8521                 w = ow;
8522             }
8523             this.proxy.setBounds(x, y, w, h);
8524             if(this.dynamic){
8525                 this.resizeElement();
8526             }
8527             }catch(e){}
8528         }
8529         this.fireEvent("resizing", this, x, y, w, h, e);
8530     },
8531
8532     // private
8533     handleOver : function(){
8534         if(this.enabled){
8535             this.el.addClass("x-resizable-over");
8536         }
8537     },
8538
8539     // private
8540     handleOut : function(){
8541         if(!this.resizing){
8542             this.el.removeClass("x-resizable-over");
8543         }
8544     },
8545
8546     /**
8547      * Returns the element this component is bound to.
8548      * @return {Roo.Element}
8549      */
8550     getEl : function(){
8551         return this.el;
8552     },
8553
8554     /**
8555      * Returns the resizeChild element (or null).
8556      * @return {Roo.Element}
8557      */
8558     getResizeChild : function(){
8559         return this.resizeChild;
8560     },
8561     groupHandler : function()
8562     {
8563         
8564     },
8565     /**
8566      * Destroys this resizable. If the element was wrapped and
8567      * removeEl is not true then the element remains.
8568      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
8569      */
8570     destroy : function(removeEl){
8571         this.proxy.remove();
8572         if(this.overlay){
8573             this.overlay.removeAllListeners();
8574             this.overlay.remove();
8575         }
8576         var ps = Roo.Resizable.positions;
8577         for(var k in ps){
8578             if(typeof ps[k] != "function" && this[ps[k]]){
8579                 var h = this[ps[k]];
8580                 h.el.removeAllListeners();
8581                 h.el.remove();
8582             }
8583         }
8584         if(removeEl){
8585             this.el.update("");
8586             this.el.remove();
8587         }
8588     }
8589 });
8590
8591 // private
8592 // hash to map config positions to true positions
8593 Roo.Resizable.positions = {
8594     n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast", 
8595     hd: "hdrag"
8596 };
8597
8598 // private
8599 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
8600     if(!this.tpl){
8601         // only initialize the template if resizable is used
8602         var tpl = Roo.DomHelper.createTemplate(
8603             {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
8604         );
8605         tpl.compile();
8606         Roo.Resizable.Handle.prototype.tpl = tpl;
8607     }
8608     this.position = pos;
8609     this.rz = rz;
8610     // show north drag fro topdra
8611     var handlepos = pos == 'hdrag' ? 'north' : pos;
8612     
8613     this.el = this.tpl.append(rz.el.dom, [handlepos], true);
8614     if (pos == 'hdrag') {
8615         this.el.setStyle('cursor', 'pointer');
8616     }
8617     this.el.unselectable();
8618     if(transparent){
8619         this.el.setOpacity(0);
8620     }
8621     this.el.on("mousedown", this.onMouseDown, this);
8622     if(!disableTrackOver){
8623         this.el.on("mouseover", this.onMouseOver, this);
8624         this.el.on("mouseout", this.onMouseOut, this);
8625     }
8626 };
8627
8628 // private
8629 Roo.Resizable.Handle.prototype = {
8630     afterResize : function(rz){
8631         Roo.log('after?');
8632         // do nothing
8633     },
8634     // private
8635     onMouseDown : function(e){
8636         this.rz.onMouseDown(this, e);
8637     },
8638     // private
8639     onMouseOver : function(e){
8640         this.rz.handleOver(this, e);
8641     },
8642     // private
8643     onMouseOut : function(e){
8644         this.rz.handleOut(this, e);
8645     }
8646 };/*
8647  * Based on:
8648  * Ext JS Library 1.1.1
8649  * Copyright(c) 2006-2007, Ext JS, LLC.
8650  *
8651  * Originally Released Under LGPL - original licence link has changed is not relivant.
8652  *
8653  * Fork - LGPL
8654  * <script type="text/javascript">
8655  */
8656
8657 /**
8658  * @class Roo.Editor
8659  * @extends Roo.Component
8660  * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
8661  * @constructor
8662  * Create a new Editor
8663  * @param {Roo.form.Field} field The Field object (or descendant)
8664  * @param {Object} config The config object
8665  */
8666 Roo.Editor = function(field, config){
8667     Roo.Editor.superclass.constructor.call(this, config);
8668     this.field = field;
8669     this.addEvents({
8670         /**
8671              * @event beforestartedit
8672              * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
8673              * false from the handler of this event.
8674              * @param {Editor} this
8675              * @param {Roo.Element} boundEl The underlying element bound to this editor
8676              * @param {Mixed} value The field value being set
8677              */
8678         "beforestartedit" : true,
8679         /**
8680              * @event startedit
8681              * Fires when this editor is displayed
8682              * @param {Roo.Element} boundEl The underlying element bound to this editor
8683              * @param {Mixed} value The starting field value
8684              */
8685         "startedit" : true,
8686         /**
8687              * @event beforecomplete
8688              * Fires after a change has been made to the field, but before the change is reflected in the underlying
8689              * field.  Saving the change to the field can be canceled by returning false from the handler of this event.
8690              * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
8691              * event will not fire since no edit actually occurred.
8692              * @param {Editor} this
8693              * @param {Mixed} value The current field value
8694              * @param {Mixed} startValue The original field value
8695              */
8696         "beforecomplete" : true,
8697         /**
8698              * @event complete
8699              * Fires after editing is complete and any changed value has been written to the underlying field.
8700              * @param {Editor} this
8701              * @param {Mixed} value The current field value
8702              * @param {Mixed} startValue The original field value
8703              */
8704         "complete" : true,
8705         /**
8706          * @event specialkey
8707          * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
8708          * {@link Roo.EventObject#getKey} to determine which key was pressed.
8709          * @param {Roo.form.Field} this
8710          * @param {Roo.EventObject} e The event object
8711          */
8712         "specialkey" : true
8713     });
8714 };
8715
8716 Roo.extend(Roo.Editor, Roo.Component, {
8717     /**
8718      * @cfg {Boolean/String} autosize
8719      * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
8720      * or "height" to adopt the height only (defaults to false)
8721      */
8722     /**
8723      * @cfg {Boolean} revertInvalid
8724      * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
8725      * validation fails (defaults to true)
8726      */
8727     /**
8728      * @cfg {Boolean} ignoreNoChange
8729      * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
8730      * the value has not changed (defaults to false).  Applies only to string values - edits for other data types
8731      * will never be ignored.
8732      */
8733     /**
8734      * @cfg {Boolean} hideEl
8735      * False to keep the bound element visible while the editor is displayed (defaults to true)
8736      */
8737     /**
8738      * @cfg {Mixed} value
8739      * The data value of the underlying field (defaults to "")
8740      */
8741     value : "",
8742     /**
8743      * @cfg {String} alignment
8744      * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
8745      */
8746     alignment: "c-c?",
8747     /**
8748      * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
8749      * for bottom-right shadow (defaults to "frame")
8750      */
8751     shadow : "frame",
8752     /**
8753      * @cfg {Boolean} constrain True to constrain the editor to the viewport
8754      */
8755     constrain : false,
8756     /**
8757      * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
8758      */
8759     completeOnEnter : false,
8760     /**
8761      * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
8762      */
8763     cancelOnEsc : false,
8764     /**
8765      * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
8766      */
8767     updateEl : false,
8768
8769     // private
8770     onRender : function(ct, position){
8771         this.el = new Roo.Layer({
8772             shadow: this.shadow,
8773             cls: "x-editor",
8774             parentEl : ct,
8775             shim : this.shim,
8776             shadowOffset:4,
8777             id: this.id,
8778             constrain: this.constrain
8779         });
8780         this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
8781         if(this.field.msgTarget != 'title'){
8782             this.field.msgTarget = 'qtip';
8783         }
8784         this.field.render(this.el);
8785         if(Roo.isGecko){
8786             this.field.el.dom.setAttribute('autocomplete', 'off');
8787         }
8788         this.field.on("specialkey", this.onSpecialKey, this);
8789         if(this.swallowKeys){
8790             this.field.el.swallowEvent(['keydown','keypress']);
8791         }
8792         this.field.show();
8793         this.field.on("blur", this.onBlur, this);
8794         if(this.field.grow){
8795             this.field.on("autosize", this.el.sync,  this.el, {delay:1});
8796         }
8797     },
8798
8799     onSpecialKey : function(field, e)
8800     {
8801         //Roo.log('editor onSpecialKey');
8802         if(this.completeOnEnter && e.getKey() == e.ENTER){
8803             e.stopEvent();
8804             this.completeEdit();
8805             return;
8806         }
8807         // do not fire special key otherwise it might hide close the editor...
8808         if(e.getKey() == e.ENTER){    
8809             return;
8810         }
8811         if(this.cancelOnEsc && e.getKey() == e.ESC){
8812             this.cancelEdit();
8813             return;
8814         } 
8815         this.fireEvent('specialkey', field, e);
8816     
8817     },
8818
8819     /**
8820      * Starts the editing process and shows the editor.
8821      * @param {String/HTMLElement/Element} el The element to edit
8822      * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
8823       * to the innerHTML of el.
8824      */
8825     startEdit : function(el, value){
8826         if(this.editing){
8827             this.completeEdit();
8828         }
8829         this.boundEl = Roo.get(el);
8830         var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
8831         if(!this.rendered){
8832             this.render(this.parentEl || document.body);
8833         }
8834         if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
8835             return;
8836         }
8837         this.startValue = v;
8838         this.field.setValue(v);
8839         if(this.autoSize){
8840             var sz = this.boundEl.getSize();
8841             switch(this.autoSize){
8842                 case "width":
8843                 this.setSize(sz.width,  "");
8844                 break;
8845                 case "height":
8846                 this.setSize("",  sz.height);
8847                 break;
8848                 default:
8849                 this.setSize(sz.width,  sz.height);
8850             }
8851         }
8852         this.el.alignTo(this.boundEl, this.alignment);
8853         this.editing = true;
8854         if(Roo.QuickTips){
8855             Roo.QuickTips.disable();
8856         }
8857         this.show();
8858     },
8859
8860     /**
8861      * Sets the height and width of this editor.
8862      * @param {Number} width The new width
8863      * @param {Number} height The new height
8864      */
8865     setSize : function(w, h){
8866         this.field.setSize(w, h);
8867         if(this.el){
8868             this.el.sync();
8869         }
8870     },
8871
8872     /**
8873      * Realigns the editor to the bound field based on the current alignment config value.
8874      */
8875     realign : function(){
8876         this.el.alignTo(this.boundEl, this.alignment);
8877     },
8878
8879     /**
8880      * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
8881      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
8882      */
8883     completeEdit : function(remainVisible){
8884         if(!this.editing){
8885             return;
8886         }
8887         var v = this.getValue();
8888         if(this.revertInvalid !== false && !this.field.isValid()){
8889             v = this.startValue;
8890             this.cancelEdit(true);
8891         }
8892         if(String(v) === String(this.startValue) && this.ignoreNoChange){
8893             this.editing = false;
8894             this.hide();
8895             return;
8896         }
8897         if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
8898             this.editing = false;
8899             if(this.updateEl && this.boundEl){
8900                 this.boundEl.update(v);
8901             }
8902             if(remainVisible !== true){
8903                 this.hide();
8904             }
8905             this.fireEvent("complete", this, v, this.startValue);
8906         }
8907     },
8908
8909     // private
8910     onShow : function(){
8911         this.el.show();
8912         if(this.hideEl !== false){
8913             this.boundEl.hide();
8914         }
8915         this.field.show();
8916         if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
8917             this.fixIEFocus = true;
8918             this.deferredFocus.defer(50, this);
8919         }else{
8920             this.field.focus();
8921         }
8922         this.fireEvent("startedit", this.boundEl, this.startValue);
8923     },
8924
8925     deferredFocus : function(){
8926         if(this.editing){
8927             this.field.focus();
8928         }
8929     },
8930
8931     /**
8932      * Cancels the editing process and hides the editor without persisting any changes.  The field value will be
8933      * reverted to the original starting value.
8934      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
8935      * cancel (defaults to false)
8936      */
8937     cancelEdit : function(remainVisible){
8938         if(this.editing){
8939             this.setValue(this.startValue);
8940             if(remainVisible !== true){
8941                 this.hide();
8942             }
8943         }
8944     },
8945
8946     // private
8947     onBlur : function(){
8948         if(this.allowBlur !== true && this.editing){
8949             this.completeEdit();
8950         }
8951     },
8952
8953     // private
8954     onHide : function(){
8955         if(this.editing){
8956             this.completeEdit();
8957             return;
8958         }
8959         this.field.blur();
8960         if(this.field.collapse){
8961             this.field.collapse();
8962         }
8963         this.el.hide();
8964         if(this.hideEl !== false){
8965             this.boundEl.show();
8966         }
8967         if(Roo.QuickTips){
8968             Roo.QuickTips.enable();
8969         }
8970     },
8971
8972     /**
8973      * Sets the data value of the editor
8974      * @param {Mixed} value Any valid value supported by the underlying field
8975      */
8976     setValue : function(v){
8977         this.field.setValue(v);
8978     },
8979
8980     /**
8981      * Gets the data value of the editor
8982      * @return {Mixed} The data value
8983      */
8984     getValue : function(){
8985         return this.field.getValue();
8986     }
8987 });/*
8988  * Based on:
8989  * Ext JS Library 1.1.1
8990  * Copyright(c) 2006-2007, Ext JS, LLC.
8991  *
8992  * Originally Released Under LGPL - original licence link has changed is not relivant.
8993  *
8994  * Fork - LGPL
8995  * <script type="text/javascript">
8996  */
8997  
8998 /**
8999  * @class Roo.BasicDialog
9000  * @extends Roo.util.Observable
9001  * Lightweight Dialog Class.  The code below shows the creation of a typical dialog using existing HTML markup:
9002  * <pre><code>
9003 var dlg = new Roo.BasicDialog("my-dlg", {
9004     height: 200,
9005     width: 300,
9006     minHeight: 100,
9007     minWidth: 150,
9008     modal: true,
9009     proxyDrag: true,
9010     shadow: true
9011 });
9012 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
9013 dlg.addButton('OK', dlg.hide, dlg);    // Could call a save function instead of hiding
9014 dlg.addButton('Cancel', dlg.hide, dlg);
9015 dlg.show();
9016 </code></pre>
9017   <b>A Dialog should always be a direct child of the body element.</b>
9018  * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
9019  * @cfg {String} title Default text to display in the title bar (defaults to null)
9020  * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS).  Determined by browser if unspecified.
9021  * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS).  Determined by browser if unspecified.
9022  * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
9023  * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
9024  * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
9025  * (defaults to null with no animation)
9026  * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
9027  * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
9028  * property for valid values (defaults to 'all')
9029  * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
9030  * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
9031  * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
9032  * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
9033  * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
9034  * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
9035  * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
9036  * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
9037  * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
9038  * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
9039  * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
9040  * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
9041  * draggable = true (defaults to false)
9042  * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
9043  * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
9044  * shadow (defaults to false)
9045  * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
9046  * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
9047  * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
9048  * @cfg {Array} buttons Array of buttons
9049  * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
9050  * @constructor
9051  * Create a new BasicDialog.
9052  * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
9053  * @param {Object} config Configuration options
9054  */
9055 Roo.BasicDialog = function(el, config){
9056     this.el = Roo.get(el);
9057     var dh = Roo.DomHelper;
9058     if(!this.el && config && config.autoCreate){
9059         if(typeof config.autoCreate == "object"){
9060             if(!config.autoCreate.id){
9061                 config.autoCreate.id = el;
9062             }
9063             this.el = dh.append(document.body,
9064                         config.autoCreate, true);
9065         }else{
9066             this.el = dh.append(document.body,
9067                         {tag: "div", id: el, style:'visibility:hidden;'}, true);
9068         }
9069     }
9070     el = this.el;
9071     el.setDisplayed(true);
9072     el.hide = this.hideAction;
9073     this.id = el.id;
9074     el.addClass("x-dlg");
9075
9076     Roo.apply(this, config);
9077
9078     this.proxy = el.createProxy("x-dlg-proxy");
9079     this.proxy.hide = this.hideAction;
9080     this.proxy.setOpacity(.5);
9081     this.proxy.hide();
9082
9083     if(config.width){
9084         el.setWidth(config.width);
9085     }
9086     if(config.height){
9087         el.setHeight(config.height);
9088     }
9089     this.size = el.getSize();
9090     if(typeof config.x != "undefined" && typeof config.y != "undefined"){
9091         this.xy = [config.x,config.y];
9092     }else{
9093         this.xy = el.getCenterXY(true);
9094     }
9095     /** The header element @type Roo.Element */
9096     this.header = el.child("> .x-dlg-hd");
9097     /** The body element @type Roo.Element */
9098     this.body = el.child("> .x-dlg-bd");
9099     /** The footer element @type Roo.Element */
9100     this.footer = el.child("> .x-dlg-ft");
9101
9102     if(!this.header){
9103         this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: "&#160;"}, this.body ? this.body.dom : null);
9104     }
9105     if(!this.body){
9106         this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
9107     }
9108
9109     this.header.unselectable();
9110     if(this.title){
9111         this.header.update(this.title);
9112     }
9113     // this element allows the dialog to be focused for keyboard event
9114     this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
9115     this.focusEl.swallowEvent("click", true);
9116
9117     this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
9118
9119     // wrap the body and footer for special rendering
9120     this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
9121     if(this.footer){
9122         this.bwrap.dom.appendChild(this.footer.dom);
9123     }
9124
9125     this.bg = this.el.createChild({
9126         tag: "div", cls:"x-dlg-bg",
9127         html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center">&#160;</div></div></div>'
9128     });
9129     this.centerBg = this.bg.child("div.x-dlg-bg-center");
9130
9131
9132     if(this.autoScroll !== false && !this.autoTabs){
9133         this.body.setStyle("overflow", "auto");
9134     }
9135
9136     this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
9137
9138     if(this.closable !== false){
9139         this.el.addClass("x-dlg-closable");
9140         this.close = this.toolbox.createChild({cls:"x-dlg-close"});
9141         this.close.on("click", this.closeClick, this);
9142         this.close.addClassOnOver("x-dlg-close-over");
9143     }
9144     if(this.collapsible !== false){
9145         this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
9146         this.collapseBtn.on("click", this.collapseClick, this);
9147         this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
9148         this.header.on("dblclick", this.collapseClick, this);
9149     }
9150     if(this.resizable !== false){
9151         this.el.addClass("x-dlg-resizable");
9152         this.resizer = new Roo.Resizable(el, {
9153             minWidth: this.minWidth || 80,
9154             minHeight:this.minHeight || 80,
9155             handles: this.resizeHandles || "all",
9156             pinned: true
9157         });
9158         this.resizer.on("beforeresize", this.beforeResize, this);
9159         this.resizer.on("resize", this.onResize, this);
9160     }
9161     if(this.draggable !== false){
9162         el.addClass("x-dlg-draggable");
9163         if (!this.proxyDrag) {
9164             var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
9165         }
9166         else {
9167             var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
9168         }
9169         dd.setHandleElId(this.header.id);
9170         dd.endDrag = this.endMove.createDelegate(this);
9171         dd.startDrag = this.startMove.createDelegate(this);
9172         dd.onDrag = this.onDrag.createDelegate(this);
9173         dd.scroll = false;
9174         this.dd = dd;
9175     }
9176     if(this.modal){
9177         this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
9178         this.mask.enableDisplayMode("block");
9179         this.mask.hide();
9180         this.el.addClass("x-dlg-modal");
9181     }
9182     if(this.shadow){
9183         this.shadow = new Roo.Shadow({
9184             mode : typeof this.shadow == "string" ? this.shadow : "sides",
9185             offset : this.shadowOffset
9186         });
9187     }else{
9188         this.shadowOffset = 0;
9189     }
9190     if(Roo.useShims && this.shim !== false){
9191         this.shim = this.el.createShim();
9192         this.shim.hide = this.hideAction;
9193         this.shim.hide();
9194     }else{
9195         this.shim = false;
9196     }
9197     if(this.autoTabs){
9198         this.initTabs();
9199     }
9200     if (this.buttons) { 
9201         var bts= this.buttons;
9202         this.buttons = [];
9203         Roo.each(bts, function(b) {
9204             this.addButton(b);
9205         }, this);
9206     }
9207     
9208     
9209     this.addEvents({
9210         /**
9211          * @event keydown
9212          * Fires when a key is pressed
9213          * @param {Roo.BasicDialog} this
9214          * @param {Roo.EventObject} e
9215          */
9216         "keydown" : true,
9217         /**
9218          * @event move
9219          * Fires when this dialog is moved by the user.
9220          * @param {Roo.BasicDialog} this
9221          * @param {Number} x The new page X
9222          * @param {Number} y The new page Y
9223          */
9224         "move" : true,
9225         /**
9226          * @event resize
9227          * Fires when this dialog is resized by the user.
9228          * @param {Roo.BasicDialog} this
9229          * @param {Number} width The new width
9230          * @param {Number} height The new height
9231          */
9232         "resize" : true,
9233         /**
9234          * @event beforehide
9235          * Fires before this dialog is hidden.
9236          * @param {Roo.BasicDialog} this
9237          */
9238         "beforehide" : true,
9239         /**
9240          * @event hide
9241          * Fires when this dialog is hidden.
9242          * @param {Roo.BasicDialog} this
9243          */
9244         "hide" : true,
9245         /**
9246          * @event beforeshow
9247          * Fires before this dialog is shown.
9248          * @param {Roo.BasicDialog} this
9249          */
9250         "beforeshow" : true,
9251         /**
9252          * @event show
9253          * Fires when this dialog is shown.
9254          * @param {Roo.BasicDialog} this
9255          */
9256         "show" : true
9257     });
9258     el.on("keydown", this.onKeyDown, this);
9259     el.on("mousedown", this.toFront, this);
9260     Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
9261     this.el.hide();
9262     Roo.DialogManager.register(this);
9263     Roo.BasicDialog.superclass.constructor.call(this);
9264 };
9265
9266 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
9267     shadowOffset: Roo.isIE ? 6 : 5,
9268     minHeight: 80,
9269     minWidth: 200,
9270     minButtonWidth: 75,
9271     defaultButton: null,
9272     buttonAlign: "right",
9273     tabTag: 'div',
9274     firstShow: true,
9275
9276     /**
9277      * Sets the dialog title text
9278      * @param {String} text The title text to display
9279      * @return {Roo.BasicDialog} this
9280      */
9281     setTitle : function(text){
9282         this.header.update(text);
9283         return this;
9284     },
9285
9286     // private
9287     closeClick : function(){
9288         this.hide();
9289     },
9290
9291     // private
9292     collapseClick : function(){
9293         this[this.collapsed ? "expand" : "collapse"]();
9294     },
9295
9296     /**
9297      * Collapses the dialog to its minimized state (only the title bar is visible).
9298      * Equivalent to the user clicking the collapse dialog button.
9299      */
9300     collapse : function(){
9301         if(!this.collapsed){
9302             this.collapsed = true;
9303             this.el.addClass("x-dlg-collapsed");
9304             this.restoreHeight = this.el.getHeight();
9305             this.resizeTo(this.el.getWidth(), this.header.getHeight());
9306         }
9307     },
9308
9309     /**
9310      * Expands a collapsed dialog back to its normal state.  Equivalent to the user
9311      * clicking the expand dialog button.
9312      */
9313     expand : function(){
9314         if(this.collapsed){
9315             this.collapsed = false;
9316             this.el.removeClass("x-dlg-collapsed");
9317             this.resizeTo(this.el.getWidth(), this.restoreHeight);
9318         }
9319     },
9320
9321     /**
9322      * Reinitializes the tabs component, clearing out old tabs and finding new ones.
9323      * @return {Roo.TabPanel} The tabs component
9324      */
9325     initTabs : function(){
9326         var tabs = this.getTabs();
9327         while(tabs.getTab(0)){
9328             tabs.removeTab(0);
9329         }
9330         this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
9331             var dom = el.dom;
9332             tabs.addTab(Roo.id(dom), dom.title);
9333             dom.title = "";
9334         });
9335         tabs.activate(0);
9336         return tabs;
9337     },
9338
9339     // private
9340     beforeResize : function(){
9341         this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
9342     },
9343
9344     // private
9345     onResize : function(){
9346         this.refreshSize();
9347         this.syncBodyHeight();
9348         this.adjustAssets();
9349         this.focus();
9350         this.fireEvent("resize", this, this.size.width, this.size.height);
9351     },
9352
9353     // private
9354     onKeyDown : function(e){
9355         if(this.isVisible()){
9356             this.fireEvent("keydown", this, e);
9357         }
9358     },
9359
9360     /**
9361      * Resizes the dialog.
9362      * @param {Number} width
9363      * @param {Number} height
9364      * @return {Roo.BasicDialog} this
9365      */
9366     resizeTo : function(width, height){
9367         this.el.setSize(width, height);
9368         this.size = {width: width, height: height};
9369         this.syncBodyHeight();
9370         if(this.fixedcenter){
9371             this.center();
9372         }
9373         if(this.isVisible()){
9374             this.constrainXY();
9375             this.adjustAssets();
9376         }
9377         this.fireEvent("resize", this, width, height);
9378         return this;
9379     },
9380
9381
9382     /**
9383      * Resizes the dialog to fit the specified content size.
9384      * @param {Number} width
9385      * @param {Number} height
9386      * @return {Roo.BasicDialog} this
9387      */
9388     setContentSize : function(w, h){
9389         h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
9390         w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
9391         //if(!this.el.isBorderBox()){
9392             h +=  this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
9393             w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
9394         //}
9395         if(this.tabs){
9396             h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
9397             w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
9398         }
9399         this.resizeTo(w, h);
9400         return this;
9401     },
9402
9403     /**
9404      * Adds a key listener for when this dialog is displayed.  This allows you to hook in a function that will be
9405      * executed in response to a particular key being pressed while the dialog is active.
9406      * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
9407      *                                  {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
9408      * @param {Function} fn The function to call
9409      * @param {Object} scope (optional) The scope of the function
9410      * @return {Roo.BasicDialog} this
9411      */
9412     addKeyListener : function(key, fn, scope){
9413         var keyCode, shift, ctrl, alt;
9414         if(typeof key == "object" && !(key instanceof Array)){
9415             keyCode = key["key"];
9416             shift = key["shift"];
9417             ctrl = key["ctrl"];
9418             alt = key["alt"];
9419         }else{
9420             keyCode = key;
9421         }
9422         var handler = function(dlg, e){
9423             if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) &&  (!alt || e.altKey)){
9424                 var k = e.getKey();
9425                 if(keyCode instanceof Array){
9426                     for(var i = 0, len = keyCode.length; i < len; i++){
9427                         if(keyCode[i] == k){
9428                           fn.call(scope || window, dlg, k, e);
9429                           return;
9430                         }
9431                     }
9432                 }else{
9433                     if(k == keyCode){
9434                         fn.call(scope || window, dlg, k, e);
9435                     }
9436                 }
9437             }
9438         };
9439         this.on("keydown", handler);
9440         return this;
9441     },
9442
9443     /**
9444      * Returns the TabPanel component (creates it if it doesn't exist).
9445      * Note: If you wish to simply check for the existence of tabs without creating them,
9446      * check for a null 'tabs' property.
9447      * @return {Roo.TabPanel} The tabs component
9448      */
9449     getTabs : function(){
9450         if(!this.tabs){
9451             this.el.addClass("x-dlg-auto-tabs");
9452             this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
9453             this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
9454         }
9455         return this.tabs;
9456     },
9457
9458     /**
9459      * Adds a button to the footer section of the dialog.
9460      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
9461      * object or a valid Roo.DomHelper element config
9462      * @param {Function} handler The function called when the button is clicked
9463      * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
9464      * @return {Roo.Button} The new button
9465      */
9466     addButton : function(config, handler, scope){
9467         var dh = Roo.DomHelper;
9468         if(!this.footer){
9469             this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
9470         }
9471         if(!this.btnContainer){
9472             var tb = this.footer.createChild({
9473
9474                 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
9475                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
9476             }, null, true);
9477             this.btnContainer = tb.firstChild.firstChild.firstChild;
9478         }
9479         var bconfig = {
9480             handler: handler,
9481             scope: scope,
9482             minWidth: this.minButtonWidth,
9483             hideParent:true
9484         };
9485         if(typeof config == "string"){
9486             bconfig.text = config;
9487         }else{
9488             if(config.tag){
9489                 bconfig.dhconfig = config;
9490             }else{
9491                 Roo.apply(bconfig, config);
9492             }
9493         }
9494         var fc = false;
9495         if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
9496             bconfig.position = Math.max(0, bconfig.position);
9497             fc = this.btnContainer.childNodes[bconfig.position];
9498         }
9499          
9500         var btn = new Roo.Button(
9501             fc ? 
9502                 this.btnContainer.insertBefore(document.createElement("td"),fc)
9503                 : this.btnContainer.appendChild(document.createElement("td")),
9504             //Roo.get(this.btnContainer).createChild( { tag: 'td'},  fc ),
9505             bconfig
9506         );
9507         this.syncBodyHeight();
9508         if(!this.buttons){
9509             /**
9510              * Array of all the buttons that have been added to this dialog via addButton
9511              * @type Array
9512              */
9513             this.buttons = [];
9514         }
9515         this.buttons.push(btn);
9516         return btn;
9517     },
9518
9519     /**
9520      * Sets the default button to be focused when the dialog is displayed.
9521      * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
9522      * @return {Roo.BasicDialog} this
9523      */
9524     setDefaultButton : function(btn){
9525         this.defaultButton = btn;
9526         return this;
9527     },
9528
9529     // private
9530     getHeaderFooterHeight : function(safe){
9531         var height = 0;
9532         if(this.header){
9533            height += this.header.getHeight();
9534         }
9535         if(this.footer){
9536            var fm = this.footer.getMargins();
9537             height += (this.footer.getHeight()+fm.top+fm.bottom);
9538         }
9539         height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
9540         height += this.centerBg.getPadding("tb");
9541         return height;
9542     },
9543
9544     // private
9545     syncBodyHeight : function()
9546     {
9547         var bd = this.body, // the text
9548             cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
9549             bw = this.bwrap;
9550         var height = this.size.height - this.getHeaderFooterHeight(false);
9551         bd.setHeight(height-bd.getMargins("tb"));
9552         var hh = this.header.getHeight();
9553         var h = this.size.height-hh;
9554         cb.setHeight(h);
9555         
9556         bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
9557         bw.setHeight(h-cb.getPadding("tb"));
9558         
9559         bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
9560         bd.setWidth(bw.getWidth(true));
9561         if(this.tabs){
9562             this.tabs.syncHeight();
9563             if(Roo.isIE){
9564                 this.tabs.el.repaint();
9565             }
9566         }
9567     },
9568
9569     /**
9570      * Restores the previous state of the dialog if Roo.state is configured.
9571      * @return {Roo.BasicDialog} this
9572      */
9573     restoreState : function(){
9574         var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
9575         if(box && box.width){
9576             this.xy = [box.x, box.y];
9577             this.resizeTo(box.width, box.height);
9578         }
9579         return this;
9580     },
9581
9582     // private
9583     beforeShow : function(){
9584         this.expand();
9585         if(this.fixedcenter){
9586             this.xy = this.el.getCenterXY(true);
9587         }
9588         if(this.modal){
9589             Roo.get(document.body).addClass("x-body-masked");
9590             this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
9591             this.mask.show();
9592         }
9593         this.constrainXY();
9594     },
9595
9596     // private
9597     animShow : function(){
9598         var b = Roo.get(this.animateTarget).getBox();
9599         this.proxy.setSize(b.width, b.height);
9600         this.proxy.setLocation(b.x, b.y);
9601         this.proxy.show();
9602         this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
9603                     true, .35, this.showEl.createDelegate(this));
9604     },
9605
9606     /**
9607      * Shows the dialog.
9608      * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
9609      * @return {Roo.BasicDialog} this
9610      */
9611     show : function(animateTarget){
9612         if (this.fireEvent("beforeshow", this) === false){
9613             return;
9614         }
9615         if(this.syncHeightBeforeShow){
9616             this.syncBodyHeight();
9617         }else if(this.firstShow){
9618             this.firstShow = false;
9619             this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
9620         }
9621         this.animateTarget = animateTarget || this.animateTarget;
9622         if(!this.el.isVisible()){
9623             this.beforeShow();
9624             if(this.animateTarget && Roo.get(this.animateTarget)){
9625                 this.animShow();
9626             }else{
9627                 this.showEl();
9628             }
9629         }
9630         return this;
9631     },
9632
9633     // private
9634     showEl : function(){
9635         this.proxy.hide();
9636         this.el.setXY(this.xy);
9637         this.el.show();
9638         this.adjustAssets(true);
9639         this.toFront();
9640         this.focus();
9641         // IE peekaboo bug - fix found by Dave Fenwick
9642         if(Roo.isIE){
9643             this.el.repaint();
9644         }
9645         this.fireEvent("show", this);
9646     },
9647
9648     /**
9649      * Focuses the dialog.  If a defaultButton is set, it will receive focus, otherwise the
9650      * dialog itself will receive focus.
9651      */
9652     focus : function(){
9653         if(this.defaultButton){
9654             this.defaultButton.focus();
9655         }else{
9656             this.focusEl.focus();
9657         }
9658     },
9659
9660     // private
9661     constrainXY : function(){
9662         if(this.constraintoviewport !== false){
9663             if(!this.viewSize){
9664                 if(this.container){
9665                     var s = this.container.getSize();
9666                     this.viewSize = [s.width, s.height];
9667                 }else{
9668                     this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
9669                 }
9670             }
9671             var s = Roo.get(this.container||document).getScroll();
9672
9673             var x = this.xy[0], y = this.xy[1];
9674             var w = this.size.width, h = this.size.height;
9675             var vw = this.viewSize[0], vh = this.viewSize[1];
9676             // only move it if it needs it
9677             var moved = false;
9678             // first validate right/bottom
9679             if(x + w > vw+s.left){
9680                 x = vw - w;
9681                 moved = true;
9682             }
9683             if(y + h > vh+s.top){
9684                 y = vh - h;
9685                 moved = true;
9686             }
9687             // then make sure top/left isn't negative
9688             if(x < s.left){
9689                 x = s.left;
9690                 moved = true;
9691             }
9692             if(y < s.top){
9693                 y = s.top;
9694                 moved = true;
9695             }
9696             if(moved){
9697                 // cache xy
9698                 this.xy = [x, y];
9699                 if(this.isVisible()){
9700                     this.el.setLocation(x, y);
9701                     this.adjustAssets();
9702                 }
9703             }
9704         }
9705     },
9706
9707     // private
9708     onDrag : function(){
9709         if(!this.proxyDrag){
9710             this.xy = this.el.getXY();
9711             this.adjustAssets();
9712         }
9713     },
9714
9715     // private
9716     adjustAssets : function(doShow){
9717         var x = this.xy[0], y = this.xy[1];
9718         var w = this.size.width, h = this.size.height;
9719         if(doShow === true){
9720             if(this.shadow){
9721                 this.shadow.show(this.el);
9722             }
9723             if(this.shim){
9724                 this.shim.show();
9725             }
9726         }
9727         if(this.shadow && this.shadow.isVisible()){
9728             this.shadow.show(this.el);
9729         }
9730         if(this.shim && this.shim.isVisible()){
9731             this.shim.setBounds(x, y, w, h);
9732         }
9733     },
9734
9735     // private
9736     adjustViewport : function(w, h){
9737         if(!w || !h){
9738             w = Roo.lib.Dom.getViewWidth();
9739             h = Roo.lib.Dom.getViewHeight();
9740         }
9741         // cache the size
9742         this.viewSize = [w, h];
9743         if(this.modal && this.mask.isVisible()){
9744             this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
9745             this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
9746         }
9747         if(this.isVisible()){
9748             this.constrainXY();
9749         }
9750     },
9751
9752     /**
9753      * Destroys this dialog and all its supporting elements (including any tabs, shim,
9754      * shadow, proxy, mask, etc.)  Also removes all event listeners.
9755      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
9756      */
9757     destroy : function(removeEl){
9758         if(this.isVisible()){
9759             this.animateTarget = null;
9760             this.hide();
9761         }
9762         Roo.EventManager.removeResizeListener(this.adjustViewport, this);
9763         if(this.tabs){
9764             this.tabs.destroy(removeEl);
9765         }
9766         Roo.destroy(
9767              this.shim,
9768              this.proxy,
9769              this.resizer,
9770              this.close,
9771              this.mask
9772         );
9773         if(this.dd){
9774             this.dd.unreg();
9775         }
9776         if(this.buttons){
9777            for(var i = 0, len = this.buttons.length; i < len; i++){
9778                this.buttons[i].destroy();
9779            }
9780         }
9781         this.el.removeAllListeners();
9782         if(removeEl === true){
9783             this.el.update("");
9784             this.el.remove();
9785         }
9786         Roo.DialogManager.unregister(this);
9787     },
9788
9789     // private
9790     startMove : function(){
9791         if(this.proxyDrag){
9792             this.proxy.show();
9793         }
9794         if(this.constraintoviewport !== false){
9795             this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
9796         }
9797     },
9798
9799     // private
9800     endMove : function(){
9801         if(!this.proxyDrag){
9802             Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
9803         }else{
9804             Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
9805             this.proxy.hide();
9806         }
9807         this.refreshSize();
9808         this.adjustAssets();
9809         this.focus();
9810         this.fireEvent("move", this, this.xy[0], this.xy[1]);
9811     },
9812
9813     /**
9814      * Brings this dialog to the front of any other visible dialogs
9815      * @return {Roo.BasicDialog} this
9816      */
9817     toFront : function(){
9818         Roo.DialogManager.bringToFront(this);
9819         return this;
9820     },
9821
9822     /**
9823      * Sends this dialog to the back (under) of any other visible dialogs
9824      * @return {Roo.BasicDialog} this
9825      */
9826     toBack : function(){
9827         Roo.DialogManager.sendToBack(this);
9828         return this;
9829     },
9830
9831     /**
9832      * Centers this dialog in the viewport
9833      * @return {Roo.BasicDialog} this
9834      */
9835     center : function(){
9836         var xy = this.el.getCenterXY(true);
9837         this.moveTo(xy[0], xy[1]);
9838         return this;
9839     },
9840
9841     /**
9842      * Moves the dialog's top-left corner to the specified point
9843      * @param {Number} x
9844      * @param {Number} y
9845      * @return {Roo.BasicDialog} this
9846      */
9847     moveTo : function(x, y){
9848         this.xy = [x,y];
9849         if(this.isVisible()){
9850             this.el.setXY(this.xy);
9851             this.adjustAssets();
9852         }
9853         return this;
9854     },
9855
9856     /**
9857      * Aligns the dialog to the specified element
9858      * @param {String/HTMLElement/Roo.Element} element The element to align to.
9859      * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
9860      * @param {Array} offsets (optional) Offset the positioning by [x, y]
9861      * @return {Roo.BasicDialog} this
9862      */
9863     alignTo : function(element, position, offsets){
9864         this.xy = this.el.getAlignToXY(element, position, offsets);
9865         if(this.isVisible()){
9866             this.el.setXY(this.xy);
9867             this.adjustAssets();
9868         }
9869         return this;
9870     },
9871
9872     /**
9873      * Anchors an element to another element and realigns it when the window is resized.
9874      * @param {String/HTMLElement/Roo.Element} element The element to align to.
9875      * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
9876      * @param {Array} offsets (optional) Offset the positioning by [x, y]
9877      * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
9878      * is a number, it is used as the buffer delay (defaults to 50ms).
9879      * @return {Roo.BasicDialog} this
9880      */
9881     anchorTo : function(el, alignment, offsets, monitorScroll){
9882         var action = function(){
9883             this.alignTo(el, alignment, offsets);
9884         };
9885         Roo.EventManager.onWindowResize(action, this);
9886         var tm = typeof monitorScroll;
9887         if(tm != 'undefined'){
9888             Roo.EventManager.on(window, 'scroll', action, this,
9889                 {buffer: tm == 'number' ? monitorScroll : 50});
9890         }
9891         action.call(this);
9892         return this;
9893     },
9894
9895     /**
9896      * Returns true if the dialog is visible
9897      * @return {Boolean}
9898      */
9899     isVisible : function(){
9900         return this.el.isVisible();
9901     },
9902
9903     // private
9904     animHide : function(callback){
9905         var b = Roo.get(this.animateTarget).getBox();
9906         this.proxy.show();
9907         this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
9908         this.el.hide();
9909         this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
9910                     this.hideEl.createDelegate(this, [callback]));
9911     },
9912
9913     /**
9914      * Hides the dialog.
9915      * @param {Function} callback (optional) Function to call when the dialog is hidden
9916      * @return {Roo.BasicDialog} this
9917      */
9918     hide : function(callback){
9919         if (this.fireEvent("beforehide", this) === false){
9920             return;
9921         }
9922         if(this.shadow){
9923             this.shadow.hide();
9924         }
9925         if(this.shim) {
9926           this.shim.hide();
9927         }
9928         // sometimes animateTarget seems to get set.. causing problems...
9929         // this just double checks..
9930         if(this.animateTarget && Roo.get(this.animateTarget)) {
9931            this.animHide(callback);
9932         }else{
9933             this.el.hide();
9934             this.hideEl(callback);
9935         }
9936         return this;
9937     },
9938
9939     // private
9940     hideEl : function(callback){
9941         this.proxy.hide();
9942         if(this.modal){
9943             this.mask.hide();
9944             Roo.get(document.body).removeClass("x-body-masked");
9945         }
9946         this.fireEvent("hide", this);
9947         if(typeof callback == "function"){
9948             callback();
9949         }
9950     },
9951
9952     // private
9953     hideAction : function(){
9954         this.setLeft("-10000px");
9955         this.setTop("-10000px");
9956         this.setStyle("visibility", "hidden");
9957     },
9958
9959     // private
9960     refreshSize : function(){
9961         this.size = this.el.getSize();
9962         this.xy = this.el.getXY();
9963         Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
9964     },
9965
9966     // private
9967     // z-index is managed by the DialogManager and may be overwritten at any time
9968     setZIndex : function(index){
9969         if(this.modal){
9970             this.mask.setStyle("z-index", index);
9971         }
9972         if(this.shim){
9973             this.shim.setStyle("z-index", ++index);
9974         }
9975         if(this.shadow){
9976             this.shadow.setZIndex(++index);
9977         }
9978         this.el.setStyle("z-index", ++index);
9979         if(this.proxy){
9980             this.proxy.setStyle("z-index", ++index);
9981         }
9982         if(this.resizer){
9983             this.resizer.proxy.setStyle("z-index", ++index);
9984         }
9985
9986         this.lastZIndex = index;
9987     },
9988
9989     /**
9990      * Returns the element for this dialog
9991      * @return {Roo.Element} The underlying dialog Element
9992      */
9993     getEl : function(){
9994         return this.el;
9995     }
9996 });
9997
9998 /**
9999  * @class Roo.DialogManager
10000  * Provides global access to BasicDialogs that have been created and
10001  * support for z-indexing (layering) multiple open dialogs.
10002  */
10003 Roo.DialogManager = function(){
10004     var list = {};
10005     var accessList = [];
10006     var front = null;
10007
10008     // private
10009     var sortDialogs = function(d1, d2){
10010         return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
10011     };
10012
10013     // private
10014     var orderDialogs = function(){
10015         accessList.sort(sortDialogs);
10016         var seed = Roo.DialogManager.zseed;
10017         for(var i = 0, len = accessList.length; i < len; i++){
10018             var dlg = accessList[i];
10019             if(dlg){
10020                 dlg.setZIndex(seed + (i*10));
10021             }
10022         }
10023     };
10024
10025     return {
10026         /**
10027          * The starting z-index for BasicDialogs (defaults to 9000)
10028          * @type Number The z-index value
10029          */
10030         zseed : 9000,
10031
10032         // private
10033         register : function(dlg){
10034             list[dlg.id] = dlg;
10035             accessList.push(dlg);
10036         },
10037
10038         // private
10039         unregister : function(dlg){
10040             delete list[dlg.id];
10041             var i=0;
10042             var len=0;
10043             if(!accessList.indexOf){
10044                 for(  i = 0, len = accessList.length; i < len; i++){
10045                     if(accessList[i] == dlg){
10046                         accessList.splice(i, 1);
10047                         return;
10048                     }
10049                 }
10050             }else{
10051                  i = accessList.indexOf(dlg);
10052                 if(i != -1){
10053                     accessList.splice(i, 1);
10054                 }
10055             }
10056         },
10057
10058         /**
10059          * Gets a registered dialog by id
10060          * @param {String/Object} id The id of the dialog or a dialog
10061          * @return {Roo.BasicDialog} this
10062          */
10063         get : function(id){
10064             return typeof id == "object" ? id : list[id];
10065         },
10066
10067         /**
10068          * Brings the specified dialog to the front
10069          * @param {String/Object} dlg The id of the dialog or a dialog
10070          * @return {Roo.BasicDialog} this
10071          */
10072         bringToFront : function(dlg){
10073             dlg = this.get(dlg);
10074             if(dlg != front){
10075                 front = dlg;
10076                 dlg._lastAccess = new Date().getTime();
10077                 orderDialogs();
10078             }
10079             return dlg;
10080         },
10081
10082         /**
10083          * Sends the specified dialog to the back
10084          * @param {String/Object} dlg The id of the dialog or a dialog
10085          * @return {Roo.BasicDialog} this
10086          */
10087         sendToBack : function(dlg){
10088             dlg = this.get(dlg);
10089             dlg._lastAccess = -(new Date().getTime());
10090             orderDialogs();
10091             return dlg;
10092         },
10093
10094         /**
10095          * Hides all dialogs
10096          */
10097         hideAll : function(){
10098             for(var id in list){
10099                 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
10100                     list[id].hide();
10101                 }
10102             }
10103         }
10104     };
10105 }();
10106
10107 /**
10108  * @class Roo.LayoutDialog
10109  * @extends Roo.BasicDialog
10110  * @children Roo.ContentPanel
10111  * @parent builder none
10112  * Dialog which provides adjustments for working with a layout in a Dialog.
10113  * Add your necessary layout config options to the dialog's config.<br>
10114  * Example usage (including a nested layout):
10115  * <pre><code>
10116 if(!dialog){
10117     dialog = new Roo.LayoutDialog("download-dlg", {
10118         modal: true,
10119         width:600,
10120         height:450,
10121         shadow:true,
10122         minWidth:500,
10123         minHeight:350,
10124         autoTabs:true,
10125         proxyDrag:true,
10126         // layout config merges with the dialog config
10127         center:{
10128             tabPosition: "top",
10129             alwaysShowTabs: true
10130         }
10131     });
10132     dialog.addKeyListener(27, dialog.hide, dialog);
10133     dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
10134     dialog.addButton("Build It!", this.getDownload, this);
10135
10136     // we can even add nested layouts
10137     var innerLayout = new Roo.BorderLayout("dl-inner", {
10138         east: {
10139             initialSize: 200,
10140             autoScroll:true,
10141             split:true
10142         },
10143         center: {
10144             autoScroll:true
10145         }
10146     });
10147     innerLayout.beginUpdate();
10148     innerLayout.add("east", new Roo.ContentPanel("dl-details"));
10149     innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
10150     innerLayout.endUpdate(true);
10151
10152     var layout = dialog.getLayout();
10153     layout.beginUpdate();
10154     layout.add("center", new Roo.ContentPanel("standard-panel",
10155                         {title: "Download the Source", fitToFrame:true}));
10156     layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
10157                {title: "Build your own roo.js"}));
10158     layout.getRegion("center").showPanel(sp);
10159     layout.endUpdate();
10160 }
10161 </code></pre>
10162     * @constructor
10163     * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
10164     * @param {Object} config configuration options
10165   */
10166 Roo.LayoutDialog = function(el, cfg){
10167     
10168     var config=  cfg;
10169     if (typeof(cfg) == 'undefined') {
10170         config = Roo.apply({}, el);
10171         // not sure why we use documentElement here.. - it should always be body.
10172         // IE7 borks horribly if we use documentElement.
10173         // webkit also does not like documentElement - it creates a body element...
10174         el = Roo.get( document.body || document.documentElement ).createChild();
10175         //config.autoCreate = true;
10176     }
10177     
10178     
10179     config.autoTabs = false;
10180     Roo.LayoutDialog.superclass.constructor.call(this, el, config);
10181     this.body.setStyle({overflow:"hidden", position:"relative"});
10182     this.layout = new Roo.BorderLayout(this.body.dom, config);
10183     this.layout.monitorWindowResize = false;
10184     this.el.addClass("x-dlg-auto-layout");
10185     // fix case when center region overwrites center function
10186     this.center = Roo.BasicDialog.prototype.center;
10187     this.on("show", this.layout.layout, this.layout, true);
10188     if (config.items) {
10189         var xitems = config.items;
10190         delete config.items;
10191         Roo.each(xitems, this.addxtype, this);
10192     }
10193     
10194     
10195 };
10196 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
10197     
10198     
10199     /**
10200      * @cfg {Roo.LayoutRegion} east  
10201      */
10202     /**
10203      * @cfg {Roo.LayoutRegion} west
10204      */
10205     /**
10206      * @cfg {Roo.LayoutRegion} south
10207      */
10208     /**
10209      * @cfg {Roo.LayoutRegion} north
10210      */
10211     /**
10212      * @cfg {Roo.LayoutRegion} center
10213      */
10214     /**
10215      * @cfg {Roo.Button} buttons[]  Bottom buttons..
10216      */
10217     
10218     
10219     /**
10220      * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
10221      * @deprecated
10222      */
10223     endUpdate : function(){
10224         this.layout.endUpdate();
10225     },
10226
10227     /**
10228      * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
10229      *  @deprecated
10230      */
10231     beginUpdate : function(){
10232         this.layout.beginUpdate();
10233     },
10234
10235     /**
10236      * Get the BorderLayout for this dialog
10237      * @return {Roo.BorderLayout}
10238      */
10239     getLayout : function(){
10240         return this.layout;
10241     },
10242
10243     showEl : function(){
10244         Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
10245         if(Roo.isIE7){
10246             this.layout.layout();
10247         }
10248     },
10249
10250     // private
10251     // Use the syncHeightBeforeShow config option to control this automatically
10252     syncBodyHeight : function(){
10253         Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
10254         if(this.layout){this.layout.layout();}
10255     },
10256     
10257       /**
10258      * Add an xtype element (actually adds to the layout.)
10259      * @return {Object} xdata xtype object data.
10260      */
10261     
10262     addxtype : function(c) {
10263         return this.layout.addxtype(c);
10264     }
10265 });/*
10266  * Based on:
10267  * Ext JS Library 1.1.1
10268  * Copyright(c) 2006-2007, Ext JS, LLC.
10269  *
10270  * Originally Released Under LGPL - original licence link has changed is not relivant.
10271  *
10272  * Fork - LGPL
10273  * <script type="text/javascript">
10274  */
10275  
10276 /**
10277  * @class Roo.MessageBox
10278  * Utility class for generating different styles of message boxes.  The alias Roo.Msg can also be used.
10279  * Example usage:
10280  *<pre><code>
10281 // Basic alert:
10282 Roo.Msg.alert('Status', 'Changes saved successfully.');
10283
10284 // Prompt for user data:
10285 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
10286     if (btn == 'ok'){
10287         // process text value...
10288     }
10289 });
10290
10291 // Show a dialog using config options:
10292 Roo.Msg.show({
10293    title:'Save Changes?',
10294    msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
10295    buttons: Roo.Msg.YESNOCANCEL,
10296    fn: processResult,
10297    animEl: 'elId'
10298 });
10299 </code></pre>
10300  * @static
10301  */
10302 Roo.MessageBox = function(){
10303     var dlg, opt, mask, waitTimer;
10304     var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
10305     var buttons, activeTextEl, bwidth;
10306
10307     // private
10308     var handleButton = function(button){
10309         dlg.hide();
10310         Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
10311     };
10312
10313     // private
10314     var handleHide = function(){
10315         if(opt && opt.cls){
10316             dlg.el.removeClass(opt.cls);
10317         }
10318         if(waitTimer){
10319             Roo.TaskMgr.stop(waitTimer);
10320             waitTimer = null;
10321         }
10322     };
10323
10324     // private
10325     var updateButtons = function(b){
10326         var width = 0;
10327         if(!b){
10328             buttons["ok"].hide();
10329             buttons["cancel"].hide();
10330             buttons["yes"].hide();
10331             buttons["no"].hide();
10332             dlg.footer.dom.style.display = 'none';
10333             return width;
10334         }
10335         dlg.footer.dom.style.display = '';
10336         for(var k in buttons){
10337             if(typeof buttons[k] != "function"){
10338                 if(b[k]){
10339                     buttons[k].show();
10340                     buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
10341                     width += buttons[k].el.getWidth()+15;
10342                 }else{
10343                     buttons[k].hide();
10344                 }
10345             }
10346         }
10347         return width;
10348     };
10349
10350     // private
10351     var handleEsc = function(d, k, e){
10352         if(opt && opt.closable !== false){
10353             dlg.hide();
10354         }
10355         if(e){
10356             e.stopEvent();
10357         }
10358     };
10359
10360     return {
10361         /**
10362          * Returns a reference to the underlying {@link Roo.BasicDialog} element
10363          * @return {Roo.BasicDialog} The BasicDialog element
10364          */
10365         getDialog : function(){
10366            if(!dlg){
10367                 dlg = new Roo.BasicDialog("x-msg-box", {
10368                     autoCreate : true,
10369                     shadow: true,
10370                     draggable: true,
10371                     resizable:false,
10372                     constraintoviewport:false,
10373                     fixedcenter:true,
10374                     collapsible : false,
10375                     shim:true,
10376                     modal: true,
10377                     width:400, height:100,
10378                     buttonAlign:"center",
10379                     closeClick : function(){
10380                         if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
10381                             handleButton("no");
10382                         }else{
10383                             handleButton("cancel");
10384                         }
10385                     }
10386                 });
10387                 dlg.on("hide", handleHide);
10388                 mask = dlg.mask;
10389                 dlg.addKeyListener(27, handleEsc);
10390                 buttons = {};
10391                 var bt = this.buttonText;
10392                 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
10393                 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
10394                 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
10395                 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
10396                 bodyEl = dlg.body.createChild({
10397
10398                     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>'
10399                 });
10400                 msgEl = bodyEl.dom.firstChild;
10401                 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
10402                 textboxEl.enableDisplayMode();
10403                 textboxEl.addKeyListener([10,13], function(){
10404                     if(dlg.isVisible() && opt && opt.buttons){
10405                         if(opt.buttons.ok){
10406                             handleButton("ok");
10407                         }else if(opt.buttons.yes){
10408                             handleButton("yes");
10409                         }
10410                     }
10411                 });
10412                 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
10413                 textareaEl.enableDisplayMode();
10414                 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
10415                 progressEl.enableDisplayMode();
10416                 var pf = progressEl.dom.firstChild;
10417                 if (pf) {
10418                     pp = Roo.get(pf.firstChild);
10419                     pp.setHeight(pf.offsetHeight);
10420                 }
10421                 
10422             }
10423             return dlg;
10424         },
10425
10426         /**
10427          * Updates the message box body text
10428          * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
10429          * the XHTML-compliant non-breaking space character '&amp;#160;')
10430          * @return {Roo.MessageBox} This message box
10431          */
10432         updateText : function(text){
10433             if(!dlg.isVisible() && !opt.width){
10434                 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
10435             }
10436             msgEl.innerHTML = text || '&#160;';
10437       
10438             var cw =  Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
10439             //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
10440             var w = Math.max(
10441                     Math.min(opt.width || cw , this.maxWidth), 
10442                     Math.max(opt.minWidth || this.minWidth, bwidth)
10443             );
10444             if(opt.prompt){
10445                 activeTextEl.setWidth(w);
10446             }
10447             if(dlg.isVisible()){
10448                 dlg.fixedcenter = false;
10449             }
10450             // to big, make it scroll. = But as usual stupid IE does not support
10451             // !important..
10452             
10453             if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
10454                 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
10455                 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
10456             } else {
10457                 bodyEl.dom.style.height = '';
10458                 bodyEl.dom.style.overflowY = '';
10459             }
10460             if (cw > w) {
10461                 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
10462             } else {
10463                 bodyEl.dom.style.overflowX = '';
10464             }
10465             
10466             dlg.setContentSize(w, bodyEl.getHeight());
10467             if(dlg.isVisible()){
10468                 dlg.fixedcenter = true;
10469             }
10470             return this;
10471         },
10472
10473         /**
10474          * Updates a progress-style message box's text and progress bar.  Only relevant on message boxes
10475          * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
10476          * @param {Number} value Any number between 0 and 1 (e.g., .5)
10477          * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
10478          * @return {Roo.MessageBox} This message box
10479          */
10480         updateProgress : function(value, text){
10481             if(text){
10482                 this.updateText(text);
10483             }
10484             if (pp) { // weird bug on my firefox - for some reason this is not defined
10485                 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
10486             }
10487             return this;
10488         },        
10489
10490         /**
10491          * Returns true if the message box is currently displayed
10492          * @return {Boolean} True if the message box is visible, else false
10493          */
10494         isVisible : function(){
10495             return dlg && dlg.isVisible();  
10496         },
10497
10498         /**
10499          * Hides the message box if it is displayed
10500          */
10501         hide : function(){
10502             if(this.isVisible()){
10503                 dlg.hide();
10504             }  
10505         },
10506
10507         /**
10508          * Displays a new message box, or reinitializes an existing message box, based on the config options
10509          * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
10510          * The following config object properties are supported:
10511          * <pre>
10512 Property    Type             Description
10513 ----------  ---------------  ------------------------------------------------------------------------------------
10514 animEl            String/Element   An id or Element from which the message box should animate as it opens and
10515                                    closes (defaults to undefined)
10516 buttons           Object/Boolean   A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
10517                                    cancel:'Bar'}), or false to not show any buttons (defaults to false)
10518 closable          Boolean          False to hide the top-right close button (defaults to true).  Note that
10519                                    progress and wait dialogs will ignore this property and always hide the
10520                                    close button as they can only be closed programmatically.
10521 cls               String           A custom CSS class to apply to the message box element
10522 defaultTextHeight Number           The default height in pixels of the message box's multiline textarea if
10523                                    displayed (defaults to 75)
10524 fn                Function         A callback function to execute after closing the dialog.  The arguments to the
10525                                    function will be btn (the name of the button that was clicked, if applicable,
10526                                    e.g. "ok"), and text (the value of the active text field, if applicable).
10527                                    Progress and wait dialogs will ignore this option since they do not respond to
10528                                    user actions and can only be closed programmatically, so any required function
10529                                    should be called by the same code after it closes the dialog.
10530 icon              String           A CSS class that provides a background image to be used as an icon for
10531                                    the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
10532 maxWidth          Number           The maximum width in pixels of the message box (defaults to 600)
10533 minWidth          Number           The minimum width in pixels of the message box (defaults to 100)
10534 modal             Boolean          False to allow user interaction with the page while the message box is
10535                                    displayed (defaults to true)
10536 msg               String           A string that will replace the existing message box body text (defaults
10537                                    to the XHTML-compliant non-breaking space character '&#160;')
10538 multiline         Boolean          True to prompt the user to enter multi-line text (defaults to false)
10539 progress          Boolean          True to display a progress bar (defaults to false)
10540 progressText      String           The text to display inside the progress bar if progress = true (defaults to '')
10541 prompt            Boolean          True to prompt the user to enter single-line text (defaults to false)
10542 proxyDrag         Boolean          True to display a lightweight proxy while dragging (defaults to false)
10543 title             String           The title text
10544 value             String           The string value to set into the active textbox element if displayed
10545 wait              Boolean          True to display a progress bar (defaults to false)
10546 width             Number           The width of the dialog in pixels
10547 </pre>
10548          *
10549          * Example usage:
10550          * <pre><code>
10551 Roo.Msg.show({
10552    title: 'Address',
10553    msg: 'Please enter your address:',
10554    width: 300,
10555    buttons: Roo.MessageBox.OKCANCEL,
10556    multiline: true,
10557    fn: saveAddress,
10558    animEl: 'addAddressBtn'
10559 });
10560 </code></pre>
10561          * @param {Object} config Configuration options
10562          * @return {Roo.MessageBox} This message box
10563          */
10564         show : function(options)
10565         {
10566             
10567             // this causes nightmares if you show one dialog after another
10568             // especially on callbacks..
10569              
10570             if(this.isVisible()){
10571                 
10572                 this.hide();
10573                 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
10574                 Roo.log("Old Dialog Message:" +  msgEl.innerHTML );
10575                 Roo.log("New Dialog Message:" +  options.msg )
10576                 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
10577                 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
10578                 
10579             }
10580             var d = this.getDialog();
10581             opt = options;
10582             d.setTitle(opt.title || "&#160;");
10583             d.close.setDisplayed(opt.closable !== false);
10584             activeTextEl = textboxEl;
10585             opt.prompt = opt.prompt || (opt.multiline ? true : false);
10586             if(opt.prompt){
10587                 if(opt.multiline){
10588                     textboxEl.hide();
10589                     textareaEl.show();
10590                     textareaEl.setHeight(typeof opt.multiline == "number" ?
10591                         opt.multiline : this.defaultTextHeight);
10592                     activeTextEl = textareaEl;
10593                 }else{
10594                     textboxEl.show();
10595                     textareaEl.hide();
10596                 }
10597             }else{
10598                 textboxEl.hide();
10599                 textareaEl.hide();
10600             }
10601             progressEl.setDisplayed(opt.progress === true);
10602             this.updateProgress(0);
10603             activeTextEl.dom.value = opt.value || "";
10604             if(opt.prompt){
10605                 dlg.setDefaultButton(activeTextEl);
10606             }else{
10607                 var bs = opt.buttons;
10608                 var db = null;
10609                 if(bs && bs.ok){
10610                     db = buttons["ok"];
10611                 }else if(bs && bs.yes){
10612                     db = buttons["yes"];
10613                 }
10614                 dlg.setDefaultButton(db);
10615             }
10616             bwidth = updateButtons(opt.buttons);
10617             this.updateText(opt.msg);
10618             if(opt.cls){
10619                 d.el.addClass(opt.cls);
10620             }
10621             d.proxyDrag = opt.proxyDrag === true;
10622             d.modal = opt.modal !== false;
10623             d.mask = opt.modal !== false ? mask : false;
10624             if(!d.isVisible()){
10625                 // force it to the end of the z-index stack so it gets a cursor in FF
10626                 document.body.appendChild(dlg.el.dom);
10627                 d.animateTarget = null;
10628                 d.show(options.animEl);
10629             }
10630             return this;
10631         },
10632
10633         /**
10634          * Displays a message box with a progress bar.  This message box has no buttons and is not closeable by
10635          * the user.  You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
10636          * and closing the message box when the process is complete.
10637          * @param {String} title The title bar text
10638          * @param {String} msg The message box body text
10639          * @return {Roo.MessageBox} This message box
10640          */
10641         progress : function(title, msg){
10642             this.show({
10643                 title : title,
10644                 msg : msg,
10645                 buttons: false,
10646                 progress:true,
10647                 closable:false,
10648                 minWidth: this.minProgressWidth,
10649                 modal : true
10650             });
10651             return this;
10652         },
10653
10654         /**
10655          * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
10656          * If a callback function is passed it will be called after the user clicks the button, and the
10657          * id of the button that was clicked will be passed as the only parameter to the callback
10658          * (could also be the top-right close button).
10659          * @param {String} title The title bar text
10660          * @param {String} msg The message box body text
10661          * @param {Function} fn (optional) The callback function invoked after the message box is closed
10662          * @param {Object} scope (optional) The scope of the callback function
10663          * @return {Roo.MessageBox} This message box
10664          */
10665         alert : function(title, msg, fn, scope){
10666             this.show({
10667                 title : title,
10668                 msg : msg,
10669                 buttons: this.OK,
10670                 fn: fn,
10671                 scope : scope,
10672                 modal : true
10673             });
10674             return this;
10675         },
10676
10677         /**
10678          * Displays a message box with an infinitely auto-updating progress bar.  This can be used to block user
10679          * interaction while waiting for a long-running process to complete that does not have defined intervals.
10680          * You are responsible for closing the message box when the process is complete.
10681          * @param {String} msg The message box body text
10682          * @param {String} title (optional) The title bar text
10683          * @return {Roo.MessageBox} This message box
10684          */
10685         wait : function(msg, title){
10686             this.show({
10687                 title : title,
10688                 msg : msg,
10689                 buttons: false,
10690                 closable:false,
10691                 progress:true,
10692                 modal:true,
10693                 width:300,
10694                 wait:true
10695             });
10696             waitTimer = Roo.TaskMgr.start({
10697                 run: function(i){
10698                     Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
10699                 },
10700                 interval: 1000
10701             });
10702             return this;
10703         },
10704
10705         /**
10706          * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
10707          * If a callback function is passed it will be called after the user clicks either button, and the id of the
10708          * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
10709          * @param {String} title The title bar text
10710          * @param {String} msg The message box body text
10711          * @param {Function} fn (optional) The callback function invoked after the message box is closed
10712          * @param {Object} scope (optional) The scope of the callback function
10713          * @return {Roo.MessageBox} This message box
10714          */
10715         confirm : function(title, msg, fn, scope){
10716             this.show({
10717                 title : title,
10718                 msg : msg,
10719                 buttons: this.YESNO,
10720                 fn: fn,
10721                 scope : scope,
10722                 modal : true
10723             });
10724             return this;
10725         },
10726
10727         /**
10728          * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
10729          * JavaScript's Window.prompt).  The prompt can be a single-line or multi-line textbox.  If a callback function
10730          * is passed it will be called after the user clicks either button, and the id of the button that was clicked
10731          * (could also be the top-right close button) and the text that was entered will be passed as the two
10732          * parameters to the callback.
10733          * @param {String} title The title bar text
10734          * @param {String} msg The message box body text
10735          * @param {Function} fn (optional) The callback function invoked after the message box is closed
10736          * @param {Object} scope (optional) The scope of the callback function
10737          * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
10738          * property, or the height in pixels to create the textbox (defaults to false / single-line)
10739          * @return {Roo.MessageBox} This message box
10740          */
10741         prompt : function(title, msg, fn, scope, multiline){
10742             this.show({
10743                 title : title,
10744                 msg : msg,
10745                 buttons: this.OKCANCEL,
10746                 fn: fn,
10747                 minWidth:250,
10748                 scope : scope,
10749                 prompt:true,
10750                 multiline: multiline,
10751                 modal : true
10752             });
10753             return this;
10754         },
10755
10756         /**
10757          * Button config that displays a single OK button
10758          * @type Object
10759          */
10760         OK : {ok:true},
10761         /**
10762          * Button config that displays Yes and No buttons
10763          * @type Object
10764          */
10765         YESNO : {yes:true, no:true},
10766         /**
10767          * Button config that displays OK and Cancel buttons
10768          * @type Object
10769          */
10770         OKCANCEL : {ok:true, cancel:true},
10771         /**
10772          * Button config that displays Yes, No and Cancel buttons
10773          * @type Object
10774          */
10775         YESNOCANCEL : {yes:true, no:true, cancel:true},
10776
10777         /**
10778          * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
10779          * @type Number
10780          */
10781         defaultTextHeight : 75,
10782         /**
10783          * The maximum width in pixels of the message box (defaults to 600)
10784          * @type Number
10785          */
10786         maxWidth : 600,
10787         /**
10788          * The minimum width in pixels of the message box (defaults to 100)
10789          * @type Number
10790          */
10791         minWidth : 100,
10792         /**
10793          * The minimum width in pixels of the message box if it is a progress-style dialog.  This is useful
10794          * for setting a different minimum width than text-only dialogs may need (defaults to 250)
10795          * @type Number
10796          */
10797         minProgressWidth : 250,
10798         /**
10799          * An object containing the default button text strings that can be overriden for localized language support.
10800          * Supported properties are: ok, cancel, yes and no.
10801          * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
10802          * @type Object
10803          */
10804         buttonText : {
10805             ok : "OK",
10806             cancel : "Cancel",
10807             yes : "Yes",
10808             no : "No"
10809         }
10810     };
10811 }();
10812
10813 /**
10814  * Shorthand for {@link Roo.MessageBox}
10815  */
10816 Roo.Msg = Roo.MessageBox;/*
10817  * Based on:
10818  * Ext JS Library 1.1.1
10819  * Copyright(c) 2006-2007, Ext JS, LLC.
10820  *
10821  * Originally Released Under LGPL - original licence link has changed is not relivant.
10822  *
10823  * Fork - LGPL
10824  * <script type="text/javascript">
10825  */
10826 /**
10827  * @class Roo.QuickTips
10828  * Provides attractive and customizable tooltips for any element.
10829  * @static
10830  */
10831 Roo.QuickTips = function(){
10832     var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
10833     var ce, bd, xy, dd;
10834     var visible = false, disabled = true, inited = false;
10835     var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
10836     
10837     var onOver = function(e){
10838         if(disabled){
10839             return;
10840         }
10841         var t = e.getTarget();
10842         if(!t || t.nodeType !== 1 || t == document || t == document.body){
10843             return;
10844         }
10845         if(ce && t == ce.el){
10846             clearTimeout(hideProc);
10847             return;
10848         }
10849         if(t && tagEls[t.id]){
10850             tagEls[t.id].el = t;
10851             showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
10852             return;
10853         }
10854         var ttp, et = Roo.fly(t);
10855         var ns = cfg.namespace;
10856         if(tm.interceptTitles && t.title){
10857             ttp = t.title;
10858             t.qtip = ttp;
10859             t.removeAttribute("title");
10860             e.preventDefault();
10861         }else{
10862             ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute) || et.getAttributeNS(cfg.alt_namespace, cfg.attribute) ;
10863         }
10864         if(ttp){
10865             showProc = show.defer(tm.showDelay, tm, [{
10866                 el: t, 
10867                 text: ttp.replace(/\\n/g,'<br/>'),
10868                 width: et.getAttributeNS(ns, cfg.width),
10869                 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
10870                 title: et.getAttributeNS(ns, cfg.title),
10871                     cls: et.getAttributeNS(ns, cfg.cls)
10872             }]);
10873         }
10874     };
10875     
10876     var onOut = function(e){
10877         clearTimeout(showProc);
10878         var t = e.getTarget();
10879         if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
10880             hideProc = setTimeout(hide, tm.hideDelay);
10881         }
10882     };
10883     
10884     var onMove = function(e){
10885         if(disabled){
10886             return;
10887         }
10888         xy = e.getXY();
10889         xy[1] += 18;
10890         if(tm.trackMouse && ce){
10891             el.setXY(xy);
10892         }
10893     };
10894     
10895     var onDown = function(e){
10896         clearTimeout(showProc);
10897         clearTimeout(hideProc);
10898         if(!e.within(el)){
10899             if(tm.hideOnClick){
10900                 hide();
10901                 tm.disable();
10902                 tm.enable.defer(100, tm);
10903             }
10904         }
10905     };
10906     
10907     var getPad = function(){
10908         return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
10909     };
10910
10911     var show = function(o){
10912         if(disabled){
10913             return;
10914         }
10915         clearTimeout(dismissProc);
10916         ce = o;
10917         if(removeCls){ // in case manually hidden
10918             el.removeClass(removeCls);
10919             removeCls = null;
10920         }
10921         if(ce.cls){
10922             el.addClass(ce.cls);
10923             removeCls = ce.cls;
10924         }
10925         if(ce.title){
10926             tipTitle.update(ce.title);
10927             tipTitle.show();
10928         }else{
10929             tipTitle.update('');
10930             tipTitle.hide();
10931         }
10932         el.dom.style.width  = tm.maxWidth+'px';
10933         //tipBody.dom.style.width = '';
10934         tipBodyText.update(o.text);
10935         var p = getPad(), w = ce.width;
10936         if(!w){
10937             var td = tipBodyText.dom;
10938             var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
10939             if(aw > tm.maxWidth){
10940                 w = tm.maxWidth;
10941             }else if(aw < tm.minWidth){
10942                 w = tm.minWidth;
10943             }else{
10944                 w = aw;
10945             }
10946         }
10947         //tipBody.setWidth(w);
10948         el.setWidth(parseInt(w, 10) + p);
10949         if(ce.autoHide === false){
10950             close.setDisplayed(true);
10951             if(dd){
10952                 dd.unlock();
10953             }
10954         }else{
10955             close.setDisplayed(false);
10956             if(dd){
10957                 dd.lock();
10958             }
10959         }
10960         if(xy){
10961             el.avoidY = xy[1]-18;
10962             el.setXY(xy);
10963         }
10964         if(tm.animate){
10965             el.setOpacity(.1);
10966             el.setStyle("visibility", "visible");
10967             el.fadeIn({callback: afterShow});
10968         }else{
10969             afterShow();
10970         }
10971     };
10972     
10973     var afterShow = function(){
10974         if(ce){
10975             el.show();
10976             esc.enable();
10977             if(tm.autoDismiss && ce.autoHide !== false){
10978                 dismissProc = setTimeout(hide, tm.autoDismissDelay);
10979             }
10980         }
10981     };
10982     
10983     var hide = function(noanim){
10984         clearTimeout(dismissProc);
10985         clearTimeout(hideProc);
10986         ce = null;
10987         if(el.isVisible()){
10988             esc.disable();
10989             if(noanim !== true && tm.animate){
10990                 el.fadeOut({callback: afterHide});
10991             }else{
10992                 afterHide();
10993             } 
10994         }
10995     };
10996     
10997     var afterHide = function(){
10998         el.hide();
10999         if(removeCls){
11000             el.removeClass(removeCls);
11001             removeCls = null;
11002         }
11003     };
11004     
11005     return {
11006         /**
11007         * @cfg {Number} minWidth
11008         * The minimum width of the quick tip (defaults to 40)
11009         */
11010        minWidth : 40,
11011         /**
11012         * @cfg {Number} maxWidth
11013         * The maximum width of the quick tip (defaults to 300)
11014         */
11015        maxWidth : 300,
11016         /**
11017         * @cfg {Boolean} interceptTitles
11018         * True to automatically use the element's DOM title value if available (defaults to false)
11019         */
11020        interceptTitles : false,
11021         /**
11022         * @cfg {Boolean} trackMouse
11023         * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
11024         */
11025        trackMouse : false,
11026         /**
11027         * @cfg {Boolean} hideOnClick
11028         * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
11029         */
11030        hideOnClick : true,
11031         /**
11032         * @cfg {Number} showDelay
11033         * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
11034         */
11035        showDelay : 500,
11036         /**
11037         * @cfg {Number} hideDelay
11038         * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
11039         */
11040        hideDelay : 200,
11041         /**
11042         * @cfg {Boolean} autoHide
11043         * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
11044         * Used in conjunction with hideDelay.
11045         */
11046        autoHide : true,
11047         /**
11048         * @cfg {Boolean}
11049         * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
11050         * (defaults to true).  Used in conjunction with autoDismissDelay.
11051         */
11052        autoDismiss : true,
11053         /**
11054         * @cfg {Number}
11055         * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
11056         */
11057        autoDismissDelay : 5000,
11058        /**
11059         * @cfg {Boolean} animate
11060         * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
11061         */
11062        animate : false,
11063
11064        /**
11065         * @cfg {String} title
11066         * Title text to display (defaults to '').  This can be any valid HTML markup.
11067         */
11068         title: '',
11069        /**
11070         * @cfg {String} text
11071         * Body text to display (defaults to '').  This can be any valid HTML markup.
11072         */
11073         text : '',
11074        /**
11075         * @cfg {String} cls
11076         * A CSS class to apply to the base quick tip element (defaults to '').
11077         */
11078         cls : '',
11079        /**
11080         * @cfg {Number} width
11081         * Width in pixels of the quick tip (defaults to auto).  Width will be ignored if it exceeds the bounds of
11082         * minWidth or maxWidth.
11083         */
11084         width : null,
11085
11086     /**
11087      * Initialize and enable QuickTips for first use.  This should be called once before the first attempt to access
11088      * or display QuickTips in a page.
11089      */
11090        init : function(){
11091           tm = Roo.QuickTips;
11092           cfg = tm.tagConfig;
11093           if(!inited){
11094               if(!Roo.isReady){ // allow calling of init() before onReady
11095                   Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
11096                   return;
11097               }
11098               el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
11099               el.fxDefaults = {stopFx: true};
11100               // maximum custom styling
11101               //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>');
11102               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>');              
11103               tipTitle = el.child('h3');
11104               tipTitle.enableDisplayMode("block");
11105               tipBody = el.child('div.x-tip-bd');
11106               tipBodyText = el.child('div.x-tip-bd-inner');
11107               //bdLeft = el.child('div.x-tip-bd-left');
11108               //bdRight = el.child('div.x-tip-bd-right');
11109               close = el.child('div.x-tip-close');
11110               close.enableDisplayMode("block");
11111               close.on("click", hide);
11112               var d = Roo.get(document);
11113               d.on("mousedown", onDown);
11114               d.on("mouseover", onOver);
11115               d.on("mouseout", onOut);
11116               d.on("mousemove", onMove);
11117               esc = d.addKeyListener(27, hide);
11118               esc.disable();
11119               if(Roo.dd.DD){
11120                   dd = el.initDD("default", null, {
11121                       onDrag : function(){
11122                           el.sync();  
11123                       }
11124                   });
11125                   dd.setHandleElId(tipTitle.id);
11126                   dd.lock();
11127               }
11128               inited = true;
11129           }
11130           this.enable(); 
11131        },
11132
11133     /**
11134      * Configures a new quick tip instance and assigns it to a target element.  The following config options
11135      * are supported:
11136      * <pre>
11137 Property    Type                   Description
11138 ----------  ---------------------  ------------------------------------------------------------------------
11139 target      Element/String/Array   An Element, id or array of ids that this quick tip should be tied to
11140      * </ul>
11141      * @param {Object} config The config object
11142      */
11143        register : function(config){
11144            var cs = config instanceof Array ? config : arguments;
11145            for(var i = 0, len = cs.length; i < len; i++) {
11146                var c = cs[i];
11147                var target = c.target;
11148                if(target){
11149                    if(target instanceof Array){
11150                        for(var j = 0, jlen = target.length; j < jlen; j++){
11151                            tagEls[target[j]] = c;
11152                        }
11153                    }else{
11154                        tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
11155                    }
11156                }
11157            }
11158        },
11159
11160     /**
11161      * Removes this quick tip from its element and destroys it.
11162      * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
11163      */
11164        unregister : function(el){
11165            delete tagEls[Roo.id(el)];
11166        },
11167
11168     /**
11169      * Enable this quick tip.
11170      */
11171        enable : function(){
11172            if(inited && disabled){
11173                locks.pop();
11174                if(locks.length < 1){
11175                    disabled = false;
11176                }
11177            }
11178        },
11179
11180     /**
11181      * Disable this quick tip.
11182      */
11183        disable : function(){
11184           disabled = true;
11185           clearTimeout(showProc);
11186           clearTimeout(hideProc);
11187           clearTimeout(dismissProc);
11188           if(ce){
11189               hide(true);
11190           }
11191           locks.push(1);
11192        },
11193
11194     /**
11195      * Returns true if the quick tip is enabled, else false.
11196      */
11197        isEnabled : function(){
11198             return !disabled;
11199        },
11200
11201         // private
11202        tagConfig : {
11203            namespace : "roo", // was ext?? this may break..
11204            alt_namespace : "ext",
11205            attribute : "qtip",
11206            width : "width",
11207            target : "target",
11208            title : "qtitle",
11209            hide : "hide",
11210            cls : "qclass"
11211        }
11212    };
11213 }();
11214
11215 // backwards compat
11216 Roo.QuickTips.tips = Roo.QuickTips.register;/*
11217  * Based on:
11218  * Ext JS Library 1.1.1
11219  * Copyright(c) 2006-2007, Ext JS, LLC.
11220  *
11221  * Originally Released Under LGPL - original licence link has changed is not relivant.
11222  *
11223  * Fork - LGPL
11224  * <script type="text/javascript">
11225  */
11226  
11227
11228 /**
11229  * @class Roo.tree.TreePanel
11230  * @extends Roo.data.Tree
11231  * @cfg {Roo.tree.TreeNode} root The root node
11232  * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
11233  * @cfg {Boolean} lines false to disable tree lines (defaults to true)
11234  * @cfg {Boolean} enableDD true to enable drag and drop
11235  * @cfg {Boolean} enableDrag true to enable just drag
11236  * @cfg {Boolean} enableDrop true to enable just drop
11237  * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
11238  * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
11239  * @cfg {String} ddGroup The DD group this TreePanel belongs to
11240  * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
11241  * @cfg {Boolean} ddScroll true to enable YUI body scrolling
11242  * @cfg {Boolean} containerScroll true to register this container with ScrollManager
11243  * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
11244  * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
11245  * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
11246  * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
11247  * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
11248  * @cfg {Roo.tree.TreeLoader} loader A TreeLoader for use with this TreePanel
11249  * @cfg {Roo.tree.TreeEditor} editor The TreeEditor to display when clicked.
11250  * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
11251  * @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>
11252  * @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>
11253  * 
11254  * @constructor
11255  * @param {String/HTMLElement/Element} el The container element
11256  * @param {Object} config
11257  */
11258 Roo.tree.TreePanel = function(el, config){
11259     var root = false;
11260     var loader = false;
11261     if (config.root) {
11262         root = config.root;
11263         delete config.root;
11264     }
11265     if (config.loader) {
11266         loader = config.loader;
11267         delete config.loader;
11268     }
11269     
11270     Roo.apply(this, config);
11271     Roo.tree.TreePanel.superclass.constructor.call(this);
11272     this.el = Roo.get(el);
11273     this.el.addClass('x-tree');
11274     //console.log(root);
11275     if (root) {
11276         this.setRootNode( Roo.factory(root, Roo.tree));
11277     }
11278     if (loader) {
11279         this.loader = Roo.factory(loader, Roo.tree);
11280     }
11281    /**
11282     * Read-only. The id of the container element becomes this TreePanel's id.
11283     */
11284     this.id = this.el.id;
11285     this.addEvents({
11286         /**
11287         * @event beforeload
11288         * Fires before a node is loaded, return false to cancel
11289         * @param {Node} node The node being loaded
11290         */
11291         "beforeload" : true,
11292         /**
11293         * @event load
11294         * Fires when a node is loaded
11295         * @param {Node} node The node that was loaded
11296         */
11297         "load" : true,
11298         /**
11299         * @event textchange
11300         * Fires when the text for a node is changed
11301         * @param {Node} node The node
11302         * @param {String} text The new text
11303         * @param {String} oldText The old text
11304         */
11305         "textchange" : true,
11306         /**
11307         * @event beforeexpand
11308         * Fires before a node is expanded, return false to cancel.
11309         * @param {Node} node The node
11310         * @param {Boolean} deep
11311         * @param {Boolean} anim
11312         */
11313         "beforeexpand" : true,
11314         /**
11315         * @event beforecollapse
11316         * Fires before a node is collapsed, return false to cancel.
11317         * @param {Node} node The node
11318         * @param {Boolean} deep
11319         * @param {Boolean} anim
11320         */
11321         "beforecollapse" : true,
11322         /**
11323         * @event expand
11324         * Fires when a node is expanded
11325         * @param {Node} node The node
11326         */
11327         "expand" : true,
11328         /**
11329         * @event disabledchange
11330         * Fires when the disabled status of a node changes
11331         * @param {Node} node The node
11332         * @param {Boolean} disabled
11333         */
11334         "disabledchange" : true,
11335         /**
11336         * @event collapse
11337         * Fires when a node is collapsed
11338         * @param {Node} node The node
11339         */
11340         "collapse" : true,
11341         /**
11342         * @event beforeclick
11343         * Fires before click processing on a node. Return false to cancel the default action.
11344         * @param {Node} node The node
11345         * @param {Roo.EventObject} e The event object
11346         */
11347         "beforeclick":true,
11348         /**
11349         * @event checkchange
11350         * Fires when a node with a checkbox's checked property changes
11351         * @param {Node} this This node
11352         * @param {Boolean} checked
11353         */
11354         "checkchange":true,
11355         /**
11356         * @event click
11357         * Fires when a node is clicked
11358         * @param {Node} node The node
11359         * @param {Roo.EventObject} e The event object
11360         */
11361         "click":true,
11362         /**
11363         * @event dblclick
11364         * Fires when a node is double clicked
11365         * @param {Node} node The node
11366         * @param {Roo.EventObject} e The event object
11367         */
11368         "dblclick":true,
11369         /**
11370         * @event contextmenu
11371         * Fires when a node is right clicked
11372         * @param {Node} node The node
11373         * @param {Roo.EventObject} e The event object
11374         */
11375         "contextmenu":true,
11376         /**
11377         * @event beforechildrenrendered
11378         * Fires right before the child nodes for a node are rendered
11379         * @param {Node} node The node
11380         */
11381         "beforechildrenrendered":true,
11382         /**
11383         * @event startdrag
11384         * Fires when a node starts being dragged
11385         * @param {Roo.tree.TreePanel} this
11386         * @param {Roo.tree.TreeNode} node
11387         * @param {event} e The raw browser event
11388         */ 
11389        "startdrag" : true,
11390        /**
11391         * @event enddrag
11392         * Fires when a drag operation is complete
11393         * @param {Roo.tree.TreePanel} this
11394         * @param {Roo.tree.TreeNode} node
11395         * @param {event} e The raw browser event
11396         */
11397        "enddrag" : true,
11398        /**
11399         * @event dragdrop
11400         * Fires when a dragged node is dropped on a valid DD target
11401         * @param {Roo.tree.TreePanel} this
11402         * @param {Roo.tree.TreeNode} node
11403         * @param {DD} dd The dd it was dropped on
11404         * @param {event} e The raw browser event
11405         */
11406        "dragdrop" : true,
11407        /**
11408         * @event beforenodedrop
11409         * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
11410         * passed to handlers has the following properties:<br />
11411         * <ul style="padding:5px;padding-left:16px;">
11412         * <li>tree - The TreePanel</li>
11413         * <li>target - The node being targeted for the drop</li>
11414         * <li>data - The drag data from the drag source</li>
11415         * <li>point - The point of the drop - append, above or below</li>
11416         * <li>source - The drag source</li>
11417         * <li>rawEvent - Raw mouse event</li>
11418         * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
11419         * to be inserted by setting them on this object.</li>
11420         * <li>cancel - Set this to true to cancel the drop.</li>
11421         * </ul>
11422         * @param {Object} dropEvent
11423         */
11424        "beforenodedrop" : true,
11425        /**
11426         * @event nodedrop
11427         * Fires after a DD object is dropped on a node in this tree. The dropEvent
11428         * passed to handlers has the following properties:<br />
11429         * <ul style="padding:5px;padding-left:16px;">
11430         * <li>tree - The TreePanel</li>
11431         * <li>target - The node being targeted for the drop</li>
11432         * <li>data - The drag data from the drag source</li>
11433         * <li>point - The point of the drop - append, above or below</li>
11434         * <li>source - The drag source</li>
11435         * <li>rawEvent - Raw mouse event</li>
11436         * <li>dropNode - Dropped node(s).</li>
11437         * </ul>
11438         * @param {Object} dropEvent
11439         */
11440        "nodedrop" : true,
11441         /**
11442         * @event nodedragover
11443         * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
11444         * passed to handlers has the following properties:<br />
11445         * <ul style="padding:5px;padding-left:16px;">
11446         * <li>tree - The TreePanel</li>
11447         * <li>target - The node being targeted for the drop</li>
11448         * <li>data - The drag data from the drag source</li>
11449         * <li>point - The point of the drop - append, above or below</li>
11450         * <li>source - The drag source</li>
11451         * <li>rawEvent - Raw mouse event</li>
11452         * <li>dropNode - Drop node(s) provided by the source.</li>
11453         * <li>cancel - Set this to true to signal drop not allowed.</li>
11454         * </ul>
11455         * @param {Object} dragOverEvent
11456         */
11457        "nodedragover" : true,
11458        /**
11459         * @event appendnode
11460         * Fires when append node to the tree
11461         * @param {Roo.tree.TreePanel} this
11462         * @param {Roo.tree.TreeNode} node
11463         * @param {Number} index The index of the newly appended node
11464         */
11465        "appendnode" : true
11466         
11467     });
11468     if(this.singleExpand){
11469        this.on("beforeexpand", this.restrictExpand, this);
11470     }
11471     if (this.editor) {
11472         this.editor.tree = this;
11473         this.editor = Roo.factory(this.editor, Roo.tree);
11474     }
11475     
11476     if (this.selModel) {
11477         this.selModel = Roo.factory(this.selModel, Roo.tree);
11478     }
11479    
11480 };
11481 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
11482     rootVisible : true,
11483     animate: Roo.enableFx,
11484     lines : true,
11485     enableDD : false,
11486     hlDrop : Roo.enableFx,
11487   
11488     renderer: false,
11489     
11490     rendererTip: false,
11491     // private
11492     restrictExpand : function(node){
11493         var p = node.parentNode;
11494         if(p){
11495             if(p.expandedChild && p.expandedChild.parentNode == p){
11496                 p.expandedChild.collapse();
11497             }
11498             p.expandedChild = node;
11499         }
11500     },
11501
11502     // private override
11503     setRootNode : function(node){
11504         Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
11505         if(!this.rootVisible){
11506             node.ui = new Roo.tree.RootTreeNodeUI(node);
11507         }
11508         return node;
11509     },
11510
11511     /**
11512      * Returns the container element for this TreePanel
11513      */
11514     getEl : function(){
11515         return this.el;
11516     },
11517
11518     /**
11519      * Returns the default TreeLoader for this TreePanel
11520      */
11521     getLoader : function(){
11522         return this.loader;
11523     },
11524
11525     /**
11526      * Expand all nodes
11527      */
11528     expandAll : function(){
11529         this.root.expand(true);
11530     },
11531
11532     /**
11533      * Collapse all nodes
11534      */
11535     collapseAll : function(){
11536         this.root.collapse(true);
11537     },
11538
11539     /**
11540      * Returns the selection model used by this TreePanel
11541      */
11542     getSelectionModel : function(){
11543         if(!this.selModel){
11544             this.selModel = new Roo.tree.DefaultSelectionModel();
11545         }
11546         return this.selModel;
11547     },
11548
11549     /**
11550      * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
11551      * @param {String} attribute (optional) Defaults to null (return the actual nodes)
11552      * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
11553      * @return {Array}
11554      */
11555     getChecked : function(a, startNode){
11556         startNode = startNode || this.root;
11557         var r = [];
11558         var f = function(){
11559             if(this.attributes.checked){
11560                 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
11561             }
11562         }
11563         startNode.cascade(f);
11564         return r;
11565     },
11566
11567     /**
11568      * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
11569      * @param {String} path
11570      * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
11571      * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
11572      * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
11573      */
11574     expandPath : function(path, attr, callback){
11575         attr = attr || "id";
11576         var keys = path.split(this.pathSeparator);
11577         var curNode = this.root;
11578         if(curNode.attributes[attr] != keys[1]){ // invalid root
11579             if(callback){
11580                 callback(false, null);
11581             }
11582             return;
11583         }
11584         var index = 1;
11585         var f = function(){
11586             if(++index == keys.length){
11587                 if(callback){
11588                     callback(true, curNode);
11589                 }
11590                 return;
11591             }
11592             var c = curNode.findChild(attr, keys[index]);
11593             if(!c){
11594                 if(callback){
11595                     callback(false, curNode);
11596                 }
11597                 return;
11598             }
11599             curNode = c;
11600             c.expand(false, false, f);
11601         };
11602         curNode.expand(false, false, f);
11603     },
11604
11605     /**
11606      * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
11607      * @param {String} path
11608      * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
11609      * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
11610      * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
11611      */
11612     selectPath : function(path, attr, callback){
11613         attr = attr || "id";
11614         var keys = path.split(this.pathSeparator);
11615         var v = keys.pop();
11616         if(keys.length > 0){
11617             var f = function(success, node){
11618                 if(success && node){
11619                     var n = node.findChild(attr, v);
11620                     if(n){
11621                         n.select();
11622                         if(callback){
11623                             callback(true, n);
11624                         }
11625                     }else if(callback){
11626                         callback(false, n);
11627                     }
11628                 }else{
11629                     if(callback){
11630                         callback(false, n);
11631                     }
11632                 }
11633             };
11634             this.expandPath(keys.join(this.pathSeparator), attr, f);
11635         }else{
11636             this.root.select();
11637             if(callback){
11638                 callback(true, this.root);
11639             }
11640         }
11641     },
11642
11643     getTreeEl : function(){
11644         return this.el;
11645     },
11646
11647     /**
11648      * Trigger rendering of this TreePanel
11649      */
11650     render : function(){
11651         if (this.innerCt) {
11652             return this; // stop it rendering more than once!!
11653         }
11654         
11655         this.innerCt = this.el.createChild({tag:"ul",
11656                cls:"x-tree-root-ct " +
11657                (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
11658
11659         if(this.containerScroll){
11660             Roo.dd.ScrollManager.register(this.el);
11661         }
11662         if((this.enableDD || this.enableDrop) && !this.dropZone){
11663            /**
11664             * The dropZone used by this tree if drop is enabled
11665             * @type Roo.tree.TreeDropZone
11666             */
11667              this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
11668                ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
11669            });
11670         }
11671         if((this.enableDD || this.enableDrag) && !this.dragZone){
11672            /**
11673             * The dragZone used by this tree if drag is enabled
11674             * @type Roo.tree.TreeDragZone
11675             */
11676             this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
11677                ddGroup: this.ddGroup || "TreeDD",
11678                scroll: this.ddScroll
11679            });
11680         }
11681         this.getSelectionModel().init(this);
11682         if (!this.root) {
11683             Roo.log("ROOT not set in tree");
11684             return this;
11685         }
11686         this.root.render();
11687         if(!this.rootVisible){
11688             this.root.renderChildren();
11689         }
11690         return this;
11691     }
11692 });/*
11693  * Based on:
11694  * Ext JS Library 1.1.1
11695  * Copyright(c) 2006-2007, Ext JS, LLC.
11696  *
11697  * Originally Released Under LGPL - original licence link has changed is not relivant.
11698  *
11699  * Fork - LGPL
11700  * <script type="text/javascript">
11701  */
11702  
11703
11704 /**
11705  * @class Roo.tree.DefaultSelectionModel
11706  * @extends Roo.util.Observable
11707  * The default single selection for a TreePanel.
11708  * @param {Object} cfg Configuration
11709  */
11710 Roo.tree.DefaultSelectionModel = function(cfg){
11711    this.selNode = null;
11712    
11713    
11714    
11715    this.addEvents({
11716        /**
11717         * @event selectionchange
11718         * Fires when the selected node changes
11719         * @param {DefaultSelectionModel} this
11720         * @param {TreeNode} node the new selection
11721         */
11722        "selectionchange" : true,
11723
11724        /**
11725         * @event beforeselect
11726         * Fires before the selected node changes, return false to cancel the change
11727         * @param {DefaultSelectionModel} this
11728         * @param {TreeNode} node the new selection
11729         * @param {TreeNode} node the old selection
11730         */
11731        "beforeselect" : true
11732    });
11733    
11734     Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
11735 };
11736
11737 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
11738     init : function(tree){
11739         this.tree = tree;
11740         tree.getTreeEl().on("keydown", this.onKeyDown, this);
11741         tree.on("click", this.onNodeClick, this);
11742     },
11743     
11744     onNodeClick : function(node, e){
11745         if (e.ctrlKey && this.selNode == node)  {
11746             this.unselect(node);
11747             return;
11748         }
11749         this.select(node);
11750     },
11751     
11752     /**
11753      * Select a node.
11754      * @param {TreeNode} node The node to select
11755      * @return {TreeNode} The selected node
11756      */
11757     select : function(node){
11758         var last = this.selNode;
11759         if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
11760             if(last){
11761                 last.ui.onSelectedChange(false);
11762             }
11763             this.selNode = node;
11764             node.ui.onSelectedChange(true);
11765             this.fireEvent("selectionchange", this, node, last);
11766         }
11767         return node;
11768     },
11769     
11770     /**
11771      * Deselect a node.
11772      * @param {TreeNode} node The node to unselect
11773      */
11774     unselect : function(node){
11775         if(this.selNode == node){
11776             this.clearSelections();
11777         }    
11778     },
11779     
11780     /**
11781      * Clear all selections
11782      */
11783     clearSelections : function(){
11784         var n = this.selNode;
11785         if(n){
11786             n.ui.onSelectedChange(false);
11787             this.selNode = null;
11788             this.fireEvent("selectionchange", this, null);
11789         }
11790         return n;
11791     },
11792     
11793     /**
11794      * Get the selected node
11795      * @return {TreeNode} The selected node
11796      */
11797     getSelectedNode : function(){
11798         return this.selNode;    
11799     },
11800     
11801     /**
11802      * Returns true if the node is selected
11803      * @param {TreeNode} node The node to check
11804      * @return {Boolean}
11805      */
11806     isSelected : function(node){
11807         return this.selNode == node;  
11808     },
11809
11810     /**
11811      * Selects the node above the selected node in the tree, intelligently walking the nodes
11812      * @return TreeNode The new selection
11813      */
11814     selectPrevious : function(){
11815         var s = this.selNode || this.lastSelNode;
11816         if(!s){
11817             return null;
11818         }
11819         var ps = s.previousSibling;
11820         if(ps){
11821             if(!ps.isExpanded() || ps.childNodes.length < 1){
11822                 return this.select(ps);
11823             } else{
11824                 var lc = ps.lastChild;
11825                 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
11826                     lc = lc.lastChild;
11827                 }
11828                 return this.select(lc);
11829             }
11830         } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
11831             return this.select(s.parentNode);
11832         }
11833         return null;
11834     },
11835
11836     /**
11837      * Selects the node above the selected node in the tree, intelligently walking the nodes
11838      * @return TreeNode The new selection
11839      */
11840     selectNext : function(){
11841         var s = this.selNode || this.lastSelNode;
11842         if(!s){
11843             return null;
11844         }
11845         if(s.firstChild && s.isExpanded()){
11846              return this.select(s.firstChild);
11847          }else if(s.nextSibling){
11848              return this.select(s.nextSibling);
11849          }else if(s.parentNode){
11850             var newS = null;
11851             s.parentNode.bubble(function(){
11852                 if(this.nextSibling){
11853                     newS = this.getOwnerTree().selModel.select(this.nextSibling);
11854                     return false;
11855                 }
11856             });
11857             return newS;
11858          }
11859         return null;
11860     },
11861
11862     onKeyDown : function(e){
11863         var s = this.selNode || this.lastSelNode;
11864         // undesirable, but required
11865         var sm = this;
11866         if(!s){
11867             return;
11868         }
11869         var k = e.getKey();
11870         switch(k){
11871              case e.DOWN:
11872                  e.stopEvent();
11873                  this.selectNext();
11874              break;
11875              case e.UP:
11876                  e.stopEvent();
11877                  this.selectPrevious();
11878              break;
11879              case e.RIGHT:
11880                  e.preventDefault();
11881                  if(s.hasChildNodes()){
11882                      if(!s.isExpanded()){
11883                          s.expand();
11884                      }else if(s.firstChild){
11885                          this.select(s.firstChild, e);
11886                      }
11887                  }
11888              break;
11889              case e.LEFT:
11890                  e.preventDefault();
11891                  if(s.hasChildNodes() && s.isExpanded()){
11892                      s.collapse();
11893                  }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
11894                      this.select(s.parentNode, e);
11895                  }
11896              break;
11897         };
11898     }
11899 });
11900
11901 /**
11902  * @class Roo.tree.MultiSelectionModel
11903  * @extends Roo.util.Observable
11904  * Multi selection for a TreePanel.
11905  * @param {Object} cfg Configuration
11906  */
11907 Roo.tree.MultiSelectionModel = function(){
11908    this.selNodes = [];
11909    this.selMap = {};
11910    this.addEvents({
11911        /**
11912         * @event selectionchange
11913         * Fires when the selected nodes change
11914         * @param {MultiSelectionModel} this
11915         * @param {Array} nodes Array of the selected nodes
11916         */
11917        "selectionchange" : true
11918    });
11919    Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
11920    
11921 };
11922
11923 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
11924     init : function(tree){
11925         this.tree = tree;
11926         tree.getTreeEl().on("keydown", this.onKeyDown, this);
11927         tree.on("click", this.onNodeClick, this);
11928     },
11929     
11930     onNodeClick : function(node, e){
11931         this.select(node, e, e.ctrlKey);
11932     },
11933     
11934     /**
11935      * Select a node.
11936      * @param {TreeNode} node The node to select
11937      * @param {EventObject} e (optional) An event associated with the selection
11938      * @param {Boolean} keepExisting True to retain existing selections
11939      * @return {TreeNode} The selected node
11940      */
11941     select : function(node, e, keepExisting){
11942         if(keepExisting !== true){
11943             this.clearSelections(true);
11944         }
11945         if(this.isSelected(node)){
11946             this.lastSelNode = node;
11947             return node;
11948         }
11949         this.selNodes.push(node);
11950         this.selMap[node.id] = node;
11951         this.lastSelNode = node;
11952         node.ui.onSelectedChange(true);
11953         this.fireEvent("selectionchange", this, this.selNodes);
11954         return node;
11955     },
11956     
11957     /**
11958      * Deselect a node.
11959      * @param {TreeNode} node The node to unselect
11960      */
11961     unselect : function(node){
11962         if(this.selMap[node.id]){
11963             node.ui.onSelectedChange(false);
11964             var sn = this.selNodes;
11965             var index = -1;
11966             if(sn.indexOf){
11967                 index = sn.indexOf(node);
11968             }else{
11969                 for(var i = 0, len = sn.length; i < len; i++){
11970                     if(sn[i] == node){
11971                         index = i;
11972                         break;
11973                     }
11974                 }
11975             }
11976             if(index != -1){
11977                 this.selNodes.splice(index, 1);
11978             }
11979             delete this.selMap[node.id];
11980             this.fireEvent("selectionchange", this, this.selNodes);
11981         }
11982     },
11983     
11984     /**
11985      * Clear all selections
11986      */
11987     clearSelections : function(suppressEvent){
11988         var sn = this.selNodes;
11989         if(sn.length > 0){
11990             for(var i = 0, len = sn.length; i < len; i++){
11991                 sn[i].ui.onSelectedChange(false);
11992             }
11993             this.selNodes = [];
11994             this.selMap = {};
11995             if(suppressEvent !== true){
11996                 this.fireEvent("selectionchange", this, this.selNodes);
11997             }
11998         }
11999     },
12000     
12001     /**
12002      * Returns true if the node is selected
12003      * @param {TreeNode} node The node to check
12004      * @return {Boolean}
12005      */
12006     isSelected : function(node){
12007         return this.selMap[node.id] ? true : false;  
12008     },
12009     
12010     /**
12011      * Returns an array of the selected nodes
12012      * @return {Array}
12013      */
12014     getSelectedNodes : function(){
12015         return this.selNodes;    
12016     },
12017
12018     onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
12019
12020     selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
12021
12022     selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
12023 });/*
12024  * Based on:
12025  * Ext JS Library 1.1.1
12026  * Copyright(c) 2006-2007, Ext JS, LLC.
12027  *
12028  * Originally Released Under LGPL - original licence link has changed is not relivant.
12029  *
12030  * Fork - LGPL
12031  * <script type="text/javascript">
12032  */
12033  
12034 /**
12035  * @class Roo.tree.TreeNode
12036  * @extends Roo.data.Node
12037  * @cfg {String} text The text for this node
12038  * @cfg {Boolean} expanded true to start the node expanded
12039  * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
12040  * @cfg {Boolean} allowDrop false if this node cannot be drop on
12041  * @cfg {Boolean} disabled true to start the node disabled
12042  * @cfg {String} icon The path to an icon for the node. The preferred way to do this
12043  *    is to use the cls or iconCls attributes and add the icon via a CSS background image.
12044  * @cfg {String} cls A css class to be added to the node
12045  * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
12046  * @cfg {String} href URL of the link used for the node (defaults to #)
12047  * @cfg {String} hrefTarget target frame for the link
12048  * @cfg {String} qtip An Ext QuickTip for the node
12049  * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
12050  * @cfg {Boolean} singleClickExpand True for single click expand on this node
12051  * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
12052  * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
12053  * (defaults to undefined with no checkbox rendered)
12054  * @constructor
12055  * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
12056  */
12057 Roo.tree.TreeNode = function(attributes){
12058     attributes = attributes || {};
12059     if(typeof attributes == "string"){
12060         attributes = {text: attributes};
12061     }
12062     this.childrenRendered = false;
12063     this.rendered = false;
12064     Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
12065     this.expanded = attributes.expanded === true;
12066     this.isTarget = attributes.isTarget !== false;
12067     this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
12068     this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
12069
12070     /**
12071      * Read-only. The text for this node. To change it use setText().
12072      * @type String
12073      */
12074     this.text = attributes.text;
12075     /**
12076      * True if this node is disabled.
12077      * @type Boolean
12078      */
12079     this.disabled = attributes.disabled === true;
12080
12081     this.addEvents({
12082         /**
12083         * @event textchange
12084         * Fires when the text for this node is changed
12085         * @param {Node} this This node
12086         * @param {String} text The new text
12087         * @param {String} oldText The old text
12088         */
12089         "textchange" : true,
12090         /**
12091         * @event beforeexpand
12092         * Fires before this node is expanded, return false to cancel.
12093         * @param {Node} this This node
12094         * @param {Boolean} deep
12095         * @param {Boolean} anim
12096         */
12097         "beforeexpand" : true,
12098         /**
12099         * @event beforecollapse
12100         * Fires before this node is collapsed, return false to cancel.
12101         * @param {Node} this This node
12102         * @param {Boolean} deep
12103         * @param {Boolean} anim
12104         */
12105         "beforecollapse" : true,
12106         /**
12107         * @event expand
12108         * Fires when this node is expanded
12109         * @param {Node} this This node
12110         */
12111         "expand" : true,
12112         /**
12113         * @event disabledchange
12114         * Fires when the disabled status of this node changes
12115         * @param {Node} this This node
12116         * @param {Boolean} disabled
12117         */
12118         "disabledchange" : true,
12119         /**
12120         * @event collapse
12121         * Fires when this node is collapsed
12122         * @param {Node} this This node
12123         */
12124         "collapse" : true,
12125         /**
12126         * @event beforeclick
12127         * Fires before click processing. Return false to cancel the default action.
12128         * @param {Node} this This node
12129         * @param {Roo.EventObject} e The event object
12130         */
12131         "beforeclick":true,
12132         /**
12133         * @event checkchange
12134         * Fires when a node with a checkbox's checked property changes
12135         * @param {Node} this This node
12136         * @param {Boolean} checked
12137         */
12138         "checkchange":true,
12139         /**
12140         * @event click
12141         * Fires when this node is clicked
12142         * @param {Node} this This node
12143         * @param {Roo.EventObject} e The event object
12144         */
12145         "click":true,
12146         /**
12147         * @event dblclick
12148         * Fires when this node is double clicked
12149         * @param {Node} this This node
12150         * @param {Roo.EventObject} e The event object
12151         */
12152         "dblclick":true,
12153         /**
12154         * @event contextmenu
12155         * Fires when this node is right clicked
12156         * @param {Node} this This node
12157         * @param {Roo.EventObject} e The event object
12158         */
12159         "contextmenu":true,
12160         /**
12161         * @event beforechildrenrendered
12162         * Fires right before the child nodes for this node are rendered
12163         * @param {Node} this This node
12164         */
12165         "beforechildrenrendered":true
12166     });
12167
12168     var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
12169
12170     /**
12171      * Read-only. The UI for this node
12172      * @type TreeNodeUI
12173      */
12174     this.ui = new uiClass(this);
12175     
12176     // finally support items[]
12177     if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
12178         return;
12179     }
12180     
12181     
12182     Roo.each(this.attributes.items, function(c) {
12183         this.appendChild(Roo.factory(c,Roo.Tree));
12184     }, this);
12185     delete this.attributes.items;
12186     
12187     
12188     
12189 };
12190 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
12191     preventHScroll: true,
12192     /**
12193      * Returns true if this node is expanded
12194      * @return {Boolean}
12195      */
12196     isExpanded : function(){
12197         return this.expanded;
12198     },
12199
12200     /**
12201      * Returns the UI object for this node
12202      * @return {TreeNodeUI}
12203      */
12204     getUI : function(){
12205         return this.ui;
12206     },
12207
12208     // private override
12209     setFirstChild : function(node){
12210         var of = this.firstChild;
12211         Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
12212         if(this.childrenRendered && of && node != of){
12213             of.renderIndent(true, true);
12214         }
12215         if(this.rendered){
12216             this.renderIndent(true, true);
12217         }
12218     },
12219
12220     // private override
12221     setLastChild : function(node){
12222         var ol = this.lastChild;
12223         Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
12224         if(this.childrenRendered && ol && node != ol){
12225             ol.renderIndent(true, true);
12226         }
12227         if(this.rendered){
12228             this.renderIndent(true, true);
12229         }
12230     },
12231
12232     // these methods are overridden to provide lazy rendering support
12233     // private override
12234     appendChild : function()
12235     {
12236         var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
12237         if(node && this.childrenRendered){
12238             node.render();
12239         }
12240         this.ui.updateExpandIcon();
12241         return node;
12242     },
12243
12244     // private override
12245     removeChild : function(node){
12246         this.ownerTree.getSelectionModel().unselect(node);
12247         Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
12248         // if it's been rendered remove dom node
12249         if(this.childrenRendered){
12250             node.ui.remove();
12251         }
12252         if(this.childNodes.length < 1){
12253             this.collapse(false, false);
12254         }else{
12255             this.ui.updateExpandIcon();
12256         }
12257         if(!this.firstChild) {
12258             this.childrenRendered = false;
12259         }
12260         return node;
12261     },
12262
12263     // private override
12264     insertBefore : function(node, refNode){
12265         var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
12266         if(newNode && refNode && this.childrenRendered){
12267             node.render();
12268         }
12269         this.ui.updateExpandIcon();
12270         return newNode;
12271     },
12272
12273     /**
12274      * Sets the text for this node
12275      * @param {String} text
12276      */
12277     setText : function(text){
12278         var oldText = this.text;
12279         this.text = text;
12280         this.attributes.text = text;
12281         if(this.rendered){ // event without subscribing
12282             this.ui.onTextChange(this, text, oldText);
12283         }
12284         this.fireEvent("textchange", this, text, oldText);
12285     },
12286
12287     /**
12288      * Triggers selection of this node
12289      */
12290     select : function(){
12291         this.getOwnerTree().getSelectionModel().select(this);
12292     },
12293
12294     /**
12295      * Triggers deselection of this node
12296      */
12297     unselect : function(){
12298         this.getOwnerTree().getSelectionModel().unselect(this);
12299     },
12300
12301     /**
12302      * Returns true if this node is selected
12303      * @return {Boolean}
12304      */
12305     isSelected : function(){
12306         return this.getOwnerTree().getSelectionModel().isSelected(this);
12307     },
12308
12309     /**
12310      * Expand this node.
12311      * @param {Boolean} deep (optional) True to expand all children as well
12312      * @param {Boolean} anim (optional) false to cancel the default animation
12313      * @param {Function} callback (optional) A callback to be called when
12314      * expanding this node completes (does not wait for deep expand to complete).
12315      * Called with 1 parameter, this node.
12316      */
12317     expand : function(deep, anim, callback){
12318         if(!this.expanded){
12319             if(this.fireEvent("beforeexpand", this, deep, anim) === false){
12320                 return;
12321             }
12322             if(!this.childrenRendered){
12323                 this.renderChildren();
12324             }
12325             this.expanded = true;
12326             
12327             if(!this.isHiddenRoot() && (this.getOwnerTree() && this.getOwnerTree().animate && anim !== false) || anim){
12328                 this.ui.animExpand(function(){
12329                     this.fireEvent("expand", this);
12330                     if(typeof callback == "function"){
12331                         callback(this);
12332                     }
12333                     if(deep === true){
12334                         this.expandChildNodes(true);
12335                     }
12336                 }.createDelegate(this));
12337                 return;
12338             }else{
12339                 this.ui.expand();
12340                 this.fireEvent("expand", this);
12341                 if(typeof callback == "function"){
12342                     callback(this);
12343                 }
12344             }
12345         }else{
12346            if(typeof callback == "function"){
12347                callback(this);
12348            }
12349         }
12350         if(deep === true){
12351             this.expandChildNodes(true);
12352         }
12353     },
12354
12355     isHiddenRoot : function(){
12356         return this.isRoot && !this.getOwnerTree().rootVisible;
12357     },
12358
12359     /**
12360      * Collapse this node.
12361      * @param {Boolean} deep (optional) True to collapse all children as well
12362      * @param {Boolean} anim (optional) false to cancel the default animation
12363      */
12364     collapse : function(deep, anim){
12365         if(this.expanded && !this.isHiddenRoot()){
12366             if(this.fireEvent("beforecollapse", this, deep, anim) === false){
12367                 return;
12368             }
12369             this.expanded = false;
12370             if((this.getOwnerTree().animate && anim !== false) || anim){
12371                 this.ui.animCollapse(function(){
12372                     this.fireEvent("collapse", this);
12373                     if(deep === true){
12374                         this.collapseChildNodes(true);
12375                     }
12376                 }.createDelegate(this));
12377                 return;
12378             }else{
12379                 this.ui.collapse();
12380                 this.fireEvent("collapse", this);
12381             }
12382         }
12383         if(deep === true){
12384             var cs = this.childNodes;
12385             for(var i = 0, len = cs.length; i < len; i++) {
12386                 cs[i].collapse(true, false);
12387             }
12388         }
12389     },
12390
12391     // private
12392     delayedExpand : function(delay){
12393         if(!this.expandProcId){
12394             this.expandProcId = this.expand.defer(delay, this);
12395         }
12396     },
12397
12398     // private
12399     cancelExpand : function(){
12400         if(this.expandProcId){
12401             clearTimeout(this.expandProcId);
12402         }
12403         this.expandProcId = false;
12404     },
12405
12406     /**
12407      * Toggles expanded/collapsed state of the node
12408      */
12409     toggle : function(){
12410         if(this.expanded){
12411             this.collapse();
12412         }else{
12413             this.expand();
12414         }
12415     },
12416
12417     /**
12418      * Ensures all parent nodes are expanded
12419      */
12420     ensureVisible : function(callback){
12421         var tree = this.getOwnerTree();
12422         tree.expandPath(this.parentNode.getPath(), false, function(){
12423             tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
12424             Roo.callback(callback);
12425         }.createDelegate(this));
12426     },
12427
12428     /**
12429      * Expand all child nodes
12430      * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
12431      */
12432     expandChildNodes : function(deep){
12433         var cs = this.childNodes;
12434         for(var i = 0, len = cs.length; i < len; i++) {
12435                 cs[i].expand(deep);
12436         }
12437     },
12438
12439     /**
12440      * Collapse all child nodes
12441      * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
12442      */
12443     collapseChildNodes : function(deep){
12444         var cs = this.childNodes;
12445         for(var i = 0, len = cs.length; i < len; i++) {
12446                 cs[i].collapse(deep);
12447         }
12448     },
12449
12450     /**
12451      * Disables this node
12452      */
12453     disable : function(){
12454         this.disabled = true;
12455         this.unselect();
12456         if(this.rendered && this.ui.onDisableChange){ // event without subscribing
12457             this.ui.onDisableChange(this, true);
12458         }
12459         this.fireEvent("disabledchange", this, true);
12460     },
12461
12462     /**
12463      * Enables this node
12464      */
12465     enable : function(){
12466         this.disabled = false;
12467         if(this.rendered && this.ui.onDisableChange){ // event without subscribing
12468             this.ui.onDisableChange(this, false);
12469         }
12470         this.fireEvent("disabledchange", this, false);
12471     },
12472
12473     // private
12474     renderChildren : function(suppressEvent){
12475         if(suppressEvent !== false){
12476             this.fireEvent("beforechildrenrendered", this);
12477         }
12478         var cs = this.childNodes;
12479         for(var i = 0, len = cs.length; i < len; i++){
12480             cs[i].render(true);
12481         }
12482         this.childrenRendered = true;
12483     },
12484
12485     // private
12486     sort : function(fn, scope){
12487         Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
12488         if(this.childrenRendered){
12489             var cs = this.childNodes;
12490             for(var i = 0, len = cs.length; i < len; i++){
12491                 cs[i].render(true);
12492             }
12493         }
12494     },
12495
12496     // private
12497     render : function(bulkRender){
12498         this.ui.render(bulkRender);
12499         if(!this.rendered){
12500             this.rendered = true;
12501             if(this.expanded){
12502                 this.expanded = false;
12503                 this.expand(false, false);
12504             }
12505         }
12506     },
12507
12508     // private
12509     renderIndent : function(deep, refresh){
12510         if(refresh){
12511             this.ui.childIndent = null;
12512         }
12513         this.ui.renderIndent();
12514         if(deep === true && this.childrenRendered){
12515             var cs = this.childNodes;
12516             for(var i = 0, len = cs.length; i < len; i++){
12517                 cs[i].renderIndent(true, refresh);
12518             }
12519         }
12520     }
12521 });/*
12522  * Based on:
12523  * Ext JS Library 1.1.1
12524  * Copyright(c) 2006-2007, Ext JS, LLC.
12525  *
12526  * Originally Released Under LGPL - original licence link has changed is not relivant.
12527  *
12528  * Fork - LGPL
12529  * <script type="text/javascript">
12530  */
12531  
12532 /**
12533  * @class Roo.tree.AsyncTreeNode
12534  * @extends Roo.tree.TreeNode
12535  * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
12536  * @constructor
12537  * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node 
12538  */
12539  Roo.tree.AsyncTreeNode = function(config){
12540     this.loaded = false;
12541     this.loading = false;
12542     Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
12543     /**
12544     * @event beforeload
12545     * Fires before this node is loaded, return false to cancel
12546     * @param {Node} this This node
12547     */
12548     this.addEvents({'beforeload':true, 'load': true});
12549     /**
12550     * @event load
12551     * Fires when this node is loaded
12552     * @param {Node} this This node
12553     */
12554     /**
12555      * The loader used by this node (defaults to using the tree's defined loader)
12556      * @type TreeLoader
12557      * @property loader
12558      */
12559 };
12560 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
12561     expand : function(deep, anim, callback){
12562         if(this.loading){ // if an async load is already running, waiting til it's done
12563             var timer;
12564             var f = function(){
12565                 if(!this.loading){ // done loading
12566                     clearInterval(timer);
12567                     this.expand(deep, anim, callback);
12568                 }
12569             }.createDelegate(this);
12570             timer = setInterval(f, 200);
12571             return;
12572         }
12573         if(!this.loaded){
12574             if(this.fireEvent("beforeload", this) === false){
12575                 return;
12576             }
12577             this.loading = true;
12578             this.ui.beforeLoad(this);
12579             var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
12580             if(loader){
12581                 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
12582                 return;
12583             }
12584         }
12585         Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
12586     },
12587     
12588     /**
12589      * Returns true if this node is currently loading
12590      * @return {Boolean}
12591      */
12592     isLoading : function(){
12593         return this.loading;  
12594     },
12595     
12596     loadComplete : function(deep, anim, callback){
12597         this.loading = false;
12598         this.loaded = true;
12599         this.ui.afterLoad(this);
12600         this.fireEvent("load", this);
12601         this.expand(deep, anim, callback);
12602     },
12603     
12604     /**
12605      * Returns true if this node has been loaded
12606      * @return {Boolean}
12607      */
12608     isLoaded : function(){
12609         return this.loaded;
12610     },
12611     
12612     hasChildNodes : function(){
12613         if(!this.isLeaf() && !this.loaded){
12614             return true;
12615         }else{
12616             return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
12617         }
12618     },
12619
12620     /**
12621      * Trigger a reload for this node
12622      * @param {Function} callback
12623      */
12624     reload : function(callback){
12625         this.collapse(false, false);
12626         while(this.firstChild){
12627             this.removeChild(this.firstChild);
12628         }
12629         this.childrenRendered = false;
12630         this.loaded = false;
12631         if(this.isHiddenRoot()){
12632             this.expanded = false;
12633         }
12634         this.expand(false, false, callback);
12635     }
12636 });/*
12637  * Based on:
12638  * Ext JS Library 1.1.1
12639  * Copyright(c) 2006-2007, Ext JS, LLC.
12640  *
12641  * Originally Released Under LGPL - original licence link has changed is not relivant.
12642  *
12643  * Fork - LGPL
12644  * <script type="text/javascript">
12645  */
12646  
12647 /**
12648  * @class Roo.tree.TreeNodeUI
12649  * @constructor
12650  * @param {Object} node The node to render
12651  * The TreeNode UI implementation is separate from the
12652  * tree implementation. Unless you are customizing the tree UI,
12653  * you should never have to use this directly.
12654  */
12655 Roo.tree.TreeNodeUI = function(node){
12656     this.node = node;
12657     this.rendered = false;
12658     this.animating = false;
12659     this.emptyIcon = Roo.BLANK_IMAGE_URL;
12660 };
12661
12662 Roo.tree.TreeNodeUI.prototype = {
12663     removeChild : function(node){
12664         if(this.rendered){
12665             this.ctNode.removeChild(node.ui.getEl());
12666         }
12667     },
12668
12669     beforeLoad : function(){
12670          this.addClass("x-tree-node-loading");
12671     },
12672
12673     afterLoad : function(){
12674          this.removeClass("x-tree-node-loading");
12675     },
12676
12677     onTextChange : function(node, text, oldText){
12678         if(this.rendered){
12679             this.textNode.innerHTML = text;
12680         }
12681     },
12682
12683     onDisableChange : function(node, state){
12684         this.disabled = state;
12685         if(state){
12686             this.addClass("x-tree-node-disabled");
12687         }else{
12688             this.removeClass("x-tree-node-disabled");
12689         }
12690     },
12691
12692     onSelectedChange : function(state){
12693         if(state){
12694             this.focus();
12695             this.addClass("x-tree-selected");
12696         }else{
12697             //this.blur();
12698             this.removeClass("x-tree-selected");
12699         }
12700     },
12701
12702     onMove : function(tree, node, oldParent, newParent, index, refNode){
12703         this.childIndent = null;
12704         if(this.rendered){
12705             var targetNode = newParent.ui.getContainer();
12706             if(!targetNode){//target not rendered
12707                 this.holder = document.createElement("div");
12708                 this.holder.appendChild(this.wrap);
12709                 return;
12710             }
12711             var insertBefore = refNode ? refNode.ui.getEl() : null;
12712             if(insertBefore){
12713                 targetNode.insertBefore(this.wrap, insertBefore);
12714             }else{
12715                 targetNode.appendChild(this.wrap);
12716             }
12717             this.node.renderIndent(true);
12718         }
12719     },
12720
12721     addClass : function(cls){
12722         if(this.elNode){
12723             Roo.fly(this.elNode).addClass(cls);
12724         }
12725     },
12726
12727     removeClass : function(cls){
12728         if(this.elNode){
12729             Roo.fly(this.elNode).removeClass(cls);
12730         }
12731     },
12732
12733     remove : function(){
12734         if(this.rendered){
12735             this.holder = document.createElement("div");
12736             this.holder.appendChild(this.wrap);
12737         }
12738     },
12739
12740     fireEvent : function(){
12741         return this.node.fireEvent.apply(this.node, arguments);
12742     },
12743
12744     initEvents : function(){
12745         this.node.on("move", this.onMove, this);
12746         var E = Roo.EventManager;
12747         var a = this.anchor;
12748
12749         var el = Roo.fly(a, '_treeui');
12750
12751         if(Roo.isOpera){ // opera render bug ignores the CSS
12752             el.setStyle("text-decoration", "none");
12753         }
12754
12755         el.on("click", this.onClick, this);
12756         el.on("dblclick", this.onDblClick, this);
12757
12758         if(this.checkbox){
12759             Roo.EventManager.on(this.checkbox,
12760                     Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
12761         }
12762
12763         el.on("contextmenu", this.onContextMenu, this);
12764
12765         var icon = Roo.fly(this.iconNode);
12766         icon.on("click", this.onClick, this);
12767         icon.on("dblclick", this.onDblClick, this);
12768         icon.on("contextmenu", this.onContextMenu, this);
12769         E.on(this.ecNode, "click", this.ecClick, this, true);
12770
12771         if(this.node.disabled){
12772             this.addClass("x-tree-node-disabled");
12773         }
12774         if(this.node.hidden){
12775             this.addClass("x-tree-node-disabled");
12776         }
12777         var ot = this.node.getOwnerTree();
12778         var dd = ot ? (ot.enableDD || ot.enableDrag || ot.enableDrop) : false;
12779         if(dd && (!this.node.isRoot || ot.rootVisible)){
12780             Roo.dd.Registry.register(this.elNode, {
12781                 node: this.node,
12782                 handles: this.getDDHandles(),
12783                 isHandle: false
12784             });
12785         }
12786     },
12787
12788     getDDHandles : function(){
12789         return [this.iconNode, this.textNode];
12790     },
12791
12792     hide : function(){
12793         if(this.rendered){
12794             this.wrap.style.display = "none";
12795         }
12796     },
12797
12798     show : function(){
12799         if(this.rendered){
12800             this.wrap.style.display = "";
12801         }
12802     },
12803
12804     onContextMenu : function(e){
12805         if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
12806             e.preventDefault();
12807             this.focus();
12808             this.fireEvent("contextmenu", this.node, e);
12809         }
12810     },
12811
12812     onClick : function(e){
12813         if(this.dropping){
12814             e.stopEvent();
12815             return;
12816         }
12817         if(this.fireEvent("beforeclick", this.node, e) !== false){
12818             if(!this.disabled && this.node.attributes.href){
12819                 this.fireEvent("click", this.node, e);
12820                 return;
12821             }
12822             e.preventDefault();
12823             if(this.disabled){
12824                 return;
12825             }
12826
12827             if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
12828                 this.node.toggle();
12829             }
12830
12831             this.fireEvent("click", this.node, e);
12832         }else{
12833             e.stopEvent();
12834         }
12835     },
12836
12837     onDblClick : function(e){
12838         e.preventDefault();
12839         if(this.disabled){
12840             return;
12841         }
12842         if(this.checkbox){
12843             this.toggleCheck();
12844         }
12845         if(!this.animating && this.node.hasChildNodes()){
12846             this.node.toggle();
12847         }
12848         this.fireEvent("dblclick", this.node, e);
12849     },
12850
12851     onCheckChange : function(){
12852         var checked = this.checkbox.checked;
12853         this.node.attributes.checked = checked;
12854         this.fireEvent('checkchange', this.node, checked);
12855     },
12856
12857     ecClick : function(e){
12858         if(!this.animating && this.node.hasChildNodes()){
12859             this.node.toggle();
12860         }
12861     },
12862
12863     startDrop : function(){
12864         this.dropping = true;
12865     },
12866
12867     // delayed drop so the click event doesn't get fired on a drop
12868     endDrop : function(){
12869        setTimeout(function(){
12870            this.dropping = false;
12871        }.createDelegate(this), 50);
12872     },
12873
12874     expand : function(){
12875         this.updateExpandIcon();
12876         this.ctNode.style.display = "";
12877     },
12878
12879     focus : function(){
12880         if(!this.node.preventHScroll){
12881             try{this.anchor.focus();
12882             }catch(e){}
12883         }else if(!Roo.isIE){
12884             try{
12885                 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
12886                 var l = noscroll.scrollLeft;
12887                 this.anchor.focus();
12888                 noscroll.scrollLeft = l;
12889             }catch(e){}
12890         }
12891     },
12892
12893     toggleCheck : function(value){
12894         var cb = this.checkbox;
12895         if(cb){
12896             cb.checked = (value === undefined ? !cb.checked : value);
12897         }
12898     },
12899
12900     blur : function(){
12901         try{
12902             this.anchor.blur();
12903         }catch(e){}
12904     },
12905
12906     animExpand : function(callback){
12907         var ct = Roo.get(this.ctNode);
12908         ct.stopFx();
12909         if(!this.node.hasChildNodes()){
12910             this.updateExpandIcon();
12911             this.ctNode.style.display = "";
12912             Roo.callback(callback);
12913             return;
12914         }
12915         this.animating = true;
12916         this.updateExpandIcon();
12917
12918         ct.slideIn('t', {
12919            callback : function(){
12920                this.animating = false;
12921                Roo.callback(callback);
12922             },
12923             scope: this,
12924             duration: this.node.ownerTree.duration || .25
12925         });
12926     },
12927
12928     highlight : function(){
12929         var tree = this.node.getOwnerTree();
12930         Roo.fly(this.wrap).highlight(
12931             tree.hlColor || "C3DAF9",
12932             {endColor: tree.hlBaseColor}
12933         );
12934     },
12935
12936     collapse : function(){
12937         this.updateExpandIcon();
12938         this.ctNode.style.display = "none";
12939     },
12940
12941     animCollapse : function(callback){
12942         var ct = Roo.get(this.ctNode);
12943         ct.enableDisplayMode('block');
12944         ct.stopFx();
12945
12946         this.animating = true;
12947         this.updateExpandIcon();
12948
12949         ct.slideOut('t', {
12950             callback : function(){
12951                this.animating = false;
12952                Roo.callback(callback);
12953             },
12954             scope: this,
12955             duration: this.node.ownerTree.duration || .25
12956         });
12957     },
12958
12959     getContainer : function(){
12960         return this.ctNode;
12961     },
12962
12963     getEl : function(){
12964         return this.wrap;
12965     },
12966
12967     appendDDGhost : function(ghostNode){
12968         ghostNode.appendChild(this.elNode.cloneNode(true));
12969     },
12970
12971     getDDRepairXY : function(){
12972         return Roo.lib.Dom.getXY(this.iconNode);
12973     },
12974
12975     onRender : function(){
12976         this.render();
12977     },
12978
12979     render : function(bulkRender){
12980         var n = this.node, a = n.attributes;
12981         var targetNode = n.parentNode ?
12982               n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
12983
12984         if(!this.rendered){
12985             this.rendered = true;
12986
12987             this.renderElements(n, a, targetNode, bulkRender);
12988
12989             if(a.qtip){
12990                if(this.textNode.setAttributeNS){
12991                    this.textNode.setAttributeNS("ext", "qtip", a.qtip);
12992                    if(a.qtipTitle){
12993                        this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
12994                    }
12995                }else{
12996                    this.textNode.setAttribute("ext:qtip", a.qtip);
12997                    if(a.qtipTitle){
12998                        this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
12999                    }
13000                }
13001             }else if(a.qtipCfg){
13002                 a.qtipCfg.target = Roo.id(this.textNode);
13003                 Roo.QuickTips.register(a.qtipCfg);
13004             }
13005             this.initEvents();
13006             if(!this.node.expanded){
13007                 this.updateExpandIcon();
13008             }
13009         }else{
13010             if(bulkRender === true) {
13011                 targetNode.appendChild(this.wrap);
13012             }
13013         }
13014     },
13015
13016     renderElements : function(n, a, targetNode, bulkRender)
13017     {
13018         // add some indent caching, this helps performance when rendering a large tree
13019         this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
13020         var t = n.getOwnerTree();
13021         var txt = t && t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
13022         if (typeof(n.attributes.html) != 'undefined') {
13023             txt = n.attributes.html;
13024         }
13025         var tip = t && t.rendererTip ? t.rendererTip(n.attributes) : txt;
13026         var cb = typeof a.checked == 'boolean';
13027         var href = a.href ? a.href : Roo.isGecko ? "" : "#";
13028         var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
13029             '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
13030             '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
13031             '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
13032             cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
13033             '<a hidefocus="on" href="',href,'" tabIndex="1" ',
13034              a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", 
13035                 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
13036             '<ul class="x-tree-node-ct" style="display:none;"></ul>',
13037             "</li>"];
13038
13039         if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
13040             this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
13041                                 n.nextSibling.ui.getEl(), buf.join(""));
13042         }else{
13043             this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
13044         }
13045
13046         this.elNode = this.wrap.childNodes[0];
13047         this.ctNode = this.wrap.childNodes[1];
13048         var cs = this.elNode.childNodes;
13049         this.indentNode = cs[0];
13050         this.ecNode = cs[1];
13051         this.iconNode = cs[2];
13052         var index = 3;
13053         if(cb){
13054             this.checkbox = cs[3];
13055             index++;
13056         }
13057         this.anchor = cs[index];
13058         this.textNode = cs[index].firstChild;
13059     },
13060
13061     getAnchor : function(){
13062         return this.anchor;
13063     },
13064
13065     getTextEl : function(){
13066         return this.textNode;
13067     },
13068
13069     getIconEl : function(){
13070         return this.iconNode;
13071     },
13072
13073     isChecked : function(){
13074         return this.checkbox ? this.checkbox.checked : false;
13075     },
13076
13077     updateExpandIcon : function(){
13078         if(this.rendered){
13079             var n = this.node, c1, c2;
13080             var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
13081             var hasChild = n.hasChildNodes();
13082             if(hasChild){
13083                 if(n.expanded){
13084                     cls += "-minus";
13085                     c1 = "x-tree-node-collapsed";
13086                     c2 = "x-tree-node-expanded";
13087                 }else{
13088                     cls += "-plus";
13089                     c1 = "x-tree-node-expanded";
13090                     c2 = "x-tree-node-collapsed";
13091                 }
13092                 if(this.wasLeaf){
13093                     this.removeClass("x-tree-node-leaf");
13094                     this.wasLeaf = false;
13095                 }
13096                 if(this.c1 != c1 || this.c2 != c2){
13097                     Roo.fly(this.elNode).replaceClass(c1, c2);
13098                     this.c1 = c1; this.c2 = c2;
13099                 }
13100             }else{
13101                 // this changes non-leafs into leafs if they have no children.
13102                 // it's not very rational behaviour..
13103                 
13104                 if(!this.wasLeaf && this.node.leaf){
13105                     Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
13106                     delete this.c1;
13107                     delete this.c2;
13108                     this.wasLeaf = true;
13109                 }
13110             }
13111             var ecc = "x-tree-ec-icon "+cls;
13112             if(this.ecc != ecc){
13113                 this.ecNode.className = ecc;
13114                 this.ecc = ecc;
13115             }
13116         }
13117     },
13118
13119     getChildIndent : function(){
13120         if(!this.childIndent){
13121             var buf = [];
13122             var p = this.node;
13123             while(p){
13124                 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
13125                     if(!p.isLast()) {
13126                         buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
13127                     } else {
13128                         buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
13129                     }
13130                 }
13131                 p = p.parentNode;
13132             }
13133             this.childIndent = buf.join("");
13134         }
13135         return this.childIndent;
13136     },
13137
13138     renderIndent : function(){
13139         if(this.rendered){
13140             var indent = "";
13141             var p = this.node.parentNode;
13142             if(p){
13143                 indent = p.ui.getChildIndent();
13144             }
13145             if(this.indentMarkup != indent){ // don't rerender if not required
13146                 this.indentNode.innerHTML = indent;
13147                 this.indentMarkup = indent;
13148             }
13149             this.updateExpandIcon();
13150         }
13151     }
13152 };
13153
13154 Roo.tree.RootTreeNodeUI = function(){
13155     Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
13156 };
13157 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
13158     render : function(){
13159         if(!this.rendered){
13160             var targetNode = this.node.ownerTree.innerCt.dom;
13161             this.node.expanded = true;
13162             targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
13163             this.wrap = this.ctNode = targetNode.firstChild;
13164         }
13165     },
13166     collapse : function(){
13167     },
13168     expand : function(){
13169     }
13170 });/*
13171  * Based on:
13172  * Ext JS Library 1.1.1
13173  * Copyright(c) 2006-2007, Ext JS, LLC.
13174  *
13175  * Originally Released Under LGPL - original licence link has changed is not relivant.
13176  *
13177  * Fork - LGPL
13178  * <script type="text/javascript">
13179  */
13180 /**
13181  * @class Roo.tree.TreeLoader
13182  * @extends Roo.util.Observable
13183  * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
13184  * nodes from a specified URL. The response must be a javascript Array definition
13185  * who's elements are node definition objects. eg:
13186  * <pre><code>
13187 {  success : true,
13188    data :      [
13189    
13190     { 'id': 1, 'text': 'A folder Node', 'leaf': false },
13191     { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
13192     ]
13193 }
13194
13195
13196 </code></pre>
13197  * <br><br>
13198  * The old style respose with just an array is still supported, but not recommended.
13199  * <br><br>
13200  *
13201  * A server request is sent, and child nodes are loaded only when a node is expanded.
13202  * The loading node's id is passed to the server under the parameter name "node" to
13203  * enable the server to produce the correct child nodes.
13204  * <br><br>
13205  * To pass extra parameters, an event handler may be attached to the "beforeload"
13206  * event, and the parameters specified in the TreeLoader's baseParams property:
13207  * <pre><code>
13208     myTreeLoader.on("beforeload", function(treeLoader, node) {
13209         this.baseParams.category = node.attributes.category;
13210     }, this);
13211     
13212 </code></pre>
13213  *
13214  * This would pass an HTTP parameter called "category" to the server containing
13215  * the value of the Node's "category" attribute.
13216  * @constructor
13217  * Creates a new Treeloader.
13218  * @param {Object} config A config object containing config properties.
13219  */
13220 Roo.tree.TreeLoader = function(config){
13221     this.baseParams = {};
13222     this.requestMethod = "POST";
13223     Roo.apply(this, config);
13224
13225     this.addEvents({
13226     
13227         /**
13228          * @event beforeload
13229          * Fires before a network request is made to retrieve the Json text which specifies a node's children.
13230          * @param {Object} This TreeLoader object.
13231          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
13232          * @param {Object} callback The callback function specified in the {@link #load} call.
13233          */
13234         beforeload : true,
13235         /**
13236          * @event load
13237          * Fires when the node has been successfuly loaded.
13238          * @param {Object} This TreeLoader object.
13239          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
13240          * @param {Object} response The response object containing the data from the server.
13241          */
13242         load : true,
13243         /**
13244          * @event loadexception
13245          * Fires if the network request failed.
13246          * @param {Object} This TreeLoader object.
13247          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
13248          * @param {Object} response The response object containing the data from the server.
13249          */
13250         loadexception : true,
13251         /**
13252          * @event create
13253          * Fires before a node is created, enabling you to return custom Node types 
13254          * @param {Object} This TreeLoader object.
13255          * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
13256          */
13257         create : true
13258     });
13259
13260     Roo.tree.TreeLoader.superclass.constructor.call(this);
13261 };
13262
13263 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
13264     /**
13265     * @cfg {String} dataUrl The URL from which to request a Json string which
13266     * specifies an array of node definition object representing the child nodes
13267     * to be loaded.
13268     */
13269     /**
13270     * @cfg {String} requestMethod either GET or POST
13271     * defaults to POST (due to BC)
13272     * to be loaded.
13273     */
13274     /**
13275     * @cfg {Object} baseParams (optional) An object containing properties which
13276     * specify HTTP parameters to be passed to each request for child nodes.
13277     */
13278     /**
13279     * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
13280     * created by this loader. If the attributes sent by the server have an attribute in this object,
13281     * they take priority.
13282     */
13283     /**
13284     * @cfg {Object} uiProviders (optional) An object containing properties which
13285     * 
13286     * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
13287     * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
13288     * <i>uiProvider</i> attribute of a returned child node is a string rather
13289     * than a reference to a TreeNodeUI implementation, this that string value
13290     * is used as a property name in the uiProviders object. You can define the provider named
13291     * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
13292     */
13293     uiProviders : {},
13294
13295     /**
13296     * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
13297     * child nodes before loading.
13298     */
13299     clearOnLoad : true,
13300
13301     /**
13302     * @cfg {String} root (optional) Default to false. Use this to read data from an object 
13303     * property on loading, rather than expecting an array. (eg. more compatible to a standard
13304     * Grid query { data : [ .....] }
13305     */
13306     
13307     root : false,
13308      /**
13309     * @cfg {String} queryParam (optional) 
13310     * Name of the query as it will be passed on the querystring (defaults to 'node')
13311     * eg. the request will be ?node=[id]
13312     */
13313     
13314     
13315     queryParam: false,
13316     
13317     /**
13318      * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
13319      * This is called automatically when a node is expanded, but may be used to reload
13320      * a node (or append new children if the {@link #clearOnLoad} option is false.)
13321      * @param {Roo.tree.TreeNode} node
13322      * @param {Function} callback
13323      */
13324     load : function(node, callback){
13325         if(this.clearOnLoad){
13326             while(node.firstChild){
13327                 node.removeChild(node.firstChild);
13328             }
13329         }
13330         if(node.attributes.children){ // preloaded json children
13331             var cs = node.attributes.children;
13332             for(var i = 0, len = cs.length; i < len; i++){
13333                 node.appendChild(this.createNode(cs[i]));
13334             }
13335             if(typeof callback == "function"){
13336                 callback();
13337             }
13338         }else if(this.dataUrl){
13339             this.requestData(node, callback);
13340         }
13341     },
13342
13343     getParams: function(node){
13344         var buf = [], bp = this.baseParams;
13345         for(var key in bp){
13346             if(typeof bp[key] != "function"){
13347                 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
13348             }
13349         }
13350         var n = this.queryParam === false ? 'node' : this.queryParam;
13351         buf.push(n + "=", encodeURIComponent(node.id));
13352         return buf.join("");
13353     },
13354
13355     requestData : function(node, callback){
13356         if(this.fireEvent("beforeload", this, node, callback) !== false){
13357             this.transId = Roo.Ajax.request({
13358                 method:this.requestMethod,
13359                 url: this.dataUrl||this.url,
13360                 success: this.handleResponse,
13361                 failure: this.handleFailure,
13362                 scope: this,
13363                 argument: {callback: callback, node: node},
13364                 params: this.getParams(node)
13365             });
13366         }else{
13367             // if the load is cancelled, make sure we notify
13368             // the node that we are done
13369             if(typeof callback == "function"){
13370                 callback();
13371             }
13372         }
13373     },
13374
13375     isLoading : function(){
13376         return this.transId ? true : false;
13377     },
13378
13379     abort : function(){
13380         if(this.isLoading()){
13381             Roo.Ajax.abort(this.transId);
13382         }
13383     },
13384
13385     // private
13386     createNode : function(attr)
13387     {
13388         // apply baseAttrs, nice idea Corey!
13389         if(this.baseAttrs){
13390             Roo.applyIf(attr, this.baseAttrs);
13391         }
13392         if(this.applyLoader !== false){
13393             attr.loader = this;
13394         }
13395         // uiProvider = depreciated..
13396         
13397         if(typeof(attr.uiProvider) == 'string'){
13398            attr.uiProvider = this.uiProviders[attr.uiProvider] || 
13399                 /**  eval:var:attr */ eval(attr.uiProvider);
13400         }
13401         if(typeof(this.uiProviders['default']) != 'undefined') {
13402             attr.uiProvider = this.uiProviders['default'];
13403         }
13404         
13405         this.fireEvent('create', this, attr);
13406         
13407         attr.leaf  = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
13408         return(attr.leaf ?
13409                         new Roo.tree.TreeNode(attr) :
13410                         new Roo.tree.AsyncTreeNode(attr));
13411     },
13412
13413     processResponse : function(response, node, callback)
13414     {
13415         var json = response.responseText;
13416         try {
13417             
13418             var o = Roo.decode(json);
13419             
13420             if (this.root === false && typeof(o.success) != undefined) {
13421                 this.root = 'data'; // the default behaviour for list like data..
13422                 }
13423                 
13424             if (this.root !== false &&  !o.success) {
13425                 // it's a failure condition.
13426                 var a = response.argument;
13427                 this.fireEvent("loadexception", this, a.node, response);
13428                 Roo.log("Load failed - should have a handler really");
13429                 return;
13430             }
13431             
13432             
13433             
13434             if (this.root !== false) {
13435                  o = o[this.root];
13436             }
13437             
13438             for(var i = 0, len = o.length; i < len; i++){
13439                 var n = this.createNode(o[i]);
13440                 if(n){
13441                     node.appendChild(n);
13442                 }
13443             }
13444             if(typeof callback == "function"){
13445                 callback(this, node);
13446             }
13447         }catch(e){
13448             this.handleFailure(response);
13449         }
13450     },
13451
13452     handleResponse : function(response){
13453         this.transId = false;
13454         var a = response.argument;
13455         this.processResponse(response, a.node, a.callback);
13456         this.fireEvent("load", this, a.node, response);
13457     },
13458
13459     handleFailure : function(response)
13460     {
13461         // should handle failure better..
13462         this.transId = false;
13463         var a = response.argument;
13464         this.fireEvent("loadexception", this, a.node, response);
13465         if(typeof a.callback == "function"){
13466             a.callback(this, a.node);
13467         }
13468     }
13469 });/*
13470  * Based on:
13471  * Ext JS Library 1.1.1
13472  * Copyright(c) 2006-2007, Ext JS, LLC.
13473  *
13474  * Originally Released Under LGPL - original licence link has changed is not relivant.
13475  *
13476  * Fork - LGPL
13477  * <script type="text/javascript">
13478  */
13479
13480 /**
13481 * @class Roo.tree.TreeFilter
13482 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
13483 * @param {TreePanel} tree
13484 * @param {Object} config (optional)
13485  */
13486 Roo.tree.TreeFilter = function(tree, config){
13487     this.tree = tree;
13488     this.filtered = {};
13489     Roo.apply(this, config);
13490 };
13491
13492 Roo.tree.TreeFilter.prototype = {
13493     clearBlank:false,
13494     reverse:false,
13495     autoClear:false,
13496     remove:false,
13497
13498      /**
13499      * Filter the data by a specific attribute.
13500      * @param {String/RegExp} value Either string that the attribute value
13501      * should start with or a RegExp to test against the attribute
13502      * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
13503      * @param {TreeNode} startNode (optional) The node to start the filter at.
13504      */
13505     filter : function(value, attr, startNode){
13506         attr = attr || "text";
13507         var f;
13508         if(typeof value == "string"){
13509             var vlen = value.length;
13510             // auto clear empty filter
13511             if(vlen == 0 && this.clearBlank){
13512                 this.clear();
13513                 return;
13514             }
13515             value = value.toLowerCase();
13516             f = function(n){
13517                 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
13518             };
13519         }else if(value.exec){ // regex?
13520             f = function(n){
13521                 return value.test(n.attributes[attr]);
13522             };
13523         }else{
13524             throw 'Illegal filter type, must be string or regex';
13525         }
13526         this.filterBy(f, null, startNode);
13527         },
13528
13529     /**
13530      * Filter by a function. The passed function will be called with each
13531      * node in the tree (or from the startNode). If the function returns true, the node is kept
13532      * otherwise it is filtered. If a node is filtered, its children are also filtered.
13533      * @param {Function} fn The filter function
13534      * @param {Object} scope (optional) The scope of the function (defaults to the current node)
13535      */
13536     filterBy : function(fn, scope, startNode){
13537         startNode = startNode || this.tree.root;
13538         if(this.autoClear){
13539             this.clear();
13540         }
13541         var af = this.filtered, rv = this.reverse;
13542         var f = function(n){
13543             if(n == startNode){
13544                 return true;
13545             }
13546             if(af[n.id]){
13547                 return false;
13548             }
13549             var m = fn.call(scope || n, n);
13550             if(!m || rv){
13551                 af[n.id] = n;
13552                 n.ui.hide();
13553                 return false;
13554             }
13555             return true;
13556         };
13557         startNode.cascade(f);
13558         if(this.remove){
13559            for(var id in af){
13560                if(typeof id != "function"){
13561                    var n = af[id];
13562                    if(n && n.parentNode){
13563                        n.parentNode.removeChild(n);
13564                    }
13565                }
13566            }
13567         }
13568     },
13569
13570     /**
13571      * Clears the current filter. Note: with the "remove" option
13572      * set a filter cannot be cleared.
13573      */
13574     clear : function(){
13575         var t = this.tree;
13576         var af = this.filtered;
13577         for(var id in af){
13578             if(typeof id != "function"){
13579                 var n = af[id];
13580                 if(n){
13581                     n.ui.show();
13582                 }
13583             }
13584         }
13585         this.filtered = {};
13586     }
13587 };
13588 /*
13589  * Based on:
13590  * Ext JS Library 1.1.1
13591  * Copyright(c) 2006-2007, Ext JS, LLC.
13592  *
13593  * Originally Released Under LGPL - original licence link has changed is not relivant.
13594  *
13595  * Fork - LGPL
13596  * <script type="text/javascript">
13597  */
13598  
13599
13600 /**
13601  * @class Roo.tree.TreeSorter
13602  * Provides sorting of nodes in a TreePanel
13603  * 
13604  * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
13605  * @cfg {String} property The named attribute on the node to sort by (defaults to text)
13606  * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
13607  * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
13608  * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
13609  * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
13610  * @constructor
13611  * @param {TreePanel} tree
13612  * @param {Object} config
13613  */
13614 Roo.tree.TreeSorter = function(tree, config){
13615     Roo.apply(this, config);
13616     tree.on("beforechildrenrendered", this.doSort, this);
13617     tree.on("append", this.updateSort, this);
13618     tree.on("insert", this.updateSort, this);
13619     
13620     var dsc = this.dir && this.dir.toLowerCase() == "desc";
13621     var p = this.property || "text";
13622     var sortType = this.sortType;
13623     var fs = this.folderSort;
13624     var cs = this.caseSensitive === true;
13625     var leafAttr = this.leafAttr || 'leaf';
13626
13627     this.sortFn = function(n1, n2){
13628         if(fs){
13629             if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
13630                 return 1;
13631             }
13632             if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
13633                 return -1;
13634             }
13635         }
13636         var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
13637         var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
13638         if(v1 < v2){
13639                         return dsc ? +1 : -1;
13640                 }else if(v1 > v2){
13641                         return dsc ? -1 : +1;
13642         }else{
13643                 return 0;
13644         }
13645     };
13646 };
13647
13648 Roo.tree.TreeSorter.prototype = {
13649     doSort : function(node){
13650         node.sort(this.sortFn);
13651     },
13652     
13653     compareNodes : function(n1, n2){
13654         return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
13655     },
13656     
13657     updateSort : function(tree, node){
13658         if(node.childrenRendered){
13659             this.doSort.defer(1, this, [node]);
13660         }
13661     }
13662 };/*
13663  * Based on:
13664  * Ext JS Library 1.1.1
13665  * Copyright(c) 2006-2007, Ext JS, LLC.
13666  *
13667  * Originally Released Under LGPL - original licence link has changed is not relivant.
13668  *
13669  * Fork - LGPL
13670  * <script type="text/javascript">
13671  */
13672
13673 if(Roo.dd.DropZone){
13674     
13675 Roo.tree.TreeDropZone = function(tree, config){
13676     this.allowParentInsert = false;
13677     this.allowContainerDrop = false;
13678     this.appendOnly = false;
13679     Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
13680     this.tree = tree;
13681     this.lastInsertClass = "x-tree-no-status";
13682     this.dragOverData = {};
13683 };
13684
13685 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
13686     ddGroup : "TreeDD",
13687     scroll:  true,
13688     
13689     expandDelay : 1000,
13690     
13691     expandNode : function(node){
13692         if(node.hasChildNodes() && !node.isExpanded()){
13693             node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
13694         }
13695     },
13696     
13697     queueExpand : function(node){
13698         this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
13699     },
13700     
13701     cancelExpand : function(){
13702         if(this.expandProcId){
13703             clearTimeout(this.expandProcId);
13704             this.expandProcId = false;
13705         }
13706     },
13707     
13708     isValidDropPoint : function(n, pt, dd, e, data){
13709         if(!n || !data){ return false; }
13710         var targetNode = n.node;
13711         var dropNode = data.node;
13712         // default drop rules
13713         if(!(targetNode && targetNode.isTarget && pt)){
13714             return false;
13715         }
13716         if(pt == "append" && targetNode.allowChildren === false){
13717             return false;
13718         }
13719         if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
13720             return false;
13721         }
13722         if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
13723             return false;
13724         }
13725         // reuse the object
13726         var overEvent = this.dragOverData;
13727         overEvent.tree = this.tree;
13728         overEvent.target = targetNode;
13729         overEvent.data = data;
13730         overEvent.point = pt;
13731         overEvent.source = dd;
13732         overEvent.rawEvent = e;
13733         overEvent.dropNode = dropNode;
13734         overEvent.cancel = false;  
13735         var result = this.tree.fireEvent("nodedragover", overEvent);
13736         return overEvent.cancel === false && result !== false;
13737     },
13738     
13739     getDropPoint : function(e, n, dd)
13740     {
13741         var tn = n.node;
13742         if(tn.isRoot){
13743             return tn.allowChildren !== false ? "append" : false; // always append for root
13744         }
13745         var dragEl = n.ddel;
13746         var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
13747         var y = Roo.lib.Event.getPageY(e);
13748         //var noAppend = tn.allowChildren === false || tn.isLeaf();
13749         
13750         // we may drop nodes anywhere, as long as allowChildren has not been set to false..
13751         var noAppend = tn.allowChildren === false;
13752         if(this.appendOnly || tn.parentNode.allowChildren === false){
13753             return noAppend ? false : "append";
13754         }
13755         var noBelow = false;
13756         if(!this.allowParentInsert){
13757             noBelow = tn.hasChildNodes() && tn.isExpanded();
13758         }
13759         var q = (b - t) / (noAppend ? 2 : 3);
13760         if(y >= t && y < (t + q)){
13761             return "above";
13762         }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
13763             return "below";
13764         }else{
13765             return "append";
13766         }
13767     },
13768     
13769     onNodeEnter : function(n, dd, e, data)
13770     {
13771         this.cancelExpand();
13772     },
13773     
13774     onNodeOver : function(n, dd, e, data)
13775     {
13776        
13777         var pt = this.getDropPoint(e, n, dd);
13778         var node = n.node;
13779         
13780         // auto node expand check
13781         if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
13782             this.queueExpand(node);
13783         }else if(pt != "append"){
13784             this.cancelExpand();
13785         }
13786         
13787         // set the insert point style on the target node
13788         var returnCls = this.dropNotAllowed;
13789         if(this.isValidDropPoint(n, pt, dd, e, data)){
13790            if(pt){
13791                var el = n.ddel;
13792                var cls;
13793                if(pt == "above"){
13794                    returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
13795                    cls = "x-tree-drag-insert-above";
13796                }else if(pt == "below"){
13797                    returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
13798                    cls = "x-tree-drag-insert-below";
13799                }else{
13800                    returnCls = "x-tree-drop-ok-append";
13801                    cls = "x-tree-drag-append";
13802                }
13803                if(this.lastInsertClass != cls){
13804                    Roo.fly(el).replaceClass(this.lastInsertClass, cls);
13805                    this.lastInsertClass = cls;
13806                }
13807            }
13808        }
13809        return returnCls;
13810     },
13811     
13812     onNodeOut : function(n, dd, e, data){
13813         
13814         this.cancelExpand();
13815         this.removeDropIndicators(n);
13816     },
13817     
13818     onNodeDrop : function(n, dd, e, data){
13819         var point = this.getDropPoint(e, n, dd);
13820         var targetNode = n.node;
13821         targetNode.ui.startDrop();
13822         if(!this.isValidDropPoint(n, point, dd, e, data)){
13823             targetNode.ui.endDrop();
13824             return false;
13825         }
13826         // first try to find the drop node
13827         var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
13828         var dropEvent = {
13829             tree : this.tree,
13830             target: targetNode,
13831             data: data,
13832             point: point,
13833             source: dd,
13834             rawEvent: e,
13835             dropNode: dropNode,
13836             cancel: !dropNode   
13837         };
13838         var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
13839         if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
13840             targetNode.ui.endDrop();
13841             return false;
13842         }
13843         // allow target changing
13844         targetNode = dropEvent.target;
13845         if(point == "append" && !targetNode.isExpanded()){
13846             targetNode.expand(false, null, function(){
13847                 this.completeDrop(dropEvent);
13848             }.createDelegate(this));
13849         }else{
13850             this.completeDrop(dropEvent);
13851         }
13852         return true;
13853     },
13854     
13855     completeDrop : function(de){
13856         var ns = de.dropNode, p = de.point, t = de.target;
13857         if(!(ns instanceof Array)){
13858             ns = [ns];
13859         }
13860         var n;
13861         for(var i = 0, len = ns.length; i < len; i++){
13862             n = ns[i];
13863             if(p == "above"){
13864                 t.parentNode.insertBefore(n, t);
13865             }else if(p == "below"){
13866                 t.parentNode.insertBefore(n, t.nextSibling);
13867             }else{
13868                 t.appendChild(n);
13869             }
13870         }
13871         n.ui.focus();
13872         if(this.tree.hlDrop){
13873             n.ui.highlight();
13874         }
13875         t.ui.endDrop();
13876         this.tree.fireEvent("nodedrop", de);
13877     },
13878     
13879     afterNodeMoved : function(dd, data, e, targetNode, dropNode){
13880         if(this.tree.hlDrop){
13881             dropNode.ui.focus();
13882             dropNode.ui.highlight();
13883         }
13884         this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
13885     },
13886     
13887     getTree : function(){
13888         return this.tree;
13889     },
13890     
13891     removeDropIndicators : function(n){
13892         if(n && n.ddel){
13893             var el = n.ddel;
13894             Roo.fly(el).removeClass([
13895                     "x-tree-drag-insert-above",
13896                     "x-tree-drag-insert-below",
13897                     "x-tree-drag-append"]);
13898             this.lastInsertClass = "_noclass";
13899         }
13900     },
13901     
13902     beforeDragDrop : function(target, e, id){
13903         this.cancelExpand();
13904         return true;
13905     },
13906     
13907     afterRepair : function(data){
13908         if(data && Roo.enableFx){
13909             data.node.ui.highlight();
13910         }
13911         this.hideProxy();
13912     } 
13913     
13914 });
13915
13916 }
13917 /*
13918  * Based on:
13919  * Ext JS Library 1.1.1
13920  * Copyright(c) 2006-2007, Ext JS, LLC.
13921  *
13922  * Originally Released Under LGPL - original licence link has changed is not relivant.
13923  *
13924  * Fork - LGPL
13925  * <script type="text/javascript">
13926  */
13927  
13928
13929 if(Roo.dd.DragZone){
13930 Roo.tree.TreeDragZone = function(tree, config){
13931     Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
13932     this.tree = tree;
13933 };
13934
13935 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
13936     ddGroup : "TreeDD",
13937    
13938     onBeforeDrag : function(data, e){
13939         var n = data.node;
13940         return n && n.draggable && !n.disabled;
13941     },
13942      
13943     
13944     onInitDrag : function(e){
13945         var data = this.dragData;
13946         this.tree.getSelectionModel().select(data.node);
13947         this.proxy.update("");
13948         data.node.ui.appendDDGhost(this.proxy.ghost.dom);
13949         this.tree.fireEvent("startdrag", this.tree, data.node, e);
13950     },
13951     
13952     getRepairXY : function(e, data){
13953         return data.node.ui.getDDRepairXY();
13954     },
13955     
13956     onEndDrag : function(data, e){
13957         this.tree.fireEvent("enddrag", this.tree, data.node, e);
13958         
13959         
13960     },
13961     
13962     onValidDrop : function(dd, e, id){
13963         this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
13964         this.hideProxy();
13965     },
13966     
13967     beforeInvalidDrop : function(e, id){
13968         // this scrolls the original position back into view
13969         var sm = this.tree.getSelectionModel();
13970         sm.clearSelections();
13971         sm.select(this.dragData.node);
13972     }
13973 });
13974 }/*
13975  * Based on:
13976  * Ext JS Library 1.1.1
13977  * Copyright(c) 2006-2007, Ext JS, LLC.
13978  *
13979  * Originally Released Under LGPL - original licence link has changed is not relivant.
13980  *
13981  * Fork - LGPL
13982  * <script type="text/javascript">
13983  */
13984 /**
13985  * @class Roo.tree.TreeEditor
13986  * @extends Roo.Editor
13987  * Provides editor functionality for inline tree node editing.  Any valid {@link Roo.form.Field} can be used
13988  * as the editor field.
13989  * @constructor
13990  * @param {Object} config (used to be the tree panel.)
13991  * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
13992  * 
13993  * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
13994  * @cfg {Roo.form.TextField} field [required] The field configuration
13995  *
13996  * 
13997  */
13998 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
13999     var tree = config;
14000     var field;
14001     if (oldconfig) { // old style..
14002         field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
14003     } else {
14004         // new style..
14005         tree = config.tree;
14006         config.field = config.field  || {};
14007         config.field.xtype = 'TextField';
14008         field = Roo.factory(config.field, Roo.form);
14009     }
14010     config = config || {};
14011     
14012     
14013     this.addEvents({
14014         /**
14015          * @event beforenodeedit
14016          * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
14017          * false from the handler of this event.
14018          * @param {Editor} this
14019          * @param {Roo.tree.Node} node 
14020          */
14021         "beforenodeedit" : true
14022     });
14023     
14024     //Roo.log(config);
14025     Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
14026
14027     this.tree = tree;
14028
14029     tree.on('beforeclick', this.beforeNodeClick, this);
14030     tree.getTreeEl().on('mousedown', this.hide, this);
14031     this.on('complete', this.updateNode, this);
14032     this.on('beforestartedit', this.fitToTree, this);
14033     this.on('startedit', this.bindScroll, this, {delay:10});
14034     this.on('specialkey', this.onSpecialKey, this);
14035 };
14036
14037 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
14038     /**
14039      * @cfg {String} alignment
14040      * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
14041      */
14042     alignment: "l-l",
14043     // inherit
14044     autoSize: false,
14045     /**
14046      * @cfg {Boolean} hideEl
14047      * True to hide the bound element while the editor is displayed (defaults to false)
14048      */
14049     hideEl : false,
14050     /**
14051      * @cfg {String} cls
14052      * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
14053      */
14054     cls: "x-small-editor x-tree-editor",
14055     /**
14056      * @cfg {Boolean} shim
14057      * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
14058      */
14059     shim:false,
14060     // inherit
14061     shadow:"frame",
14062     /**
14063      * @cfg {Number} maxWidth
14064      * The maximum width in pixels of the editor field (defaults to 250).  Note that if the maxWidth would exceed
14065      * the containing tree element's size, it will be automatically limited for you to the container width, taking
14066      * scroll and client offsets into account prior to each edit.
14067      */
14068     maxWidth: 250,
14069
14070     editDelay : 350,
14071
14072     // private
14073     fitToTree : function(ed, el){
14074         var td = this.tree.getTreeEl().dom, nd = el.dom;
14075         if(td.scrollLeft >  nd.offsetLeft){ // ensure the node left point is visible
14076             td.scrollLeft = nd.offsetLeft;
14077         }
14078         var w = Math.min(
14079                 this.maxWidth,
14080                 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
14081         this.setSize(w, '');
14082         
14083         return this.fireEvent('beforenodeedit', this, this.editNode);
14084         
14085     },
14086
14087     // private
14088     triggerEdit : function(node){
14089         this.completeEdit();
14090         this.editNode = node;
14091         this.startEdit(node.ui.textNode, node.text);
14092     },
14093
14094     // private
14095     bindScroll : function(){
14096         this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
14097     },
14098
14099     // private
14100     beforeNodeClick : function(node, e){
14101         var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
14102         this.lastClick = new Date();
14103         if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
14104             e.stopEvent();
14105             this.triggerEdit(node);
14106             return false;
14107         }
14108         return true;
14109     },
14110
14111     // private
14112     updateNode : function(ed, value){
14113         this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
14114         this.editNode.setText(value);
14115     },
14116
14117     // private
14118     onHide : function(){
14119         Roo.tree.TreeEditor.superclass.onHide.call(this);
14120         if(this.editNode){
14121             this.editNode.ui.focus();
14122         }
14123     },
14124
14125     // private
14126     onSpecialKey : function(field, e){
14127         var k = e.getKey();
14128         if(k == e.ESC){
14129             e.stopEvent();
14130             this.cancelEdit();
14131         }else if(k == e.ENTER && !e.hasModifier()){
14132             e.stopEvent();
14133             this.completeEdit();
14134         }
14135     }
14136 });//<Script type="text/javascript">
14137 /*
14138  * Based on:
14139  * Ext JS Library 1.1.1
14140  * Copyright(c) 2006-2007, Ext JS, LLC.
14141  *
14142  * Originally Released Under LGPL - original licence link has changed is not relivant.
14143  *
14144  * Fork - LGPL
14145  * <script type="text/javascript">
14146  */
14147  
14148 /**
14149  * Not documented??? - probably should be...
14150  */
14151
14152 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
14153     //focus: Roo.emptyFn, // prevent odd scrolling behavior
14154     
14155     renderElements : function(n, a, targetNode, bulkRender){
14156         //consel.log("renderElements?");
14157         this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
14158
14159         var t = n.getOwnerTree();
14160         var tid = Pman.Tab.Document_TypesTree.tree.el.id;
14161         
14162         var cols = t.columns;
14163         var bw = t.borderWidth;
14164         var c = cols[0];
14165         var href = a.href ? a.href : Roo.isGecko ? "" : "#";
14166          var cb = typeof a.checked == "boolean";
14167         var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
14168         var colcls = 'x-t-' + tid + '-c0';
14169         var buf = [
14170             '<li class="x-tree-node">',
14171             
14172                 
14173                 '<div class="x-tree-node-el ', a.cls,'">',
14174                     // extran...
14175                     '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
14176                 
14177                 
14178                         '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
14179                         '<img src="', this.emptyIcon, '" class="x-tree-ec-icon  " />',
14180                         '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
14181                            (a.icon ? ' x-tree-node-inline-icon' : ''),
14182                            (a.iconCls ? ' '+a.iconCls : ''),
14183                            '" unselectable="on" />',
14184                         (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + 
14185                              (a.checked ? 'checked="checked" />' : ' />')) : ''),
14186                              
14187                         '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
14188                             (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
14189                             '<span unselectable="on" qtip="' + tx + '">',
14190                              tx,
14191                              '</span></a>' ,
14192                     '</div>',
14193                      '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
14194                             (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
14195                  ];
14196         for(var i = 1, len = cols.length; i < len; i++){
14197             c = cols[i];
14198             colcls = 'x-t-' + tid + '-c' +i;
14199             tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
14200             buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
14201                         '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
14202                       "</div>");
14203          }
14204          
14205          buf.push(
14206             '</a>',
14207             '<div class="x-clear"></div></div>',
14208             '<ul class="x-tree-node-ct" style="display:none;"></ul>',
14209             "</li>");
14210         
14211         if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
14212             this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
14213                                 n.nextSibling.ui.getEl(), buf.join(""));
14214         }else{
14215             this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
14216         }
14217         var el = this.wrap.firstChild;
14218         this.elRow = el;
14219         this.elNode = el.firstChild;
14220         this.ranchor = el.childNodes[1];
14221         this.ctNode = this.wrap.childNodes[1];
14222         var cs = el.firstChild.childNodes;
14223         this.indentNode = cs[0];
14224         this.ecNode = cs[1];
14225         this.iconNode = cs[2];
14226         var index = 3;
14227         if(cb){
14228             this.checkbox = cs[3];
14229             index++;
14230         }
14231         this.anchor = cs[index];
14232         
14233         this.textNode = cs[index].firstChild;
14234         
14235         //el.on("click", this.onClick, this);
14236         //el.on("dblclick", this.onDblClick, this);
14237         
14238         
14239        // console.log(this);
14240     },
14241     initEvents : function(){
14242         Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
14243         
14244             
14245         var a = this.ranchor;
14246
14247         var el = Roo.get(a);
14248
14249         if(Roo.isOpera){ // opera render bug ignores the CSS
14250             el.setStyle("text-decoration", "none");
14251         }
14252
14253         el.on("click", this.onClick, this);
14254         el.on("dblclick", this.onDblClick, this);
14255         el.on("contextmenu", this.onContextMenu, this);
14256         
14257     },
14258     
14259     /*onSelectedChange : function(state){
14260         if(state){
14261             this.focus();
14262             this.addClass("x-tree-selected");
14263         }else{
14264             //this.blur();
14265             this.removeClass("x-tree-selected");
14266         }
14267     },*/
14268     addClass : function(cls){
14269         if(this.elRow){
14270             Roo.fly(this.elRow).addClass(cls);
14271         }
14272         
14273     },
14274     
14275     
14276     removeClass : function(cls){
14277         if(this.elRow){
14278             Roo.fly(this.elRow).removeClass(cls);
14279         }
14280     }
14281
14282     
14283     
14284 });//<Script type="text/javascript">
14285
14286 /*
14287  * Based on:
14288  * Ext JS Library 1.1.1
14289  * Copyright(c) 2006-2007, Ext JS, LLC.
14290  *
14291  * Originally Released Under LGPL - original licence link has changed is not relivant.
14292  *
14293  * Fork - LGPL
14294  * <script type="text/javascript">
14295  */
14296  
14297
14298 /**
14299  * @class Roo.tree.ColumnTree
14300  * @extends Roo.tree.TreePanel
14301  * @cfg {Object} columns  Including width, header, renderer, cls, dataIndex 
14302  * @cfg {int} borderWidth  compined right/left border allowance
14303  * @constructor
14304  * @param {String/HTMLElement/Element} el The container element
14305  * @param {Object} config
14306  */
14307 Roo.tree.ColumnTree =  function(el, config)
14308 {
14309    Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
14310    this.addEvents({
14311         /**
14312         * @event resize
14313         * Fire this event on a container when it resizes
14314         * @param {int} w Width
14315         * @param {int} h Height
14316         */
14317        "resize" : true
14318     });
14319     this.on('resize', this.onResize, this);
14320 };
14321
14322 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
14323     //lines:false,
14324     
14325     
14326     borderWidth: Roo.isBorderBox ? 0 : 2, 
14327     headEls : false,
14328     
14329     render : function(){
14330         // add the header.....
14331        
14332         Roo.tree.ColumnTree.superclass.render.apply(this);
14333         
14334         this.el.addClass('x-column-tree');
14335         
14336         this.headers = this.el.createChild(
14337             {cls:'x-tree-headers'},this.innerCt.dom);
14338    
14339         var cols = this.columns, c;
14340         var totalWidth = 0;
14341         this.headEls = [];
14342         var  len = cols.length;
14343         for(var i = 0; i < len; i++){
14344              c = cols[i];
14345              totalWidth += c.width;
14346             this.headEls.push(this.headers.createChild({
14347                  cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
14348                  cn: {
14349                      cls:'x-tree-hd-text',
14350                      html: c.header
14351                  },
14352                  style:'width:'+(c.width-this.borderWidth)+'px;'
14353              }));
14354         }
14355         this.headers.createChild({cls:'x-clear'});
14356         // prevent floats from wrapping when clipped
14357         this.headers.setWidth(totalWidth);
14358         //this.innerCt.setWidth(totalWidth);
14359         this.innerCt.setStyle({ overflow: 'auto' });
14360         this.onResize(this.width, this.height);
14361              
14362         
14363     },
14364     onResize : function(w,h)
14365     {
14366         this.height = h;
14367         this.width = w;
14368         // resize cols..
14369         this.innerCt.setWidth(this.width);
14370         this.innerCt.setHeight(this.height-20);
14371         
14372         // headers...
14373         var cols = this.columns, c;
14374         var totalWidth = 0;
14375         var expEl = false;
14376         var len = cols.length;
14377         for(var i = 0; i < len; i++){
14378             c = cols[i];
14379             if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
14380                 // it's the expander..
14381                 expEl  = this.headEls[i];
14382                 continue;
14383             }
14384             totalWidth += c.width;
14385             
14386         }
14387         if (expEl) {
14388             expEl.setWidth(  ((w - totalWidth)-this.borderWidth - 20));
14389         }
14390         this.headers.setWidth(w-20);
14391
14392         
14393         
14394         
14395     }
14396 });
14397 /*
14398  * Based on:
14399  * Ext JS Library 1.1.1
14400  * Copyright(c) 2006-2007, Ext JS, LLC.
14401  *
14402  * Originally Released Under LGPL - original licence link has changed is not relivant.
14403  *
14404  * Fork - LGPL
14405  * <script type="text/javascript">
14406  */
14407  
14408 /**
14409  * @class Roo.menu.Menu
14410  * @extends Roo.util.Observable
14411  * @children Roo.menu.BaseItem
14412  * A menu object.  This is the container to which you add all other menu items.  Menu can also serve a as a base class
14413  * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
14414  * @constructor
14415  * Creates a new Menu
14416  * @param {Object} config Configuration options
14417  */
14418 Roo.menu.Menu = function(config){
14419     
14420     Roo.menu.Menu.superclass.constructor.call(this, config);
14421     
14422     this.id = this.id || Roo.id();
14423     this.addEvents({
14424         /**
14425          * @event beforeshow
14426          * Fires before this menu is displayed
14427          * @param {Roo.menu.Menu} this
14428          */
14429         beforeshow : true,
14430         /**
14431          * @event beforehide
14432          * Fires before this menu is hidden
14433          * @param {Roo.menu.Menu} this
14434          */
14435         beforehide : true,
14436         /**
14437          * @event show
14438          * Fires after this menu is displayed
14439          * @param {Roo.menu.Menu} this
14440          */
14441         show : true,
14442         /**
14443          * @event hide
14444          * Fires after this menu is hidden
14445          * @param {Roo.menu.Menu} this
14446          */
14447         hide : true,
14448         /**
14449          * @event click
14450          * Fires when this menu is clicked (or when the enter key is pressed while it is active)
14451          * @param {Roo.menu.Menu} this
14452          * @param {Roo.menu.Item} menuItem The menu item that was clicked
14453          * @param {Roo.EventObject} e
14454          */
14455         click : true,
14456         /**
14457          * @event mouseover
14458          * Fires when the mouse is hovering over this menu
14459          * @param {Roo.menu.Menu} this
14460          * @param {Roo.EventObject} e
14461          * @param {Roo.menu.Item} menuItem The menu item that was clicked
14462          */
14463         mouseover : true,
14464         /**
14465          * @event mouseout
14466          * Fires when the mouse exits this menu
14467          * @param {Roo.menu.Menu} this
14468          * @param {Roo.EventObject} e
14469          * @param {Roo.menu.Item} menuItem The menu item that was clicked
14470          */
14471         mouseout : true,
14472         /**
14473          * @event itemclick
14474          * Fires when a menu item contained in this menu is clicked
14475          * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
14476          * @param {Roo.EventObject} e
14477          */
14478         itemclick: true
14479     });
14480     if (this.registerMenu) {
14481         Roo.menu.MenuMgr.register(this);
14482     }
14483     
14484     var mis = this.items;
14485     this.items = new Roo.util.MixedCollection();
14486     if(mis){
14487         this.add.apply(this, mis);
14488     }
14489 };
14490
14491 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
14492     /**
14493      * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
14494      */
14495     minWidth : 120,
14496     /**
14497      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
14498      * for bottom-right shadow (defaults to "sides")
14499      */
14500     shadow : "sides",
14501     /**
14502      * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
14503      * this menu (defaults to "tl-tr?")
14504      */
14505     subMenuAlign : "tl-tr?",
14506     /**
14507      * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
14508      * relative to its element of origin (defaults to "tl-bl?")
14509      */
14510     defaultAlign : "tl-bl?",
14511     /**
14512      * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
14513      */
14514     allowOtherMenus : false,
14515     /**
14516      * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
14517      */
14518     registerMenu : true,
14519
14520     hidden:true,
14521
14522     // private
14523     render : function(){
14524         if(this.el){
14525             return;
14526         }
14527         var el = this.el = new Roo.Layer({
14528             cls: "x-menu",
14529             shadow:this.shadow,
14530             constrain: false,
14531             parentEl: this.parentEl || document.body,
14532             zindex:15000
14533         });
14534
14535         this.keyNav = new Roo.menu.MenuNav(this);
14536
14537         if(this.plain){
14538             el.addClass("x-menu-plain");
14539         }
14540         if(this.cls){
14541             el.addClass(this.cls);
14542         }
14543         // generic focus element
14544         this.focusEl = el.createChild({
14545             tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
14546         });
14547         var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
14548         //disabling touch- as it's causing issues ..
14549         //ul.on(Roo.isTouch ? 'touchstart' : 'click'   , this.onClick, this);
14550         ul.on('click'   , this.onClick, this);
14551         
14552         
14553         ul.on("mouseover", this.onMouseOver, this);
14554         ul.on("mouseout", this.onMouseOut, this);
14555         this.items.each(function(item){
14556             if (item.hidden) {
14557                 return;
14558             }
14559             
14560             var li = document.createElement("li");
14561             li.className = "x-menu-list-item";
14562             ul.dom.appendChild(li);
14563             item.render(li, this);
14564         }, this);
14565         this.ul = ul;
14566         this.autoWidth();
14567     },
14568
14569     // private
14570     autoWidth : function(){
14571         var el = this.el, ul = this.ul;
14572         if(!el){
14573             return;
14574         }
14575         var w = this.width;
14576         if(w){
14577             el.setWidth(w);
14578         }else if(Roo.isIE){
14579             el.setWidth(this.minWidth);
14580             var t = el.dom.offsetWidth; // force recalc
14581             el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
14582         }
14583     },
14584
14585     // private
14586     delayAutoWidth : function(){
14587         if(this.rendered){
14588             if(!this.awTask){
14589                 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
14590             }
14591             this.awTask.delay(20);
14592         }
14593     },
14594
14595     // private
14596     findTargetItem : function(e){
14597         var t = e.getTarget(".x-menu-list-item", this.ul,  true);
14598         if(t && t.menuItemId){
14599             return this.items.get(t.menuItemId);
14600         }
14601     },
14602
14603     // private
14604     onClick : function(e){
14605         Roo.log("menu.onClick");
14606         var t = this.findTargetItem(e);
14607         if(!t){
14608             return;
14609         }
14610         Roo.log(e);
14611         if (Roo.isTouch && e.type == 'touchstart' && t.menu  && !t.disabled) {
14612             if(t == this.activeItem && t.shouldDeactivate(e)){
14613                 this.activeItem.deactivate();
14614                 delete this.activeItem;
14615                 return;
14616             }
14617             if(t.canActivate){
14618                 this.setActiveItem(t, true);
14619             }
14620             return;
14621             
14622             
14623         }
14624         
14625         t.onClick(e);
14626         this.fireEvent("click", this, t, e);
14627     },
14628
14629     // private
14630     setActiveItem : function(item, autoExpand){
14631         if(item != this.activeItem){
14632             if(this.activeItem){
14633                 this.activeItem.deactivate();
14634             }
14635             this.activeItem = item;
14636             item.activate(autoExpand);
14637         }else if(autoExpand){
14638             item.expandMenu();
14639         }
14640     },
14641
14642     // private
14643     tryActivate : function(start, step){
14644         var items = this.items;
14645         for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
14646             var item = items.get(i);
14647             if(!item.disabled && item.canActivate){
14648                 this.setActiveItem(item, false);
14649                 return item;
14650             }
14651         }
14652         return false;
14653     },
14654
14655     // private
14656     onMouseOver : function(e){
14657         var t;
14658         if(t = this.findTargetItem(e)){
14659             if(t.canActivate && !t.disabled){
14660                 this.setActiveItem(t, true);
14661             }
14662         }
14663         this.fireEvent("mouseover", this, e, t);
14664     },
14665
14666     // private
14667     onMouseOut : function(e){
14668         var t;
14669         if(t = this.findTargetItem(e)){
14670             if(t == this.activeItem && t.shouldDeactivate(e)){
14671                 this.activeItem.deactivate();
14672                 delete this.activeItem;
14673             }
14674         }
14675         this.fireEvent("mouseout", this, e, t);
14676     },
14677
14678     /**
14679      * Read-only.  Returns true if the menu is currently displayed, else false.
14680      * @type Boolean
14681      */
14682     isVisible : function(){
14683         return this.el && !this.hidden;
14684     },
14685
14686     /**
14687      * Displays this menu relative to another element
14688      * @param {String/HTMLElement/Roo.Element} element The element to align to
14689      * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
14690      * the element (defaults to this.defaultAlign)
14691      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
14692      */
14693     show : function(el, pos, parentMenu){
14694         this.parentMenu = parentMenu;
14695         if(!this.el){
14696             this.render();
14697         }
14698         this.fireEvent("beforeshow", this);
14699         this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
14700     },
14701
14702     /**
14703      * Displays this menu at a specific xy position
14704      * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
14705      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
14706      */
14707     showAt : function(xy, parentMenu, /* private: */_e){
14708         this.parentMenu = parentMenu;
14709         if(!this.el){
14710             this.render();
14711         }
14712         if(_e !== false){
14713             this.fireEvent("beforeshow", this);
14714             xy = this.el.adjustForConstraints(xy);
14715         }
14716         this.el.setXY(xy);
14717         this.el.show();
14718         this.hidden = false;
14719         this.focus();
14720         this.fireEvent("show", this);
14721     },
14722
14723     focus : function(){
14724         if(!this.hidden){
14725             this.doFocus.defer(50, this);
14726         }
14727     },
14728
14729     doFocus : function(){
14730         if(!this.hidden){
14731             this.focusEl.focus();
14732         }
14733     },
14734
14735     /**
14736      * Hides this menu and optionally all parent menus
14737      * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
14738      */
14739     hide : function(deep){
14740         if(this.el && this.isVisible()){
14741             this.fireEvent("beforehide", this);
14742             if(this.activeItem){
14743                 this.activeItem.deactivate();
14744                 this.activeItem = null;
14745             }
14746             this.el.hide();
14747             this.hidden = true;
14748             this.fireEvent("hide", this);
14749         }
14750         if(deep === true && this.parentMenu){
14751             this.parentMenu.hide(true);
14752         }
14753     },
14754
14755     /**
14756      * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
14757      * Any of the following are valid:
14758      * <ul>
14759      * <li>Any menu item object based on {@link Roo.menu.Item}</li>
14760      * <li>An HTMLElement object which will be converted to a menu item</li>
14761      * <li>A menu item config object that will be created as a new menu item</li>
14762      * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
14763      * it will be converted into a {@link Roo.menu.TextItem} and added</li>
14764      * </ul>
14765      * Usage:
14766      * <pre><code>
14767 // Create the menu
14768 var menu = new Roo.menu.Menu();
14769
14770 // Create a menu item to add by reference
14771 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
14772
14773 // Add a bunch of items at once using different methods.
14774 // Only the last item added will be returned.
14775 var item = menu.add(
14776     menuItem,                // add existing item by ref
14777     'Dynamic Item',          // new TextItem
14778     '-',                     // new separator
14779     { text: 'Config Item' }  // new item by config
14780 );
14781 </code></pre>
14782      * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
14783      * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
14784      */
14785     add : function(){
14786         var a = arguments, l = a.length, item;
14787         for(var i = 0; i < l; i++){
14788             var el = a[i];
14789             if ((typeof(el) == "object") && el.xtype && el.xns) {
14790                 el = Roo.factory(el, Roo.menu);
14791             }
14792             
14793             if(el.render){ // some kind of Item
14794                 item = this.addItem(el);
14795             }else if(typeof el == "string"){ // string
14796                 if(el == "separator" || el == "-"){
14797                     item = this.addSeparator();
14798                 }else{
14799                     item = this.addText(el);
14800                 }
14801             }else if(el.tagName || el.el){ // element
14802                 item = this.addElement(el);
14803             }else if(typeof el == "object"){ // must be menu item config?
14804                 item = this.addMenuItem(el);
14805             }
14806         }
14807         return item;
14808     },
14809
14810     /**
14811      * Returns this menu's underlying {@link Roo.Element} object
14812      * @return {Roo.Element} The element
14813      */
14814     getEl : function(){
14815         if(!this.el){
14816             this.render();
14817         }
14818         return this.el;
14819     },
14820
14821     /**
14822      * Adds a separator bar to the menu
14823      * @return {Roo.menu.Item} The menu item that was added
14824      */
14825     addSeparator : function(){
14826         return this.addItem(new Roo.menu.Separator());
14827     },
14828
14829     /**
14830      * Adds an {@link Roo.Element} object to the menu
14831      * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
14832      * @return {Roo.menu.Item} The menu item that was added
14833      */
14834     addElement : function(el){
14835         return this.addItem(new Roo.menu.BaseItem(el));
14836     },
14837
14838     /**
14839      * Adds an existing object based on {@link Roo.menu.Item} to the menu
14840      * @param {Roo.menu.Item} item The menu item to add
14841      * @return {Roo.menu.Item} The menu item that was added
14842      */
14843     addItem : function(item){
14844         this.items.add(item);
14845         if(this.ul){
14846             var li = document.createElement("li");
14847             li.className = "x-menu-list-item";
14848             this.ul.dom.appendChild(li);
14849             item.render(li, this);
14850             this.delayAutoWidth();
14851         }
14852         return item;
14853     },
14854
14855     /**
14856      * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
14857      * @param {Object} config A MenuItem config object
14858      * @return {Roo.menu.Item} The menu item that was added
14859      */
14860     addMenuItem : function(config){
14861         if(!(config instanceof Roo.menu.Item)){
14862             if(typeof config.checked == "boolean"){ // must be check menu item config?
14863                 config = new Roo.menu.CheckItem(config);
14864             }else{
14865                 config = new Roo.menu.Item(config);
14866             }
14867         }
14868         return this.addItem(config);
14869     },
14870
14871     /**
14872      * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
14873      * @param {String} text The text to display in the menu item
14874      * @return {Roo.menu.Item} The menu item that was added
14875      */
14876     addText : function(text){
14877         return this.addItem(new Roo.menu.TextItem({ text : text }));
14878     },
14879
14880     /**
14881      * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
14882      * @param {Number} index The index in the menu's list of current items where the new item should be inserted
14883      * @param {Roo.menu.Item} item The menu item to add
14884      * @return {Roo.menu.Item} The menu item that was added
14885      */
14886     insert : function(index, item){
14887         this.items.insert(index, item);
14888         if(this.ul){
14889             var li = document.createElement("li");
14890             li.className = "x-menu-list-item";
14891             this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
14892             item.render(li, this);
14893             this.delayAutoWidth();
14894         }
14895         return item;
14896     },
14897
14898     /**
14899      * Removes an {@link Roo.menu.Item} from the menu and destroys the object
14900      * @param {Roo.menu.Item} item The menu item to remove
14901      */
14902     remove : function(item){
14903         this.items.removeKey(item.id);
14904         item.destroy();
14905     },
14906
14907     /**
14908      * Removes and destroys all items in the menu
14909      */
14910     removeAll : function(){
14911         var f;
14912         while(f = this.items.first()){
14913             this.remove(f);
14914         }
14915     }
14916 });
14917
14918 // MenuNav is a private utility class used internally by the Menu
14919 Roo.menu.MenuNav = function(menu){
14920     Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
14921     this.scope = this.menu = menu;
14922 };
14923
14924 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
14925     doRelay : function(e, h){
14926         var k = e.getKey();
14927         if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
14928             this.menu.tryActivate(0, 1);
14929             return false;
14930         }
14931         return h.call(this.scope || this, e, this.menu);
14932     },
14933
14934     up : function(e, m){
14935         if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
14936             m.tryActivate(m.items.length-1, -1);
14937         }
14938     },
14939
14940     down : function(e, m){
14941         if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
14942             m.tryActivate(0, 1);
14943         }
14944     },
14945
14946     right : function(e, m){
14947         if(m.activeItem){
14948             m.activeItem.expandMenu(true);
14949         }
14950     },
14951
14952     left : function(e, m){
14953         m.hide();
14954         if(m.parentMenu && m.parentMenu.activeItem){
14955             m.parentMenu.activeItem.activate();
14956         }
14957     },
14958
14959     enter : function(e, m){
14960         if(m.activeItem){
14961             e.stopPropagation();
14962             m.activeItem.onClick(e);
14963             m.fireEvent("click", this, m.activeItem);
14964             return true;
14965         }
14966     }
14967 });/*
14968  * Based on:
14969  * Ext JS Library 1.1.1
14970  * Copyright(c) 2006-2007, Ext JS, LLC.
14971  *
14972  * Originally Released Under LGPL - original licence link has changed is not relivant.
14973  *
14974  * Fork - LGPL
14975  * <script type="text/javascript">
14976  */
14977  
14978 /**
14979  * @class Roo.menu.MenuMgr
14980  * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
14981  * @static
14982  */
14983 Roo.menu.MenuMgr = function(){
14984    var menus, active, groups = {}, attached = false, lastShow = new Date();
14985
14986    // private - called when first menu is created
14987    function init(){
14988        menus = {};
14989        active = new Roo.util.MixedCollection();
14990        Roo.get(document).addKeyListener(27, function(){
14991            if(active.length > 0){
14992                hideAll();
14993            }
14994        });
14995    }
14996
14997    // private
14998    function hideAll(){
14999        if(active && active.length > 0){
15000            var c = active.clone();
15001            c.each(function(m){
15002                m.hide();
15003            });
15004        }
15005    }
15006
15007    // private
15008    function onHide(m){
15009        active.remove(m);
15010        if(active.length < 1){
15011            Roo.get(document).un("mousedown", onMouseDown);
15012            attached = false;
15013        }
15014    }
15015
15016    // private
15017    function onShow(m){
15018        var last = active.last();
15019        lastShow = new Date();
15020        active.add(m);
15021        if(!attached){
15022            Roo.get(document).on("mousedown", onMouseDown);
15023            attached = true;
15024        }
15025        if(m.parentMenu){
15026           m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
15027           m.parentMenu.activeChild = m;
15028        }else if(last && last.isVisible()){
15029           m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
15030        }
15031    }
15032
15033    // private
15034    function onBeforeHide(m){
15035        if(m.activeChild){
15036            m.activeChild.hide();
15037        }
15038        if(m.autoHideTimer){
15039            clearTimeout(m.autoHideTimer);
15040            delete m.autoHideTimer;
15041        }
15042    }
15043
15044    // private
15045    function onBeforeShow(m){
15046        var pm = m.parentMenu;
15047        if(!pm && !m.allowOtherMenus){
15048            hideAll();
15049        }else if(pm && pm.activeChild && active != m){
15050            pm.activeChild.hide();
15051        }
15052    }
15053
15054    // private
15055    function onMouseDown(e){
15056        if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
15057            hideAll();
15058        }
15059    }
15060
15061    // private
15062    function onBeforeCheck(mi, state){
15063        if(state){
15064            var g = groups[mi.group];
15065            for(var i = 0, l = g.length; i < l; i++){
15066                if(g[i] != mi){
15067                    g[i].setChecked(false);
15068                }
15069            }
15070        }
15071    }
15072
15073    return {
15074
15075        /**
15076         * Hides all menus that are currently visible
15077         */
15078        hideAll : function(){
15079             hideAll();  
15080        },
15081
15082        // private
15083        register : function(menu){
15084            if(!menus){
15085                init();
15086            }
15087            menus[menu.id] = menu;
15088            menu.on("beforehide", onBeforeHide);
15089            menu.on("hide", onHide);
15090            menu.on("beforeshow", onBeforeShow);
15091            menu.on("show", onShow);
15092            var g = menu.group;
15093            if(g && menu.events["checkchange"]){
15094                if(!groups[g]){
15095                    groups[g] = [];
15096                }
15097                groups[g].push(menu);
15098                menu.on("checkchange", onCheck);
15099            }
15100        },
15101
15102         /**
15103          * Returns a {@link Roo.menu.Menu} object
15104          * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
15105          * be used to generate and return a new Menu instance.
15106          */
15107        get : function(menu){
15108            if(typeof menu == "string"){ // menu id
15109                return menus[menu];
15110            }else if(menu.events){  // menu instance
15111                return menu;
15112            }else if(typeof menu.length == 'number'){ // array of menu items?
15113                return new Roo.menu.Menu({items:menu});
15114            }else{ // otherwise, must be a config
15115                return new Roo.menu.Menu(menu);
15116            }
15117        },
15118
15119        // private
15120        unregister : function(menu){
15121            delete menus[menu.id];
15122            menu.un("beforehide", onBeforeHide);
15123            menu.un("hide", onHide);
15124            menu.un("beforeshow", onBeforeShow);
15125            menu.un("show", onShow);
15126            var g = menu.group;
15127            if(g && menu.events["checkchange"]){
15128                groups[g].remove(menu);
15129                menu.un("checkchange", onCheck);
15130            }
15131        },
15132
15133        // private
15134        registerCheckable : function(menuItem){
15135            var g = menuItem.group;
15136            if(g){
15137                if(!groups[g]){
15138                    groups[g] = [];
15139                }
15140                groups[g].push(menuItem);
15141                menuItem.on("beforecheckchange", onBeforeCheck);
15142            }
15143        },
15144
15145        // private
15146        unregisterCheckable : function(menuItem){
15147            var g = menuItem.group;
15148            if(g){
15149                groups[g].remove(menuItem);
15150                menuItem.un("beforecheckchange", onBeforeCheck);
15151            }
15152        }
15153    };
15154 }();/*
15155  * Based on:
15156  * Ext JS Library 1.1.1
15157  * Copyright(c) 2006-2007, Ext JS, LLC.
15158  *
15159  * Originally Released Under LGPL - original licence link has changed is not relivant.
15160  *
15161  * Fork - LGPL
15162  * <script type="text/javascript">
15163  */
15164  
15165
15166 /**
15167  * @class Roo.menu.BaseItem
15168  * @extends Roo.Component
15169  * @abstract
15170  * The base class for all items that render into menus.  BaseItem provides default rendering, activated state
15171  * management and base configuration options shared by all menu components.
15172  * @constructor
15173  * Creates a new BaseItem
15174  * @param {Object} config Configuration options
15175  */
15176 Roo.menu.BaseItem = function(config){
15177     Roo.menu.BaseItem.superclass.constructor.call(this, config);
15178
15179     this.addEvents({
15180         /**
15181          * @event click
15182          * Fires when this item is clicked
15183          * @param {Roo.menu.BaseItem} this
15184          * @param {Roo.EventObject} e
15185          */
15186         click: true,
15187         /**
15188          * @event activate
15189          * Fires when this item is activated
15190          * @param {Roo.menu.BaseItem} this
15191          */
15192         activate : true,
15193         /**
15194          * @event deactivate
15195          * Fires when this item is deactivated
15196          * @param {Roo.menu.BaseItem} this
15197          */
15198         deactivate : true
15199     });
15200
15201     if(this.handler){
15202         this.on("click", this.handler, this.scope, true);
15203     }
15204 };
15205
15206 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
15207     /**
15208      * @cfg {Function} handler
15209      * A function that will handle the click event of this menu item (defaults to undefined)
15210      */
15211     /**
15212      * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
15213      */
15214     canActivate : false,
15215     
15216      /**
15217      * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
15218      */
15219     hidden: false,
15220     
15221     /**
15222      * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
15223      */
15224     activeClass : "x-menu-item-active",
15225     /**
15226      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
15227      */
15228     hideOnClick : true,
15229     /**
15230      * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
15231      */
15232     hideDelay : 100,
15233
15234     // private
15235     ctype: "Roo.menu.BaseItem",
15236
15237     // private
15238     actionMode : "container",
15239
15240     // private
15241     render : function(container, parentMenu){
15242         this.parentMenu = parentMenu;
15243         Roo.menu.BaseItem.superclass.render.call(this, container);
15244         this.container.menuItemId = this.id;
15245     },
15246
15247     // private
15248     onRender : function(container, position){
15249         this.el = Roo.get(this.el);
15250         container.dom.appendChild(this.el.dom);
15251     },
15252
15253     // private
15254     onClick : function(e){
15255         if(!this.disabled && this.fireEvent("click", this, e) !== false
15256                 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
15257             this.handleClick(e);
15258         }else{
15259             e.stopEvent();
15260         }
15261     },
15262
15263     // private
15264     activate : function(){
15265         if(this.disabled){
15266             return false;
15267         }
15268         var li = this.container;
15269         li.addClass(this.activeClass);
15270         this.region = li.getRegion().adjust(2, 2, -2, -2);
15271         this.fireEvent("activate", this);
15272         return true;
15273     },
15274
15275     // private
15276     deactivate : function(){
15277         this.container.removeClass(this.activeClass);
15278         this.fireEvent("deactivate", this);
15279     },
15280
15281     // private
15282     shouldDeactivate : function(e){
15283         return !this.region || !this.region.contains(e.getPoint());
15284     },
15285
15286     // private
15287     handleClick : function(e){
15288         if(this.hideOnClick){
15289             this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
15290         }
15291     },
15292
15293     // private
15294     expandMenu : function(autoActivate){
15295         // do nothing
15296     },
15297
15298     // private
15299     hideMenu : function(){
15300         // do nothing
15301     }
15302 });/*
15303  * Based on:
15304  * Ext JS Library 1.1.1
15305  * Copyright(c) 2006-2007, Ext JS, LLC.
15306  *
15307  * Originally Released Under LGPL - original licence link has changed is not relivant.
15308  *
15309  * Fork - LGPL
15310  * <script type="text/javascript">
15311  */
15312  
15313 /**
15314  * @class Roo.menu.Adapter
15315  * @extends Roo.menu.BaseItem
15316  * @abstract
15317  * 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.
15318  * It provides basic rendering, activation management and enable/disable logic required to work in menus.
15319  * @constructor
15320  * Creates a new Adapter
15321  * @param {Object} config Configuration options
15322  */
15323 Roo.menu.Adapter = function(component, config){
15324     Roo.menu.Adapter.superclass.constructor.call(this, config);
15325     this.component = component;
15326 };
15327 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
15328     // private
15329     canActivate : true,
15330
15331     // private
15332     onRender : function(container, position){
15333         this.component.render(container);
15334         this.el = this.component.getEl();
15335     },
15336
15337     // private
15338     activate : function(){
15339         if(this.disabled){
15340             return false;
15341         }
15342         this.component.focus();
15343         this.fireEvent("activate", this);
15344         return true;
15345     },
15346
15347     // private
15348     deactivate : function(){
15349         this.fireEvent("deactivate", this);
15350     },
15351
15352     // private
15353     disable : function(){
15354         this.component.disable();
15355         Roo.menu.Adapter.superclass.disable.call(this);
15356     },
15357
15358     // private
15359     enable : function(){
15360         this.component.enable();
15361         Roo.menu.Adapter.superclass.enable.call(this);
15362     }
15363 });/*
15364  * Based on:
15365  * Ext JS Library 1.1.1
15366  * Copyright(c) 2006-2007, Ext JS, LLC.
15367  *
15368  * Originally Released Under LGPL - original licence link has changed is not relivant.
15369  *
15370  * Fork - LGPL
15371  * <script type="text/javascript">
15372  */
15373
15374 /**
15375  * @class Roo.menu.TextItem
15376  * @extends Roo.menu.BaseItem
15377  * Adds a static text string to a menu, usually used as either a heading or group separator.
15378  * Note: old style constructor with text is still supported.
15379  * 
15380  * @constructor
15381  * Creates a new TextItem
15382  * @param {Object} cfg Configuration
15383  */
15384 Roo.menu.TextItem = function(cfg){
15385     if (typeof(cfg) == 'string') {
15386         this.text = cfg;
15387     } else {
15388         Roo.apply(this,cfg);
15389     }
15390     
15391     Roo.menu.TextItem.superclass.constructor.call(this);
15392 };
15393
15394 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
15395     /**
15396      * @cfg {String} text Text to show on item.
15397      */
15398     text : '',
15399     
15400     /**
15401      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
15402      */
15403     hideOnClick : false,
15404     /**
15405      * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
15406      */
15407     itemCls : "x-menu-text",
15408
15409     // private
15410     onRender : function(){
15411         var s = document.createElement("span");
15412         s.className = this.itemCls;
15413         s.innerHTML = this.text;
15414         this.el = s;
15415         Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
15416     }
15417 });/*
15418  * Based on:
15419  * Ext JS Library 1.1.1
15420  * Copyright(c) 2006-2007, Ext JS, LLC.
15421  *
15422  * Originally Released Under LGPL - original licence link has changed is not relivant.
15423  *
15424  * Fork - LGPL
15425  * <script type="text/javascript">
15426  */
15427
15428 /**
15429  * @class Roo.menu.Separator
15430  * @extends Roo.menu.BaseItem
15431  * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
15432  * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
15433  * @constructor
15434  * @param {Object} config Configuration options
15435  */
15436 Roo.menu.Separator = function(config){
15437     Roo.menu.Separator.superclass.constructor.call(this, config);
15438 };
15439
15440 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
15441     /**
15442      * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
15443      */
15444     itemCls : "x-menu-sep",
15445     /**
15446      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
15447      */
15448     hideOnClick : false,
15449
15450     // private
15451     onRender : function(li){
15452         var s = document.createElement("span");
15453         s.className = this.itemCls;
15454         s.innerHTML = "&#160;";
15455         this.el = s;
15456         li.addClass("x-menu-sep-li");
15457         Roo.menu.Separator.superclass.onRender.apply(this, arguments);
15458     }
15459 });/*
15460  * Based on:
15461  * Ext JS Library 1.1.1
15462  * Copyright(c) 2006-2007, Ext JS, LLC.
15463  *
15464  * Originally Released Under LGPL - original licence link has changed is not relivant.
15465  *
15466  * Fork - LGPL
15467  * <script type="text/javascript">
15468  */
15469 /**
15470  * @class Roo.menu.Item
15471  * @extends Roo.menu.BaseItem
15472  * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
15473  * display items.  Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
15474  * activation and click handling.
15475  * @constructor
15476  * Creates a new Item
15477  * @param {Object} config Configuration options
15478  */
15479 Roo.menu.Item = function(config){
15480     Roo.menu.Item.superclass.constructor.call(this, config);
15481     if(this.menu){
15482         this.menu = Roo.menu.MenuMgr.get(this.menu);
15483     }
15484 };
15485 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
15486     /**
15487      * @cfg {Roo.menu.Menu} menu
15488      * A Sub menu
15489      */
15490     /**
15491      * @cfg {String} text
15492      * The text to show on the menu item.
15493      */
15494     text: '',
15495      /**
15496      * @cfg {String} HTML to render in menu
15497      * The text to show on the menu item (HTML version).
15498      */
15499     html: '',
15500     /**
15501      * @cfg {String} icon
15502      * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
15503      */
15504     icon: undefined,
15505     /**
15506      * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
15507      */
15508     itemCls : "x-menu-item",
15509     /**
15510      * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
15511      */
15512     canActivate : true,
15513     /**
15514      * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
15515      */
15516     showDelay: 200,
15517     // doc'd in BaseItem
15518     hideDelay: 200,
15519
15520     // private
15521     ctype: "Roo.menu.Item",
15522     
15523     // private
15524     onRender : function(container, position){
15525         var el = document.createElement("a");
15526         el.hideFocus = true;
15527         el.unselectable = "on";
15528         el.href = this.href || "#";
15529         if(this.hrefTarget){
15530             el.target = this.hrefTarget;
15531         }
15532         el.className = this.itemCls + (this.menu ?  " x-menu-item-arrow" : "") + (this.cls ?  " " + this.cls : "");
15533         
15534         var html = this.html.length ? this.html  : String.format('{0}',this.text);
15535         
15536         el.innerHTML = String.format(
15537                 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
15538                 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
15539         this.el = el;
15540         Roo.menu.Item.superclass.onRender.call(this, container, position);
15541     },
15542
15543     /**
15544      * Sets the text to display in this menu item
15545      * @param {String} text The text to display
15546      * @param {Boolean} isHTML true to indicate text is pure html.
15547      */
15548     setText : function(text, isHTML){
15549         if (isHTML) {
15550             this.html = text;
15551         } else {
15552             this.text = text;
15553             this.html = '';
15554         }
15555         if(this.rendered){
15556             var html = this.html.length ? this.html  : String.format('{0}',this.text);
15557      
15558             this.el.update(String.format(
15559                 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
15560                 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
15561             this.parentMenu.autoWidth();
15562         }
15563     },
15564
15565     // private
15566     handleClick : function(e){
15567         if(!this.href){ // if no link defined, stop the event automatically
15568             e.stopEvent();
15569         }
15570         Roo.menu.Item.superclass.handleClick.apply(this, arguments);
15571     },
15572
15573     // private
15574     activate : function(autoExpand){
15575         if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
15576             this.focus();
15577             if(autoExpand){
15578                 this.expandMenu();
15579             }
15580         }
15581         return true;
15582     },
15583
15584     // private
15585     shouldDeactivate : function(e){
15586         if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
15587             if(this.menu && this.menu.isVisible()){
15588                 return !this.menu.getEl().getRegion().contains(e.getPoint());
15589             }
15590             return true;
15591         }
15592         return false;
15593     },
15594
15595     // private
15596     deactivate : function(){
15597         Roo.menu.Item.superclass.deactivate.apply(this, arguments);
15598         this.hideMenu();
15599     },
15600
15601     // private
15602     expandMenu : function(autoActivate){
15603         if(!this.disabled && this.menu){
15604             clearTimeout(this.hideTimer);
15605             delete this.hideTimer;
15606             if(!this.menu.isVisible() && !this.showTimer){
15607                 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
15608             }else if (this.menu.isVisible() && autoActivate){
15609                 this.menu.tryActivate(0, 1);
15610             }
15611         }
15612     },
15613
15614     // private
15615     deferExpand : function(autoActivate){
15616         delete this.showTimer;
15617         this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
15618         if(autoActivate){
15619             this.menu.tryActivate(0, 1);
15620         }
15621     },
15622
15623     // private
15624     hideMenu : function(){
15625         clearTimeout(this.showTimer);
15626         delete this.showTimer;
15627         if(!this.hideTimer && this.menu && this.menu.isVisible()){
15628             this.hideTimer = this.deferHide.defer(this.hideDelay, this);
15629         }
15630     },
15631
15632     // private
15633     deferHide : function(){
15634         delete this.hideTimer;
15635         this.menu.hide();
15636     }
15637 });/*
15638  * Based on:
15639  * Ext JS Library 1.1.1
15640  * Copyright(c) 2006-2007, Ext JS, LLC.
15641  *
15642  * Originally Released Under LGPL - original licence link has changed is not relivant.
15643  *
15644  * Fork - LGPL
15645  * <script type="text/javascript">
15646  */
15647  
15648 /**
15649  * @class Roo.menu.CheckItem
15650  * @extends Roo.menu.Item
15651  * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
15652  * @constructor
15653  * Creates a new CheckItem
15654  * @param {Object} config Configuration options
15655  */
15656 Roo.menu.CheckItem = function(config){
15657     Roo.menu.CheckItem.superclass.constructor.call(this, config);
15658     this.addEvents({
15659         /**
15660          * @event beforecheckchange
15661          * Fires before the checked value is set, providing an opportunity to cancel if needed
15662          * @param {Roo.menu.CheckItem} this
15663          * @param {Boolean} checked The new checked value that will be set
15664          */
15665         "beforecheckchange" : true,
15666         /**
15667          * @event checkchange
15668          * Fires after the checked value has been set
15669          * @param {Roo.menu.CheckItem} this
15670          * @param {Boolean} checked The checked value that was set
15671          */
15672         "checkchange" : true
15673     });
15674     if(this.checkHandler){
15675         this.on('checkchange', this.checkHandler, this.scope);
15676     }
15677 };
15678 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
15679     /**
15680      * @cfg {String} group
15681      * All check items with the same group name will automatically be grouped into a single-select
15682      * radio button group (defaults to '')
15683      */
15684     /**
15685      * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
15686      */
15687     itemCls : "x-menu-item x-menu-check-item",
15688     /**
15689      * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
15690      */
15691     groupClass : "x-menu-group-item",
15692
15693     /**
15694      * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false).  Note that
15695      * if this checkbox is part of a radio group (group = true) only the last item in the group that is
15696      * initialized with checked = true will be rendered as checked.
15697      */
15698     checked: false,
15699
15700     // private
15701     ctype: "Roo.menu.CheckItem",
15702
15703     // private
15704     onRender : function(c){
15705         Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
15706         if(this.group){
15707             this.el.addClass(this.groupClass);
15708         }
15709         Roo.menu.MenuMgr.registerCheckable(this);
15710         if(this.checked){
15711             this.checked = false;
15712             this.setChecked(true, true);
15713         }
15714     },
15715
15716     // private
15717     destroy : function(){
15718         if(this.rendered){
15719             Roo.menu.MenuMgr.unregisterCheckable(this);
15720         }
15721         Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
15722     },
15723
15724     /**
15725      * Set the checked state of this item
15726      * @param {Boolean} checked The new checked value
15727      * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
15728      */
15729     setChecked : function(state, suppressEvent){
15730         if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
15731             if(this.container){
15732                 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
15733             }
15734             this.checked = state;
15735             if(suppressEvent !== true){
15736                 this.fireEvent("checkchange", this, state);
15737             }
15738         }
15739     },
15740
15741     // private
15742     handleClick : function(e){
15743        if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
15744            this.setChecked(!this.checked);
15745        }
15746        Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
15747     }
15748 });/*
15749  * Based on:
15750  * Ext JS Library 1.1.1
15751  * Copyright(c) 2006-2007, Ext JS, LLC.
15752  *
15753  * Originally Released Under LGPL - original licence link has changed is not relivant.
15754  *
15755  * Fork - LGPL
15756  * <script type="text/javascript">
15757  */
15758  
15759 /**
15760  * @class Roo.menu.DateItem
15761  * @extends Roo.menu.Adapter
15762  * A menu item that wraps the {@link Roo.DatPicker} component.
15763  * @constructor
15764  * Creates a new DateItem
15765  * @param {Object} config Configuration options
15766  */
15767 Roo.menu.DateItem = function(config){
15768     Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
15769     /** The Roo.DatePicker object @type Roo.DatePicker */
15770     this.picker = this.component;
15771     this.addEvents({select: true});
15772     
15773     this.picker.on("render", function(picker){
15774         picker.getEl().swallowEvent("click");
15775         picker.container.addClass("x-menu-date-item");
15776     });
15777
15778     this.picker.on("select", this.onSelect, this);
15779 };
15780
15781 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
15782     // private
15783     onSelect : function(picker, date){
15784         this.fireEvent("select", this, date, picker);
15785         Roo.menu.DateItem.superclass.handleClick.call(this);
15786     }
15787 });/*
15788  * Based on:
15789  * Ext JS Library 1.1.1
15790  * Copyright(c) 2006-2007, Ext JS, LLC.
15791  *
15792  * Originally Released Under LGPL - original licence link has changed is not relivant.
15793  *
15794  * Fork - LGPL
15795  * <script type="text/javascript">
15796  */
15797  
15798 /**
15799  * @class Roo.menu.ColorItem
15800  * @extends Roo.menu.Adapter
15801  * A menu item that wraps the {@link Roo.ColorPalette} component.
15802  * @constructor
15803  * Creates a new ColorItem
15804  * @param {Object} config Configuration options
15805  */
15806 Roo.menu.ColorItem = function(config){
15807     Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
15808     /** The Roo.ColorPalette object @type Roo.ColorPalette */
15809     this.palette = this.component;
15810     this.relayEvents(this.palette, ["select"]);
15811     if(this.selectHandler){
15812         this.on('select', this.selectHandler, this.scope);
15813     }
15814 };
15815 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
15816  * Based on:
15817  * Ext JS Library 1.1.1
15818  * Copyright(c) 2006-2007, Ext JS, LLC.
15819  *
15820  * Originally Released Under LGPL - original licence link has changed is not relivant.
15821  *
15822  * Fork - LGPL
15823  * <script type="text/javascript">
15824  */
15825  
15826
15827 /**
15828  * @class Roo.menu.DateMenu
15829  * @extends Roo.menu.Menu
15830  * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
15831  * @constructor
15832  * Creates a new DateMenu
15833  * @param {Object} config Configuration options
15834  */
15835 Roo.menu.DateMenu = function(config){
15836     Roo.menu.DateMenu.superclass.constructor.call(this, config);
15837     this.plain = true;
15838     var di = new Roo.menu.DateItem(config);
15839     this.add(di);
15840     /**
15841      * The {@link Roo.DatePicker} instance for this DateMenu
15842      * @type DatePicker
15843      */
15844     this.picker = di.picker;
15845     /**
15846      * @event select
15847      * @param {DatePicker} picker
15848      * @param {Date} date
15849      */
15850     this.relayEvents(di, ["select"]);
15851     this.on('beforeshow', function(){
15852         if(this.picker){
15853             this.picker.hideMonthPicker(false);
15854         }
15855     }, this);
15856 };
15857 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
15858     cls:'x-date-menu'
15859 });/*
15860  * Based on:
15861  * Ext JS Library 1.1.1
15862  * Copyright(c) 2006-2007, Ext JS, LLC.
15863  *
15864  * Originally Released Under LGPL - original licence link has changed is not relivant.
15865  *
15866  * Fork - LGPL
15867  * <script type="text/javascript">
15868  */
15869  
15870
15871 /**
15872  * @class Roo.menu.ColorMenu
15873  * @extends Roo.menu.Menu
15874  * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
15875  * @constructor
15876  * Creates a new ColorMenu
15877  * @param {Object} config Configuration options
15878  */
15879 Roo.menu.ColorMenu = function(config){
15880     Roo.menu.ColorMenu.superclass.constructor.call(this, config);
15881     this.plain = true;
15882     var ci = new Roo.menu.ColorItem(config);
15883     this.add(ci);
15884     /**
15885      * The {@link Roo.ColorPalette} instance for this ColorMenu
15886      * @type ColorPalette
15887      */
15888     this.palette = ci.palette;
15889     /**
15890      * @event select
15891      * @param {ColorPalette} palette
15892      * @param {String} color
15893      */
15894     this.relayEvents(ci, ["select"]);
15895 };
15896 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
15897  * Based on:
15898  * Ext JS Library 1.1.1
15899  * Copyright(c) 2006-2007, Ext JS, LLC.
15900  *
15901  * Originally Released Under LGPL - original licence link has changed is not relivant.
15902  *
15903  * Fork - LGPL
15904  * <script type="text/javascript">
15905  */
15906  
15907 /**
15908  * @class Roo.form.TextItem
15909  * @extends Roo.BoxComponent
15910  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
15911  * @constructor
15912  * Creates a new TextItem
15913  * @param {Object} config Configuration options
15914  */
15915 Roo.form.TextItem = function(config){
15916     Roo.form.TextItem.superclass.constructor.call(this, config);
15917 };
15918
15919 Roo.extend(Roo.form.TextItem, Roo.BoxComponent,  {
15920     
15921     /**
15922      * @cfg {String} tag the tag for this item (default div)
15923      */
15924     tag : 'div',
15925     /**
15926      * @cfg {String} html the content for this item
15927      */
15928     html : '',
15929     
15930     getAutoCreate : function()
15931     {
15932         var cfg = {
15933             id: this.id,
15934             tag: this.tag,
15935             html: this.html,
15936             cls: 'x-form-item'
15937         };
15938         
15939         return cfg;
15940         
15941     },
15942     
15943     onRender : function(ct, position)
15944     {
15945         Roo.form.TextItem.superclass.onRender.call(this, ct, position);
15946         
15947         if(!this.el){
15948             var cfg = this.getAutoCreate();
15949             if(!cfg.name){
15950                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
15951             }
15952             if (!cfg.name.length) {
15953                 delete cfg.name;
15954             }
15955             this.el = ct.createChild(cfg, position);
15956         }
15957     },
15958     /*
15959      * setHTML
15960      * @param {String} html update the Contents of the element.
15961      */
15962     setHTML : function(html)
15963     {
15964         this.fieldEl.dom.innerHTML = html;
15965     }
15966     
15967 });/*
15968  * Based on:
15969  * Ext JS Library 1.1.1
15970  * Copyright(c) 2006-2007, Ext JS, LLC.
15971  *
15972  * Originally Released Under LGPL - original licence link has changed is not relivant.
15973  *
15974  * Fork - LGPL
15975  * <script type="text/javascript">
15976  */
15977  
15978 /**
15979  * @class Roo.form.Field
15980  * @extends Roo.BoxComponent
15981  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
15982  * @constructor
15983  * Creates a new Field
15984  * @param {Object} config Configuration options
15985  */
15986 Roo.form.Field = function(config){
15987     Roo.form.Field.superclass.constructor.call(this, config);
15988 };
15989
15990 Roo.extend(Roo.form.Field, Roo.BoxComponent,  {
15991     /**
15992      * @cfg {String} fieldLabel Label to use when rendering a form.
15993      */
15994        /**
15995      * @cfg {String} qtip Mouse over tip
15996      */
15997      
15998     /**
15999      * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
16000      */
16001     invalidClass : "x-form-invalid",
16002     /**
16003      * @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")
16004      */
16005     invalidText : "The value in this field is invalid",
16006     /**
16007      * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
16008      */
16009     focusClass : "x-form-focus",
16010     /**
16011      * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
16012       automatic validation (defaults to "keyup").
16013      */
16014     validationEvent : "keyup",
16015     /**
16016      * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
16017      */
16018     validateOnBlur : true,
16019     /**
16020      * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
16021      */
16022     validationDelay : 250,
16023     /**
16024      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
16025      * {tag: "input", type: "text", size: "20", autocomplete: "off"})
16026      */
16027     defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "new-password"},
16028     /**
16029      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
16030      */
16031     fieldClass : "x-form-field",
16032     /**
16033      * @cfg {String} msgTarget The location where error text should display.  Should be one of the following values (defaults to 'qtip'):
16034      *<pre>
16035 Value         Description
16036 -----------   ----------------------------------------------------------------------
16037 qtip          Display a quick tip when the user hovers over the field
16038 title         Display a default browser title attribute popup
16039 under         Add a block div beneath the field containing the error text
16040 side          Add an error icon to the right of the field with a popup on hover
16041 [element id]  Add the error text directly to the innerHTML of the specified element
16042 </pre>
16043      */
16044     msgTarget : 'qtip',
16045     /**
16046      * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
16047      */
16048     msgFx : 'normal',
16049
16050     /**
16051      * @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.
16052      */
16053     readOnly : false,
16054
16055     /**
16056      * @cfg {Boolean} disabled True to disable the field (defaults to false).
16057      */
16058     disabled : false,
16059
16060     /**
16061      * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
16062      */
16063     inputType : undefined,
16064     
16065     /**
16066      * @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).
16067          */
16068         tabIndex : undefined,
16069         
16070     // private
16071     isFormField : true,
16072
16073     // private
16074     hasFocus : false,
16075     /**
16076      * @property {Roo.Element} fieldEl
16077      * Element Containing the rendered Field (with label etc.)
16078      */
16079     /**
16080      * @cfg {Mixed} value A value to initialize this field with.
16081      */
16082     value : undefined,
16083
16084     /**
16085      * @cfg {String} name The field's HTML name attribute.
16086      */
16087     /**
16088      * @cfg {String} cls A CSS class to apply to the field's underlying element.
16089      */
16090     // private
16091     loadedValue : false,
16092      
16093      
16094         // private ??
16095         initComponent : function(){
16096         Roo.form.Field.superclass.initComponent.call(this);
16097         this.addEvents({
16098             /**
16099              * @event focus
16100              * Fires when this field receives input focus.
16101              * @param {Roo.form.Field} this
16102              */
16103             focus : true,
16104             /**
16105              * @event blur
16106              * Fires when this field loses input focus.
16107              * @param {Roo.form.Field} this
16108              */
16109             blur : true,
16110             /**
16111              * @event specialkey
16112              * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
16113              * {@link Roo.EventObject#getKey} to determine which key was pressed.
16114              * @param {Roo.form.Field} this
16115              * @param {Roo.EventObject} e The event object
16116              */
16117             specialkey : true,
16118             /**
16119              * @event change
16120              * Fires just before the field blurs if the field value has changed.
16121              * @param {Roo.form.Field} this
16122              * @param {Mixed} newValue The new value
16123              * @param {Mixed} oldValue The original value
16124              */
16125             change : true,
16126             /**
16127              * @event invalid
16128              * Fires after the field has been marked as invalid.
16129              * @param {Roo.form.Field} this
16130              * @param {String} msg The validation message
16131              */
16132             invalid : true,
16133             /**
16134              * @event valid
16135              * Fires after the field has been validated with no errors.
16136              * @param {Roo.form.Field} this
16137              */
16138             valid : true,
16139              /**
16140              * @event keyup
16141              * Fires after the key up
16142              * @param {Roo.form.Field} this
16143              * @param {Roo.EventObject}  e The event Object
16144              */
16145             keyup : true
16146         });
16147     },
16148
16149     /**
16150      * Returns the name attribute of the field if available
16151      * @return {String} name The field name
16152      */
16153     getName: function(){
16154          return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
16155     },
16156
16157     // private
16158     onRender : function(ct, position){
16159         Roo.form.Field.superclass.onRender.call(this, ct, position);
16160         if(!this.el){
16161             var cfg = this.getAutoCreate();
16162             if(!cfg.name){
16163                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
16164             }
16165             if (!cfg.name.length) {
16166                 delete cfg.name;
16167             }
16168             if(this.inputType){
16169                 cfg.type = this.inputType;
16170             }
16171             this.el = ct.createChild(cfg, position);
16172         }
16173         var type = this.el.dom.type;
16174         if(type){
16175             if(type == 'password'){
16176                 type = 'text';
16177             }
16178             this.el.addClass('x-form-'+type);
16179         }
16180         if(this.readOnly){
16181             this.el.dom.readOnly = true;
16182         }
16183         if(this.tabIndex !== undefined){
16184             this.el.dom.setAttribute('tabIndex', this.tabIndex);
16185         }
16186
16187         this.el.addClass([this.fieldClass, this.cls]);
16188         this.initValue();
16189     },
16190
16191     /**
16192      * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
16193      * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
16194      * @return {Roo.form.Field} this
16195      */
16196     applyTo : function(target){
16197         this.allowDomMove = false;
16198         this.el = Roo.get(target);
16199         this.render(this.el.dom.parentNode);
16200         return this;
16201     },
16202
16203     // private
16204     initValue : function(){
16205         if(this.value !== undefined){
16206             this.setValue(this.value);
16207         }else if(this.el.dom.value.length > 0){
16208             this.setValue(this.el.dom.value);
16209         }
16210     },
16211
16212     /**
16213      * Returns true if this field has been changed since it was originally loaded and is not disabled.
16214      * DEPRICATED  - it never worked well - use hasChanged/resetHasChanged.
16215      */
16216     isDirty : function() {
16217         if(this.disabled) {
16218             return false;
16219         }
16220         return String(this.getValue()) !== String(this.originalValue);
16221     },
16222
16223     /**
16224      * stores the current value in loadedValue
16225      */
16226     resetHasChanged : function()
16227     {
16228         this.loadedValue = String(this.getValue());
16229     },
16230     /**
16231      * checks the current value against the 'loaded' value.
16232      * Note - will return false if 'resetHasChanged' has not been called first.
16233      */
16234     hasChanged : function()
16235     {
16236         if(this.disabled || this.readOnly) {
16237             return false;
16238         }
16239         return this.loadedValue !== false && String(this.getValue()) !== this.loadedValue;
16240     },
16241     
16242     
16243     
16244     // private
16245     afterRender : function(){
16246         Roo.form.Field.superclass.afterRender.call(this);
16247         this.initEvents();
16248     },
16249
16250     // private
16251     fireKey : function(e){
16252         //Roo.log('field ' + e.getKey());
16253         if(e.isNavKeyPress()){
16254             this.fireEvent("specialkey", this, e);
16255         }
16256     },
16257
16258     /**
16259      * Resets the current field value to the originally loaded value and clears any validation messages
16260      */
16261     reset : function(){
16262         this.setValue(this.resetValue);
16263         this.originalValue = this.getValue();
16264         this.clearInvalid();
16265     },
16266
16267     // private
16268     initEvents : function(){
16269         // safari killled keypress - so keydown is now used..
16270         this.el.on("keydown" , this.fireKey,  this);
16271         this.el.on("focus", this.onFocus,  this);
16272         this.el.on("blur", this.onBlur,  this);
16273         this.el.relayEvent('keyup', this);
16274
16275         // reference to original value for reset
16276         this.originalValue = this.getValue();
16277         this.resetValue =  this.getValue();
16278     },
16279
16280     // private
16281     onFocus : function(){
16282         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
16283             this.el.addClass(this.focusClass);
16284         }
16285         if(!this.hasFocus){
16286             this.hasFocus = true;
16287             this.startValue = this.getValue();
16288             this.fireEvent("focus", this);
16289         }
16290     },
16291
16292     beforeBlur : Roo.emptyFn,
16293
16294     // private
16295     onBlur : function(){
16296         this.beforeBlur();
16297         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
16298             this.el.removeClass(this.focusClass);
16299         }
16300         this.hasFocus = false;
16301         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
16302             this.validate();
16303         }
16304         var v = this.getValue();
16305         if(String(v) !== String(this.startValue)){
16306             this.fireEvent('change', this, v, this.startValue);
16307         }
16308         this.fireEvent("blur", this);
16309     },
16310
16311     /**
16312      * Returns whether or not the field value is currently valid
16313      * @param {Boolean} preventMark True to disable marking the field invalid
16314      * @return {Boolean} True if the value is valid, else false
16315      */
16316     isValid : function(preventMark){
16317         if(this.disabled){
16318             return true;
16319         }
16320         var restore = this.preventMark;
16321         this.preventMark = preventMark === true;
16322         var v = this.validateValue(this.processValue(this.getRawValue()));
16323         this.preventMark = restore;
16324         return v;
16325     },
16326
16327     /**
16328      * Validates the field value
16329      * @return {Boolean} True if the value is valid, else false
16330      */
16331     validate : function(){
16332         if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
16333             this.clearInvalid();
16334             return true;
16335         }
16336         return false;
16337     },
16338
16339     processValue : function(value){
16340         return value;
16341     },
16342
16343     // private
16344     // Subclasses should provide the validation implementation by overriding this
16345     validateValue : function(value){
16346         return true;
16347     },
16348
16349     /**
16350      * Mark this field as invalid
16351      * @param {String} msg The validation message
16352      */
16353     markInvalid : function(msg){
16354         if(!this.rendered || this.preventMark){ // not rendered
16355             return;
16356         }
16357         
16358         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
16359         
16360         obj.el.addClass(this.invalidClass);
16361         msg = msg || this.invalidText;
16362         switch(this.msgTarget){
16363             case 'qtip':
16364                 obj.el.dom.qtip = msg;
16365                 obj.el.dom.qclass = 'x-form-invalid-tip';
16366                 if(Roo.QuickTips){ // fix for floating editors interacting with DND
16367                     Roo.QuickTips.enable();
16368                 }
16369                 break;
16370             case 'title':
16371                 this.el.dom.title = msg;
16372                 break;
16373             case 'under':
16374                 if(!this.errorEl){
16375                     var elp = this.el.findParent('.x-form-element', 5, true);
16376                     this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
16377                     this.errorEl.setWidth(elp.getWidth(true)-20);
16378                 }
16379                 this.errorEl.update(msg);
16380                 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
16381                 break;
16382             case 'side':
16383                 if(!this.errorIcon){
16384                     var elp = this.el.findParent('.x-form-element', 5, true);
16385                     this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
16386                 }
16387                 this.alignErrorIcon();
16388                 this.errorIcon.dom.qtip = msg;
16389                 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
16390                 this.errorIcon.show();
16391                 this.on('resize', this.alignErrorIcon, this);
16392                 break;
16393             default:
16394                 var t = Roo.getDom(this.msgTarget);
16395                 t.innerHTML = msg;
16396                 t.style.display = this.msgDisplay;
16397                 break;
16398         }
16399         this.fireEvent('invalid', this, msg);
16400     },
16401
16402     // private
16403     alignErrorIcon : function(){
16404         this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
16405     },
16406
16407     /**
16408      * Clear any invalid styles/messages for this field
16409      */
16410     clearInvalid : function(){
16411         if(!this.rendered || this.preventMark){ // not rendered
16412             return;
16413         }
16414         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
16415         
16416         obj.el.removeClass(this.invalidClass);
16417         switch(this.msgTarget){
16418             case 'qtip':
16419                 obj.el.dom.qtip = '';
16420                 break;
16421             case 'title':
16422                 this.el.dom.title = '';
16423                 break;
16424             case 'under':
16425                 if(this.errorEl){
16426                     Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
16427                 }
16428                 break;
16429             case 'side':
16430                 if(this.errorIcon){
16431                     this.errorIcon.dom.qtip = '';
16432                     this.errorIcon.hide();
16433                     this.un('resize', this.alignErrorIcon, this);
16434                 }
16435                 break;
16436             default:
16437                 var t = Roo.getDom(this.msgTarget);
16438                 t.innerHTML = '';
16439                 t.style.display = 'none';
16440                 break;
16441         }
16442         this.fireEvent('valid', this);
16443     },
16444
16445     /**
16446      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
16447      * @return {Mixed} value The field value
16448      */
16449     getRawValue : function(){
16450         var v = this.el.getValue();
16451         
16452         return v;
16453     },
16454
16455     /**
16456      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
16457      * @return {Mixed} value The field value
16458      */
16459     getValue : function(){
16460         var v = this.el.getValue();
16461          
16462         return v;
16463     },
16464
16465     /**
16466      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
16467      * @param {Mixed} value The value to set
16468      */
16469     setRawValue : function(v){
16470         return this.el.dom.value = (v === null || v === undefined ? '' : v);
16471     },
16472
16473     /**
16474      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
16475      * @param {Mixed} value The value to set
16476      */
16477     setValue : function(v){
16478         this.value = v;
16479         if(this.rendered){
16480             this.el.dom.value = (v === null || v === undefined ? '' : v);
16481              this.validate();
16482         }
16483     },
16484
16485     adjustSize : function(w, h){
16486         var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
16487         s.width = this.adjustWidth(this.el.dom.tagName, s.width);
16488         return s;
16489     },
16490
16491     adjustWidth : function(tag, w){
16492         tag = tag.toLowerCase();
16493         if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
16494             if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
16495                 if(tag == 'input'){
16496                     return w + 2;
16497                 }
16498                 if(tag == 'textarea'){
16499                     return w-2;
16500                 }
16501             }else if(Roo.isOpera){
16502                 if(tag == 'input'){
16503                     return w + 2;
16504                 }
16505                 if(tag == 'textarea'){
16506                     return w-2;
16507                 }
16508             }
16509         }
16510         return w;
16511     }
16512 });
16513
16514
16515 // anything other than normal should be considered experimental
16516 Roo.form.Field.msgFx = {
16517     normal : {
16518         show: function(msgEl, f){
16519             msgEl.setDisplayed('block');
16520         },
16521
16522         hide : function(msgEl, f){
16523             msgEl.setDisplayed(false).update('');
16524         }
16525     },
16526
16527     slide : {
16528         show: function(msgEl, f){
16529             msgEl.slideIn('t', {stopFx:true});
16530         },
16531
16532         hide : function(msgEl, f){
16533             msgEl.slideOut('t', {stopFx:true,useDisplay:true});
16534         }
16535     },
16536
16537     slideRight : {
16538         show: function(msgEl, f){
16539             msgEl.fixDisplay();
16540             msgEl.alignTo(f.el, 'tl-tr');
16541             msgEl.slideIn('l', {stopFx:true});
16542         },
16543
16544         hide : function(msgEl, f){
16545             msgEl.slideOut('l', {stopFx:true,useDisplay:true});
16546         }
16547     }
16548 };/*
16549  * Based on:
16550  * Ext JS Library 1.1.1
16551  * Copyright(c) 2006-2007, Ext JS, LLC.
16552  *
16553  * Originally Released Under LGPL - original licence link has changed is not relivant.
16554  *
16555  * Fork - LGPL
16556  * <script type="text/javascript">
16557  */
16558  
16559
16560 /**
16561  * @class Roo.form.TextField
16562  * @extends Roo.form.Field
16563  * Basic text field.  Can be used as a direct replacement for traditional text inputs, or as the base
16564  * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
16565  * @constructor
16566  * Creates a new TextField
16567  * @param {Object} config Configuration options
16568  */
16569 Roo.form.TextField = function(config){
16570     Roo.form.TextField.superclass.constructor.call(this, config);
16571     this.addEvents({
16572         /**
16573          * @event autosize
16574          * Fires when the autosize function is triggered.  The field may or may not have actually changed size
16575          * according to the default logic, but this event provides a hook for the developer to apply additional
16576          * logic at runtime to resize the field if needed.
16577              * @param {Roo.form.Field} this This text field
16578              * @param {Number} width The new field width
16579              */
16580         autosize : true
16581     });
16582 };
16583
16584 Roo.extend(Roo.form.TextField, Roo.form.Field,  {
16585     /**
16586      * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
16587      */
16588     grow : false,
16589     /**
16590      * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
16591      */
16592     growMin : 30,
16593     /**
16594      * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
16595      */
16596     growMax : 800,
16597     /**
16598      * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
16599      */
16600     vtype : null,
16601     /**
16602      * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
16603      */
16604     maskRe : null,
16605     /**
16606      * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
16607      */
16608     disableKeyFilter : false,
16609     /**
16610      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
16611      */
16612     allowBlank : true,
16613     /**
16614      * @cfg {Number} minLength Minimum input field length required (defaults to 0)
16615      */
16616     minLength : 0,
16617     /**
16618      * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
16619      */
16620     maxLength : Number.MAX_VALUE,
16621     /**
16622      * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
16623      */
16624     minLengthText : "The minimum length for this field is {0}",
16625     /**
16626      * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
16627      */
16628     maxLengthText : "The maximum length for this field is {0}",
16629     /**
16630      * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
16631      */
16632     selectOnFocus : false,
16633     /**
16634      * @cfg {Boolean} allowLeadingSpace True to prevent the stripping of leading white space 
16635      */    
16636     allowLeadingSpace : false,
16637     /**
16638      * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
16639      */
16640     blankText : "This field is required",
16641     /**
16642      * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
16643      * If available, this function will be called only after the basic validators all return true, and will be passed the
16644      * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
16645      */
16646     validator : null,
16647     /**
16648      * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
16649      * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
16650      * current field value.  If the test fails, the field will be marked invalid using {@link #regexText}.
16651      */
16652     regex : null,
16653     /**
16654      * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
16655      */
16656     regexText : "",
16657     /**
16658      * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
16659      */
16660     emptyText : null,
16661    
16662
16663     // private
16664     initEvents : function()
16665     {
16666         if (this.emptyText) {
16667             this.el.attr('placeholder', this.emptyText);
16668         }
16669         
16670         Roo.form.TextField.superclass.initEvents.call(this);
16671         if(this.validationEvent == 'keyup'){
16672             this.validationTask = new Roo.util.DelayedTask(this.validate, this);
16673             this.el.on('keyup', this.filterValidation, this);
16674         }
16675         else if(this.validationEvent !== false){
16676             this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
16677         }
16678         
16679         if(this.selectOnFocus){
16680             this.on("focus", this.preFocus, this);
16681         }
16682         if (!this.allowLeadingSpace) {
16683             this.on('blur', this.cleanLeadingSpace, this);
16684         }
16685         
16686         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
16687             this.el.on("keypress", this.filterKeys, this);
16688         }
16689         if(this.grow){
16690             this.el.on("keyup", this.onKeyUp,  this, {buffer:50});
16691             this.el.on("click", this.autoSize,  this);
16692         }
16693         if(this.el.is('input[type=password]') && Roo.isSafari){
16694             this.el.on('keydown', this.SafariOnKeyDown, this);
16695         }
16696     },
16697
16698     processValue : function(value){
16699         if(this.stripCharsRe){
16700             var newValue = value.replace(this.stripCharsRe, '');
16701             if(newValue !== value){
16702                 this.setRawValue(newValue);
16703                 return newValue;
16704             }
16705         }
16706         return value;
16707     },
16708
16709     filterValidation : function(e){
16710         if(!e.isNavKeyPress()){
16711             this.validationTask.delay(this.validationDelay);
16712         }
16713     },
16714
16715     // private
16716     onKeyUp : function(e){
16717         if(!e.isNavKeyPress()){
16718             this.autoSize();
16719         }
16720     },
16721     // private - clean the leading white space
16722     cleanLeadingSpace : function(e)
16723     {
16724         if ( this.inputType == 'file') {
16725             return;
16726         }
16727         
16728         this.setValue((this.getValue() + '').replace(/^\s+/,''));
16729     },
16730     /**
16731      * Resets the current field value to the originally-loaded value and clears any validation messages.
16732      *  
16733      */
16734     reset : function(){
16735         Roo.form.TextField.superclass.reset.call(this);
16736        
16737     }, 
16738     // private
16739     preFocus : function(){
16740         
16741         if(this.selectOnFocus){
16742             this.el.dom.select();
16743         }
16744     },
16745
16746     
16747     // private
16748     filterKeys : function(e){
16749         var k = e.getKey();
16750         if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
16751             return;
16752         }
16753         var c = e.getCharCode(), cc = String.fromCharCode(c);
16754         if(Roo.isIE && (e.isSpecialKey() || !cc)){
16755             return;
16756         }
16757         if(!this.maskRe.test(cc)){
16758             e.stopEvent();
16759         }
16760     },
16761
16762     setValue : function(v){
16763         
16764         Roo.form.TextField.superclass.setValue.apply(this, arguments);
16765         
16766         this.autoSize();
16767     },
16768
16769     /**
16770      * Validates a value according to the field's validation rules and marks the field as invalid
16771      * if the validation fails
16772      * @param {Mixed} value The value to validate
16773      * @return {Boolean} True if the value is valid, else false
16774      */
16775     validateValue : function(value){
16776         if(value.length < 1)  { // if it's blank
16777              if(this.allowBlank){
16778                 this.clearInvalid();
16779                 return true;
16780              }else{
16781                 this.markInvalid(this.blankText);
16782                 return false;
16783              }
16784         }
16785         if(value.length < this.minLength){
16786             this.markInvalid(String.format(this.minLengthText, this.minLength));
16787             return false;
16788         }
16789         if(value.length > this.maxLength){
16790             this.markInvalid(String.format(this.maxLengthText, this.maxLength));
16791             return false;
16792         }
16793         if(this.vtype){
16794             var vt = Roo.form.VTypes;
16795             if(!vt[this.vtype](value, this)){
16796                 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
16797                 return false;
16798             }
16799         }
16800         if(typeof this.validator == "function"){
16801             var msg = this.validator(value);
16802             if(msg !== true){
16803                 this.markInvalid(msg);
16804                 return false;
16805             }
16806         }
16807         if(this.regex && !this.regex.test(value)){
16808             this.markInvalid(this.regexText);
16809             return false;
16810         }
16811         return true;
16812     },
16813
16814     /**
16815      * Selects text in this field
16816      * @param {Number} start (optional) The index where the selection should start (defaults to 0)
16817      * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
16818      */
16819     selectText : function(start, end){
16820         var v = this.getRawValue();
16821         if(v.length > 0){
16822             start = start === undefined ? 0 : start;
16823             end = end === undefined ? v.length : end;
16824             var d = this.el.dom;
16825             if(d.setSelectionRange){
16826                 d.setSelectionRange(start, end);
16827             }else if(d.createTextRange){
16828                 var range = d.createTextRange();
16829                 range.moveStart("character", start);
16830                 range.moveEnd("character", v.length-end);
16831                 range.select();
16832             }
16833         }
16834     },
16835
16836     /**
16837      * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
16838      * This only takes effect if grow = true, and fires the autosize event.
16839      */
16840     autoSize : function(){
16841         if(!this.grow || !this.rendered){
16842             return;
16843         }
16844         if(!this.metrics){
16845             this.metrics = Roo.util.TextMetrics.createInstance(this.el);
16846         }
16847         var el = this.el;
16848         var v = el.dom.value;
16849         var d = document.createElement('div');
16850         d.appendChild(document.createTextNode(v));
16851         v = d.innerHTML;
16852         d = null;
16853         v += "&#160;";
16854         var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
16855         this.el.setWidth(w);
16856         this.fireEvent("autosize", this, w);
16857     },
16858     
16859     // private
16860     SafariOnKeyDown : function(event)
16861     {
16862         // this is a workaround for a password hang bug on chrome/ webkit.
16863         
16864         var isSelectAll = false;
16865         
16866         if(this.el.dom.selectionEnd > 0){
16867             isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
16868         }
16869         if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
16870             event.preventDefault();
16871             this.setValue('');
16872             return;
16873         }
16874         
16875         if(isSelectAll && event.getCharCode() > 31){ // backspace and delete key
16876             
16877             event.preventDefault();
16878             // this is very hacky as keydown always get's upper case.
16879             
16880             var cc = String.fromCharCode(event.getCharCode());
16881             
16882             
16883             this.setValue( event.shiftKey ?  cc : cc.toLowerCase());
16884             
16885         }
16886         
16887         
16888     }
16889 });/*
16890  * Based on:
16891  * Ext JS Library 1.1.1
16892  * Copyright(c) 2006-2007, Ext JS, LLC.
16893  *
16894  * Originally Released Under LGPL - original licence link has changed is not relivant.
16895  *
16896  * Fork - LGPL
16897  * <script type="text/javascript">
16898  */
16899  
16900 /**
16901  * @class Roo.form.Hidden
16902  * @extends Roo.form.TextField
16903  * Simple Hidden element used on forms 
16904  * 
16905  * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
16906  * 
16907  * @constructor
16908  * Creates a new Hidden form element.
16909  * @param {Object} config Configuration options
16910  */
16911
16912
16913
16914 // easy hidden field...
16915 Roo.form.Hidden = function(config){
16916     Roo.form.Hidden.superclass.constructor.call(this, config);
16917 };
16918   
16919 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
16920     fieldLabel:      '',
16921     inputType:      'hidden',
16922     width:          50,
16923     allowBlank:     true,
16924     labelSeparator: '',
16925     hidden:         true,
16926     itemCls :       'x-form-item-display-none'
16927
16928
16929 });
16930
16931
16932 /*
16933  * Based on:
16934  * Ext JS Library 1.1.1
16935  * Copyright(c) 2006-2007, Ext JS, LLC.
16936  *
16937  * Originally Released Under LGPL - original licence link has changed is not relivant.
16938  *
16939  * Fork - LGPL
16940  * <script type="text/javascript">
16941  */
16942  
16943 /**
16944  * @class Roo.form.TriggerField
16945  * @extends Roo.form.TextField
16946  * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
16947  * The trigger has no default action, so you must assign a function to implement the trigger click handler by
16948  * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
16949  * for which you can provide a custom implementation.  For example:
16950  * <pre><code>
16951 var trigger = new Roo.form.TriggerField();
16952 trigger.onTriggerClick = myTriggerFn;
16953 trigger.applyTo('my-field');
16954 </code></pre>
16955  *
16956  * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
16957  * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
16958  * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
16959  * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
16960  * @constructor
16961  * Create a new TriggerField.
16962  * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
16963  * to the base TextField)
16964  */
16965 Roo.form.TriggerField = function(config){
16966     this.mimicing = false;
16967     Roo.form.TriggerField.superclass.constructor.call(this, config);
16968 };
16969
16970 Roo.extend(Roo.form.TriggerField, Roo.form.TextField,  {
16971     /**
16972      * @cfg {String} triggerClass A CSS class to apply to the trigger
16973      */
16974     /**
16975      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
16976      * {tag: "input", type: "text", size: "16", autocomplete: "off"})
16977      */
16978     defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "new-password"},
16979     /**
16980      * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
16981      */
16982     hideTrigger:false,
16983
16984     /** @cfg {Boolean} grow @hide */
16985     /** @cfg {Number} growMin @hide */
16986     /** @cfg {Number} growMax @hide */
16987
16988     /**
16989      * @hide 
16990      * @method
16991      */
16992     autoSize: Roo.emptyFn,
16993     // private
16994     monitorTab : true,
16995     // private
16996     deferHeight : true,
16997
16998     
16999     actionMode : 'wrap',
17000     // private
17001     onResize : function(w, h){
17002         Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
17003         if(typeof w == 'number'){
17004             var x = w - this.trigger.getWidth();
17005             this.el.setWidth(this.adjustWidth('input', x));
17006             this.trigger.setStyle('left', x+'px');
17007         }
17008     },
17009
17010     // private
17011     adjustSize : Roo.BoxComponent.prototype.adjustSize,
17012
17013     // private
17014     getResizeEl : function(){
17015         return this.wrap;
17016     },
17017
17018     // private
17019     getPositionEl : function(){
17020         return this.wrap;
17021     },
17022
17023     // private
17024     alignErrorIcon : function(){
17025         this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
17026     },
17027
17028     // private
17029     onRender : function(ct, position){
17030         Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
17031         this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
17032         this.trigger = this.wrap.createChild(this.triggerConfig ||
17033                 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
17034         if(this.hideTrigger){
17035             this.trigger.setDisplayed(false);
17036         }
17037         this.initTrigger();
17038         if(!this.width){
17039             this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
17040         }
17041     },
17042
17043     // private
17044     initTrigger : function(){
17045         this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
17046         this.trigger.addClassOnOver('x-form-trigger-over');
17047         this.trigger.addClassOnClick('x-form-trigger-click');
17048     },
17049
17050     // private
17051     onDestroy : function(){
17052         if(this.trigger){
17053             this.trigger.removeAllListeners();
17054             this.trigger.remove();
17055         }
17056         if(this.wrap){
17057             this.wrap.remove();
17058         }
17059         Roo.form.TriggerField.superclass.onDestroy.call(this);
17060     },
17061
17062     // private
17063     onFocus : function(){
17064         Roo.form.TriggerField.superclass.onFocus.call(this);
17065         if(!this.mimicing){
17066             this.wrap.addClass('x-trigger-wrap-focus');
17067             this.mimicing = true;
17068             Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
17069             if(this.monitorTab){
17070                 this.el.on("keydown", this.checkTab, this);
17071             }
17072         }
17073     },
17074
17075     // private
17076     checkTab : function(e){
17077         if(e.getKey() == e.TAB){
17078             this.triggerBlur();
17079         }
17080     },
17081
17082     // private
17083     onBlur : function(){
17084         // do nothing
17085     },
17086
17087     // private
17088     mimicBlur : function(e, t){
17089         if(!this.wrap.contains(t) && this.validateBlur()){
17090             this.triggerBlur();
17091         }
17092     },
17093
17094     // private
17095     triggerBlur : function(){
17096         this.mimicing = false;
17097         Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
17098         if(this.monitorTab){
17099             this.el.un("keydown", this.checkTab, this);
17100         }
17101         this.wrap.removeClass('x-trigger-wrap-focus');
17102         Roo.form.TriggerField.superclass.onBlur.call(this);
17103     },
17104
17105     // private
17106     // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
17107     validateBlur : function(e, t){
17108         return true;
17109     },
17110
17111     // private
17112     onDisable : function(){
17113         Roo.form.TriggerField.superclass.onDisable.call(this);
17114         if(this.wrap){
17115             this.wrap.addClass('x-item-disabled');
17116         }
17117     },
17118
17119     // private
17120     onEnable : function(){
17121         Roo.form.TriggerField.superclass.onEnable.call(this);
17122         if(this.wrap){
17123             this.wrap.removeClass('x-item-disabled');
17124         }
17125     },
17126
17127     // private
17128     onShow : function(){
17129         var ae = this.getActionEl();
17130         
17131         if(ae){
17132             ae.dom.style.display = '';
17133             ae.dom.style.visibility = 'visible';
17134         }
17135     },
17136
17137     // private
17138     
17139     onHide : function(){
17140         var ae = this.getActionEl();
17141         ae.dom.style.display = 'none';
17142     },
17143
17144     /**
17145      * The function that should handle the trigger's click event.  This method does nothing by default until overridden
17146      * by an implementing function.
17147      * @method
17148      * @param {EventObject} e
17149      */
17150     onTriggerClick : Roo.emptyFn
17151 });
17152
17153 // TwinTriggerField is not a public class to be used directly.  It is meant as an abstract base class
17154 // to be extended by an implementing class.  For an example of implementing this class, see the custom
17155 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
17156 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
17157     initComponent : function(){
17158         Roo.form.TwinTriggerField.superclass.initComponent.call(this);
17159
17160         this.triggerConfig = {
17161             tag:'span', cls:'x-form-twin-triggers', cn:[
17162             {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
17163             {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
17164         ]};
17165     },
17166
17167     getTrigger : function(index){
17168         return this.triggers[index];
17169     },
17170
17171     initTrigger : function(){
17172         var ts = this.trigger.select('.x-form-trigger', true);
17173         this.wrap.setStyle('overflow', 'hidden');
17174         var triggerField = this;
17175         ts.each(function(t, all, index){
17176             t.hide = function(){
17177                 var w = triggerField.wrap.getWidth();
17178                 this.dom.style.display = 'none';
17179                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
17180             };
17181             t.show = function(){
17182                 var w = triggerField.wrap.getWidth();
17183                 this.dom.style.display = '';
17184                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
17185             };
17186             var triggerIndex = 'Trigger'+(index+1);
17187
17188             if(this['hide'+triggerIndex]){
17189                 t.dom.style.display = 'none';
17190             }
17191             t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
17192             t.addClassOnOver('x-form-trigger-over');
17193             t.addClassOnClick('x-form-trigger-click');
17194         }, this);
17195         this.triggers = ts.elements;
17196     },
17197
17198     onTrigger1Click : Roo.emptyFn,
17199     onTrigger2Click : Roo.emptyFn
17200 });/*
17201  * Based on:
17202  * Ext JS Library 1.1.1
17203  * Copyright(c) 2006-2007, Ext JS, LLC.
17204  *
17205  * Originally Released Under LGPL - original licence link has changed is not relivant.
17206  *
17207  * Fork - LGPL
17208  * <script type="text/javascript">
17209  */
17210  
17211 /**
17212  * @class Roo.form.TextArea
17213  * @extends Roo.form.TextField
17214  * Multiline text field.  Can be used as a direct replacement for traditional textarea fields, plus adds
17215  * support for auto-sizing.
17216  * @constructor
17217  * Creates a new TextArea
17218  * @param {Object} config Configuration options
17219  */
17220 Roo.form.TextArea = function(config){
17221     Roo.form.TextArea.superclass.constructor.call(this, config);
17222     // these are provided exchanges for backwards compat
17223     // minHeight/maxHeight were replaced by growMin/growMax to be
17224     // compatible with TextField growing config values
17225     if(this.minHeight !== undefined){
17226         this.growMin = this.minHeight;
17227     }
17228     if(this.maxHeight !== undefined){
17229         this.growMax = this.maxHeight;
17230     }
17231 };
17232
17233 Roo.extend(Roo.form.TextArea, Roo.form.TextField,  {
17234     /**
17235      * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
17236      */
17237     growMin : 60,
17238     /**
17239      * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
17240      */
17241     growMax: 1000,
17242     /**
17243      * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
17244      * in the field (equivalent to setting overflow: hidden, defaults to false)
17245      */
17246     preventScrollbars: false,
17247     /**
17248      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
17249      * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
17250      */
17251
17252     // private
17253     onRender : function(ct, position){
17254         if(!this.el){
17255             this.defaultAutoCreate = {
17256                 tag: "textarea",
17257                 style:"width:300px;height:60px;",
17258                 autocomplete: "new-password"
17259             };
17260         }
17261         Roo.form.TextArea.superclass.onRender.call(this, ct, position);
17262         if(this.grow){
17263             this.textSizeEl = Roo.DomHelper.append(document.body, {
17264                 tag: "pre", cls: "x-form-grow-sizer"
17265             });
17266             if(this.preventScrollbars){
17267                 this.el.setStyle("overflow", "hidden");
17268             }
17269             this.el.setHeight(this.growMin);
17270         }
17271     },
17272
17273     onDestroy : function(){
17274         if(this.textSizeEl){
17275             this.textSizeEl.parentNode.removeChild(this.textSizeEl);
17276         }
17277         Roo.form.TextArea.superclass.onDestroy.call(this);
17278     },
17279
17280     // private
17281     onKeyUp : function(e){
17282         if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
17283             this.autoSize();
17284         }
17285     },
17286
17287     /**
17288      * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
17289      * This only takes effect if grow = true, and fires the autosize event if the height changes.
17290      */
17291     autoSize : function(){
17292         if(!this.grow || !this.textSizeEl){
17293             return;
17294         }
17295         var el = this.el;
17296         var v = el.dom.value;
17297         var ts = this.textSizeEl;
17298
17299         ts.innerHTML = '';
17300         ts.appendChild(document.createTextNode(v));
17301         v = ts.innerHTML;
17302
17303         Roo.fly(ts).setWidth(this.el.getWidth());
17304         if(v.length < 1){
17305             v = "&#160;&#160;";
17306         }else{
17307             if(Roo.isIE){
17308                 v = v.replace(/\n/g, '<p>&#160;</p>');
17309             }
17310             v += "&#160;\n&#160;";
17311         }
17312         ts.innerHTML = v;
17313         var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
17314         if(h != this.lastHeight){
17315             this.lastHeight = h;
17316             this.el.setHeight(h);
17317             this.fireEvent("autosize", this, h);
17318         }
17319     }
17320 });/*
17321  * Based on:
17322  * Ext JS Library 1.1.1
17323  * Copyright(c) 2006-2007, Ext JS, LLC.
17324  *
17325  * Originally Released Under LGPL - original licence link has changed is not relivant.
17326  *
17327  * Fork - LGPL
17328  * <script type="text/javascript">
17329  */
17330  
17331
17332 /**
17333  * @class Roo.form.NumberField
17334  * @extends Roo.form.TextField
17335  * Numeric text field that provides automatic keystroke filtering and numeric validation.
17336  * @constructor
17337  * Creates a new NumberField
17338  * @param {Object} config Configuration options
17339  */
17340 Roo.form.NumberField = function(config){
17341     Roo.form.NumberField.superclass.constructor.call(this, config);
17342 };
17343
17344 Roo.extend(Roo.form.NumberField, Roo.form.TextField,  {
17345     /**
17346      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
17347      */
17348     fieldClass: "x-form-field x-form-num-field",
17349     /**
17350      * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
17351      */
17352     allowDecimals : true,
17353     /**
17354      * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
17355      */
17356     decimalSeparator : ".",
17357     /**
17358      * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
17359      */
17360     decimalPrecision : 2,
17361     /**
17362      * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
17363      */
17364     allowNegative : true,
17365     /**
17366      * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
17367      */
17368     minValue : Number.NEGATIVE_INFINITY,
17369     /**
17370      * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
17371      */
17372     maxValue : Number.MAX_VALUE,
17373     /**
17374      * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
17375      */
17376     minText : "The minimum value for this field is {0}",
17377     /**
17378      * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
17379      */
17380     maxText : "The maximum value for this field is {0}",
17381     /**
17382      * @cfg {String} nanText Error text to display if the value is not a valid number.  For example, this can happen
17383      * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
17384      */
17385     nanText : "{0} is not a valid number",
17386
17387     // private
17388     initEvents : function(){
17389         Roo.form.NumberField.superclass.initEvents.call(this);
17390         var allowed = "0123456789";
17391         if(this.allowDecimals){
17392             allowed += this.decimalSeparator;
17393         }
17394         if(this.allowNegative){
17395             allowed += "-";
17396         }
17397         this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
17398         var keyPress = function(e){
17399             var k = e.getKey();
17400             if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
17401                 return;
17402             }
17403             var c = e.getCharCode();
17404             if(allowed.indexOf(String.fromCharCode(c)) === -1){
17405                 e.stopEvent();
17406             }
17407         };
17408         this.el.on("keypress", keyPress, this);
17409     },
17410
17411     // private
17412     validateValue : function(value){
17413         if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
17414             return false;
17415         }
17416         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
17417              return true;
17418         }
17419         var num = this.parseValue(value);
17420         if(isNaN(num)){
17421             this.markInvalid(String.format(this.nanText, value));
17422             return false;
17423         }
17424         if(num < this.minValue){
17425             this.markInvalid(String.format(this.minText, this.minValue));
17426             return false;
17427         }
17428         if(num > this.maxValue){
17429             this.markInvalid(String.format(this.maxText, this.maxValue));
17430             return false;
17431         }
17432         return true;
17433     },
17434
17435     getValue : function(){
17436         return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
17437     },
17438
17439     // private
17440     parseValue : function(value){
17441         value = parseFloat(String(value).replace(this.decimalSeparator, "."));
17442         return isNaN(value) ? '' : value;
17443     },
17444
17445     // private
17446     fixPrecision : function(value){
17447         var nan = isNaN(value);
17448         if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
17449             return nan ? '' : value;
17450         }
17451         return parseFloat(value).toFixed(this.decimalPrecision);
17452     },
17453
17454     setValue : function(v){
17455         v = this.fixPrecision(v);
17456         Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
17457     },
17458
17459     // private
17460     decimalPrecisionFcn : function(v){
17461         return Math.floor(v);
17462     },
17463
17464     beforeBlur : function(){
17465         var v = this.parseValue(this.getRawValue());
17466         if(v){
17467             this.setValue(v);
17468         }
17469     }
17470 });/*
17471  * Based on:
17472  * Ext JS Library 1.1.1
17473  * Copyright(c) 2006-2007, Ext JS, LLC.
17474  *
17475  * Originally Released Under LGPL - original licence link has changed is not relivant.
17476  *
17477  * Fork - LGPL
17478  * <script type="text/javascript">
17479  */
17480  
17481 /**
17482  * @class Roo.form.DateField
17483  * @extends Roo.form.TriggerField
17484  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
17485 * @constructor
17486 * Create a new DateField
17487 * @param {Object} config
17488  */
17489 Roo.form.DateField = function(config)
17490 {
17491     Roo.form.DateField.superclass.constructor.call(this, config);
17492     
17493       this.addEvents({
17494          
17495         /**
17496          * @event select
17497          * Fires when a date is selected
17498              * @param {Roo.form.DateField} combo This combo box
17499              * @param {Date} date The date selected
17500              */
17501         'select' : true
17502          
17503     });
17504     
17505     
17506     if(typeof this.minValue == "string") {
17507         this.minValue = this.parseDate(this.minValue);
17508     }
17509     if(typeof this.maxValue == "string") {
17510         this.maxValue = this.parseDate(this.maxValue);
17511     }
17512     this.ddMatch = null;
17513     if(this.disabledDates){
17514         var dd = this.disabledDates;
17515         var re = "(?:";
17516         for(var i = 0; i < dd.length; i++){
17517             re += dd[i];
17518             if(i != dd.length-1) {
17519                 re += "|";
17520             }
17521         }
17522         this.ddMatch = new RegExp(re + ")");
17523     }
17524 };
17525
17526 Roo.extend(Roo.form.DateField, Roo.form.TriggerField,  {
17527     /**
17528      * @cfg {String} format
17529      * The default date format string which can be overriden for localization support.  The format must be
17530      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
17531      */
17532     format : "m/d/y",
17533     /**
17534      * @cfg {String} altFormats
17535      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
17536      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
17537      */
17538     altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
17539     /**
17540      * @cfg {Array} disabledDays
17541      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
17542      */
17543     disabledDays : null,
17544     /**
17545      * @cfg {String} disabledDaysText
17546      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
17547      */
17548     disabledDaysText : "Disabled",
17549     /**
17550      * @cfg {Array} disabledDates
17551      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
17552      * expression so they are very powerful. Some examples:
17553      * <ul>
17554      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
17555      * <li>["03/08", "09/16"] would disable those days for every year</li>
17556      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
17557      * <li>["03/../2006"] would disable every day in March 2006</li>
17558      * <li>["^03"] would disable every day in every March</li>
17559      * </ul>
17560      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
17561      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
17562      */
17563     disabledDates : null,
17564     /**
17565      * @cfg {String} disabledDatesText
17566      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
17567      */
17568     disabledDatesText : "Disabled",
17569     /**
17570      * @cfg {Date/String} minValue
17571      * The minimum allowed date. Can be either a Javascript date object or a string date in a
17572      * valid format (defaults to null).
17573      */
17574     minValue : null,
17575     /**
17576      * @cfg {Date/String} maxValue
17577      * The maximum allowed date. Can be either a Javascript date object or a string date in a
17578      * valid format (defaults to null).
17579      */
17580     maxValue : null,
17581     /**
17582      * @cfg {String} minText
17583      * The error text to display when the date in the cell is before minValue (defaults to
17584      * 'The date in this field must be after {minValue}').
17585      */
17586     minText : "The date in this field must be equal to or after {0}",
17587     /**
17588      * @cfg {String} maxText
17589      * The error text to display when the date in the cell is after maxValue (defaults to
17590      * 'The date in this field must be before {maxValue}').
17591      */
17592     maxText : "The date in this field must be equal to or before {0}",
17593     /**
17594      * @cfg {String} invalidText
17595      * The error text to display when the date in the field is invalid (defaults to
17596      * '{value} is not a valid date - it must be in the format {format}').
17597      */
17598     invalidText : "{0} is not a valid date - it must be in the format {1}",
17599     /**
17600      * @cfg {String} triggerClass
17601      * An additional CSS class used to style the trigger button.  The trigger will always get the
17602      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
17603      * which displays a calendar icon).
17604      */
17605     triggerClass : 'x-form-date-trigger',
17606     
17607
17608     /**
17609      * @cfg {Boolean} useIso
17610      * if enabled, then the date field will use a hidden field to store the 
17611      * real value as iso formated date. default (false)
17612      */ 
17613     useIso : false,
17614     /**
17615      * @cfg {String/Object} autoCreate
17616      * A DomHelper element spec, or true for a default element spec (defaults to
17617      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
17618      */ 
17619     // private
17620     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
17621     
17622     // private
17623     hiddenField: false,
17624     
17625     onRender : function(ct, position)
17626     {
17627         Roo.form.DateField.superclass.onRender.call(this, ct, position);
17628         if (this.useIso) {
17629             //this.el.dom.removeAttribute('name'); 
17630             Roo.log("Changing name?");
17631             this.el.dom.setAttribute('name', this.name + '____hidden___' ); 
17632             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
17633                     'before', true);
17634             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
17635             // prevent input submission
17636             this.hiddenName = this.name;
17637         }
17638             
17639             
17640     },
17641     
17642     // private
17643     validateValue : function(value)
17644     {
17645         value = this.formatDate(value);
17646         if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
17647             Roo.log('super failed');
17648             return false;
17649         }
17650         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
17651              return true;
17652         }
17653         var svalue = value;
17654         value = this.parseDate(value);
17655         if(!value){
17656             Roo.log('parse date failed' + svalue);
17657             this.markInvalid(String.format(this.invalidText, svalue, this.format));
17658             return false;
17659         }
17660         var time = value.getTime();
17661         if(this.minValue && time < this.minValue.getTime()){
17662             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
17663             return false;
17664         }
17665         if(this.maxValue && time > this.maxValue.getTime()){
17666             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
17667             return false;
17668         }
17669         if(this.disabledDays){
17670             var day = value.getDay();
17671             for(var i = 0; i < this.disabledDays.length; i++) {
17672                 if(day === this.disabledDays[i]){
17673                     this.markInvalid(this.disabledDaysText);
17674                     return false;
17675                 }
17676             }
17677         }
17678         var fvalue = this.formatDate(value);
17679         if(this.ddMatch && this.ddMatch.test(fvalue)){
17680             this.markInvalid(String.format(this.disabledDatesText, fvalue));
17681             return false;
17682         }
17683         return true;
17684     },
17685
17686     // private
17687     // Provides logic to override the default TriggerField.validateBlur which just returns true
17688     validateBlur : function(){
17689         return !this.menu || !this.menu.isVisible();
17690     },
17691     
17692     getName: function()
17693     {
17694         // returns hidden if it's set..
17695         if (!this.rendered) {return ''};
17696         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
17697         
17698     },
17699
17700     /**
17701      * Returns the current date value of the date field.
17702      * @return {Date} The date value
17703      */
17704     getValue : function(){
17705         
17706         return  this.hiddenField ?
17707                 this.hiddenField.value :
17708                 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
17709     },
17710
17711     /**
17712      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
17713      * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
17714      * (the default format used is "m/d/y").
17715      * <br />Usage:
17716      * <pre><code>
17717 //All of these calls set the same date value (May 4, 2006)
17718
17719 //Pass a date object:
17720 var dt = new Date('5/4/06');
17721 dateField.setValue(dt);
17722
17723 //Pass a date string (default format):
17724 dateField.setValue('5/4/06');
17725
17726 //Pass a date string (custom format):
17727 dateField.format = 'Y-m-d';
17728 dateField.setValue('2006-5-4');
17729 </code></pre>
17730      * @param {String/Date} date The date or valid date string
17731      */
17732     setValue : function(date){
17733         if (this.hiddenField) {
17734             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
17735         }
17736         Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
17737         // make sure the value field is always stored as a date..
17738         this.value = this.parseDate(date);
17739         
17740         
17741     },
17742
17743     // private
17744     parseDate : function(value){
17745         if(!value || value instanceof Date){
17746             return value;
17747         }
17748         var v = Date.parseDate(value, this.format);
17749          if (!v && this.useIso) {
17750             v = Date.parseDate(value, 'Y-m-d');
17751         }
17752         if(!v && this.altFormats){
17753             if(!this.altFormatsArray){
17754                 this.altFormatsArray = this.altFormats.split("|");
17755             }
17756             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
17757                 v = Date.parseDate(value, this.altFormatsArray[i]);
17758             }
17759         }
17760         return v;
17761     },
17762
17763     // private
17764     formatDate : function(date, fmt){
17765         return (!date || !(date instanceof Date)) ?
17766                date : date.dateFormat(fmt || this.format);
17767     },
17768
17769     // private
17770     menuListeners : {
17771         select: function(m, d){
17772             
17773             this.setValue(d);
17774             this.fireEvent('select', this, d);
17775         },
17776         show : function(){ // retain focus styling
17777             this.onFocus();
17778         },
17779         hide : function(){
17780             this.focus.defer(10, this);
17781             var ml = this.menuListeners;
17782             this.menu.un("select", ml.select,  this);
17783             this.menu.un("show", ml.show,  this);
17784             this.menu.un("hide", ml.hide,  this);
17785         }
17786     },
17787
17788     // private
17789     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
17790     onTriggerClick : function(){
17791         if(this.disabled){
17792             return;
17793         }
17794         if(this.menu == null){
17795             this.menu = new Roo.menu.DateMenu();
17796         }
17797         Roo.apply(this.menu.picker,  {
17798             showClear: this.allowBlank,
17799             minDate : this.minValue,
17800             maxDate : this.maxValue,
17801             disabledDatesRE : this.ddMatch,
17802             disabledDatesText : this.disabledDatesText,
17803             disabledDays : this.disabledDays,
17804             disabledDaysText : this.disabledDaysText,
17805             format : this.useIso ? 'Y-m-d' : this.format,
17806             minText : String.format(this.minText, this.formatDate(this.minValue)),
17807             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
17808         });
17809         this.menu.on(Roo.apply({}, this.menuListeners, {
17810             scope:this
17811         }));
17812         this.menu.picker.setValue(this.getValue() || new Date());
17813         this.menu.show(this.el, "tl-bl?");
17814     },
17815
17816     beforeBlur : function(){
17817         var v = this.parseDate(this.getRawValue());
17818         if(v){
17819             this.setValue(v);
17820         }
17821     },
17822
17823     /*@
17824      * overide
17825      * 
17826      */
17827     isDirty : function() {
17828         if(this.disabled) {
17829             return false;
17830         }
17831         
17832         if(typeof(this.startValue) === 'undefined'){
17833             return false;
17834         }
17835         
17836         return String(this.getValue()) !== String(this.startValue);
17837         
17838     },
17839     // @overide
17840     cleanLeadingSpace : function(e)
17841     {
17842        return;
17843     }
17844     
17845 });/*
17846  * Based on:
17847  * Ext JS Library 1.1.1
17848  * Copyright(c) 2006-2007, Ext JS, LLC.
17849  *
17850  * Originally Released Under LGPL - original licence link has changed is not relivant.
17851  *
17852  * Fork - LGPL
17853  * <script type="text/javascript">
17854  */
17855  
17856 /**
17857  * @class Roo.form.MonthField
17858  * @extends Roo.form.TriggerField
17859  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
17860 * @constructor
17861 * Create a new MonthField
17862 * @param {Object} config
17863  */
17864 Roo.form.MonthField = function(config){
17865     
17866     Roo.form.MonthField.superclass.constructor.call(this, config);
17867     
17868       this.addEvents({
17869          
17870         /**
17871          * @event select
17872          * Fires when a date is selected
17873              * @param {Roo.form.MonthFieeld} combo This combo box
17874              * @param {Date} date The date selected
17875              */
17876         'select' : true
17877          
17878     });
17879     
17880     
17881     if(typeof this.minValue == "string") {
17882         this.minValue = this.parseDate(this.minValue);
17883     }
17884     if(typeof this.maxValue == "string") {
17885         this.maxValue = this.parseDate(this.maxValue);
17886     }
17887     this.ddMatch = null;
17888     if(this.disabledDates){
17889         var dd = this.disabledDates;
17890         var re = "(?:";
17891         for(var i = 0; i < dd.length; i++){
17892             re += dd[i];
17893             if(i != dd.length-1) {
17894                 re += "|";
17895             }
17896         }
17897         this.ddMatch = new RegExp(re + ")");
17898     }
17899 };
17900
17901 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField,  {
17902     /**
17903      * @cfg {String} format
17904      * The default date format string which can be overriden for localization support.  The format must be
17905      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
17906      */
17907     format : "M Y",
17908     /**
17909      * @cfg {String} altFormats
17910      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
17911      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
17912      */
17913     altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
17914     /**
17915      * @cfg {Array} disabledDays
17916      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
17917      */
17918     disabledDays : [0,1,2,3,4,5,6],
17919     /**
17920      * @cfg {String} disabledDaysText
17921      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
17922      */
17923     disabledDaysText : "Disabled",
17924     /**
17925      * @cfg {Array} disabledDates
17926      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
17927      * expression so they are very powerful. Some examples:
17928      * <ul>
17929      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
17930      * <li>["03/08", "09/16"] would disable those days for every year</li>
17931      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
17932      * <li>["03/../2006"] would disable every day in March 2006</li>
17933      * <li>["^03"] would disable every day in every March</li>
17934      * </ul>
17935      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
17936      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
17937      */
17938     disabledDates : null,
17939     /**
17940      * @cfg {String} disabledDatesText
17941      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
17942      */
17943     disabledDatesText : "Disabled",
17944     /**
17945      * @cfg {Date/String} minValue
17946      * The minimum allowed date. Can be either a Javascript date object or a string date in a
17947      * valid format (defaults to null).
17948      */
17949     minValue : null,
17950     /**
17951      * @cfg {Date/String} maxValue
17952      * The maximum allowed date. Can be either a Javascript date object or a string date in a
17953      * valid format (defaults to null).
17954      */
17955     maxValue : null,
17956     /**
17957      * @cfg {String} minText
17958      * The error text to display when the date in the cell is before minValue (defaults to
17959      * 'The date in this field must be after {minValue}').
17960      */
17961     minText : "The date in this field must be equal to or after {0}",
17962     /**
17963      * @cfg {String} maxTextf
17964      * The error text to display when the date in the cell is after maxValue (defaults to
17965      * 'The date in this field must be before {maxValue}').
17966      */
17967     maxText : "The date in this field must be equal to or before {0}",
17968     /**
17969      * @cfg {String} invalidText
17970      * The error text to display when the date in the field is invalid (defaults to
17971      * '{value} is not a valid date - it must be in the format {format}').
17972      */
17973     invalidText : "{0} is not a valid date - it must be in the format {1}",
17974     /**
17975      * @cfg {String} triggerClass
17976      * An additional CSS class used to style the trigger button.  The trigger will always get the
17977      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
17978      * which displays a calendar icon).
17979      */
17980     triggerClass : 'x-form-date-trigger',
17981     
17982
17983     /**
17984      * @cfg {Boolean} useIso
17985      * if enabled, then the date field will use a hidden field to store the 
17986      * real value as iso formated date. default (true)
17987      */ 
17988     useIso : true,
17989     /**
17990      * @cfg {String/Object} autoCreate
17991      * A DomHelper element spec, or true for a default element spec (defaults to
17992      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
17993      */ 
17994     // private
17995     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
17996     
17997     // private
17998     hiddenField: false,
17999     
18000     hideMonthPicker : false,
18001     
18002     onRender : function(ct, position)
18003     {
18004         Roo.form.MonthField.superclass.onRender.call(this, ct, position);
18005         if (this.useIso) {
18006             this.el.dom.removeAttribute('name'); 
18007             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
18008                     'before', true);
18009             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
18010             // prevent input submission
18011             this.hiddenName = this.name;
18012         }
18013             
18014             
18015     },
18016     
18017     // private
18018     validateValue : function(value)
18019     {
18020         value = this.formatDate(value);
18021         if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
18022             return false;
18023         }
18024         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
18025              return true;
18026         }
18027         var svalue = value;
18028         value = this.parseDate(value);
18029         if(!value){
18030             this.markInvalid(String.format(this.invalidText, svalue, this.format));
18031             return false;
18032         }
18033         var time = value.getTime();
18034         if(this.minValue && time < this.minValue.getTime()){
18035             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
18036             return false;
18037         }
18038         if(this.maxValue && time > this.maxValue.getTime()){
18039             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
18040             return false;
18041         }
18042         /*if(this.disabledDays){
18043             var day = value.getDay();
18044             for(var i = 0; i < this.disabledDays.length; i++) {
18045                 if(day === this.disabledDays[i]){
18046                     this.markInvalid(this.disabledDaysText);
18047                     return false;
18048                 }
18049             }
18050         }
18051         */
18052         var fvalue = this.formatDate(value);
18053         /*if(this.ddMatch && this.ddMatch.test(fvalue)){
18054             this.markInvalid(String.format(this.disabledDatesText, fvalue));
18055             return false;
18056         }
18057         */
18058         return true;
18059     },
18060
18061     // private
18062     // Provides logic to override the default TriggerField.validateBlur which just returns true
18063     validateBlur : function(){
18064         return !this.menu || !this.menu.isVisible();
18065     },
18066
18067     /**
18068      * Returns the current date value of the date field.
18069      * @return {Date} The date value
18070      */
18071     getValue : function(){
18072         
18073         
18074         
18075         return  this.hiddenField ?
18076                 this.hiddenField.value :
18077                 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
18078     },
18079
18080     /**
18081      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
18082      * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
18083      * (the default format used is "m/d/y").
18084      * <br />Usage:
18085      * <pre><code>
18086 //All of these calls set the same date value (May 4, 2006)
18087
18088 //Pass a date object:
18089 var dt = new Date('5/4/06');
18090 monthField.setValue(dt);
18091
18092 //Pass a date string (default format):
18093 monthField.setValue('5/4/06');
18094
18095 //Pass a date string (custom format):
18096 monthField.format = 'Y-m-d';
18097 monthField.setValue('2006-5-4');
18098 </code></pre>
18099      * @param {String/Date} date The date or valid date string
18100      */
18101     setValue : function(date){
18102         Roo.log('month setValue' + date);
18103         // can only be first of month..
18104         
18105         var val = this.parseDate(date);
18106         
18107         if (this.hiddenField) {
18108             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
18109         }
18110         Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
18111         this.value = this.parseDate(date);
18112     },
18113
18114     // private
18115     parseDate : function(value){
18116         if(!value || value instanceof Date){
18117             value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
18118             return value;
18119         }
18120         var v = Date.parseDate(value, this.format);
18121         if (!v && this.useIso) {
18122             v = Date.parseDate(value, 'Y-m-d');
18123         }
18124         if (v) {
18125             // 
18126             v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
18127         }
18128         
18129         
18130         if(!v && this.altFormats){
18131             if(!this.altFormatsArray){
18132                 this.altFormatsArray = this.altFormats.split("|");
18133             }
18134             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
18135                 v = Date.parseDate(value, this.altFormatsArray[i]);
18136             }
18137         }
18138         return v;
18139     },
18140
18141     // private
18142     formatDate : function(date, fmt){
18143         return (!date || !(date instanceof Date)) ?
18144                date : date.dateFormat(fmt || this.format);
18145     },
18146
18147     // private
18148     menuListeners : {
18149         select: function(m, d){
18150             this.setValue(d);
18151             this.fireEvent('select', this, d);
18152         },
18153         show : function(){ // retain focus styling
18154             this.onFocus();
18155         },
18156         hide : function(){
18157             this.focus.defer(10, this);
18158             var ml = this.menuListeners;
18159             this.menu.un("select", ml.select,  this);
18160             this.menu.un("show", ml.show,  this);
18161             this.menu.un("hide", ml.hide,  this);
18162         }
18163     },
18164     // private
18165     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
18166     onTriggerClick : function(){
18167         if(this.disabled){
18168             return;
18169         }
18170         if(this.menu == null){
18171             this.menu = new Roo.menu.DateMenu();
18172            
18173         }
18174         
18175         Roo.apply(this.menu.picker,  {
18176             
18177             showClear: this.allowBlank,
18178             minDate : this.minValue,
18179             maxDate : this.maxValue,
18180             disabledDatesRE : this.ddMatch,
18181             disabledDatesText : this.disabledDatesText,
18182             
18183             format : this.useIso ? 'Y-m-d' : this.format,
18184             minText : String.format(this.minText, this.formatDate(this.minValue)),
18185             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
18186             
18187         });
18188          this.menu.on(Roo.apply({}, this.menuListeners, {
18189             scope:this
18190         }));
18191        
18192         
18193         var m = this.menu;
18194         var p = m.picker;
18195         
18196         // hide month picker get's called when we called by 'before hide';
18197         
18198         var ignorehide = true;
18199         p.hideMonthPicker  = function(disableAnim){
18200             if (ignorehide) {
18201                 return;
18202             }
18203              if(this.monthPicker){
18204                 Roo.log("hideMonthPicker called");
18205                 if(disableAnim === true){
18206                     this.monthPicker.hide();
18207                 }else{
18208                     this.monthPicker.slideOut('t', {duration:.2});
18209                     p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
18210                     p.fireEvent("select", this, this.value);
18211                     m.hide();
18212                 }
18213             }
18214         }
18215         
18216         Roo.log('picker set value');
18217         Roo.log(this.getValue());
18218         p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
18219         m.show(this.el, 'tl-bl?');
18220         ignorehide  = false;
18221         // this will trigger hideMonthPicker..
18222         
18223         
18224         // hidden the day picker
18225         Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
18226         
18227         
18228         
18229       
18230         
18231         p.showMonthPicker.defer(100, p);
18232     
18233         
18234        
18235     },
18236
18237     beforeBlur : function(){
18238         var v = this.parseDate(this.getRawValue());
18239         if(v){
18240             this.setValue(v);
18241         }
18242     }
18243
18244     /** @cfg {Boolean} grow @hide */
18245     /** @cfg {Number} growMin @hide */
18246     /** @cfg {Number} growMax @hide */
18247     /**
18248      * @hide
18249      * @method autoSize
18250      */
18251 });/*
18252  * Based on:
18253  * Ext JS Library 1.1.1
18254  * Copyright(c) 2006-2007, Ext JS, LLC.
18255  *
18256  * Originally Released Under LGPL - original licence link has changed is not relivant.
18257  *
18258  * Fork - LGPL
18259  * <script type="text/javascript">
18260  */
18261  
18262
18263 /**
18264  * @class Roo.form.ComboBox
18265  * @extends Roo.form.TriggerField
18266  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
18267  * @constructor
18268  * Create a new ComboBox.
18269  * @param {Object} config Configuration options
18270  */
18271 Roo.form.ComboBox = function(config){
18272     Roo.form.ComboBox.superclass.constructor.call(this, config);
18273     this.addEvents({
18274         /**
18275          * @event expand
18276          * Fires when the dropdown list is expanded
18277              * @param {Roo.form.ComboBox} combo This combo box
18278              */
18279         'expand' : true,
18280         /**
18281          * @event collapse
18282          * Fires when the dropdown list is collapsed
18283              * @param {Roo.form.ComboBox} combo This combo box
18284              */
18285         'collapse' : true,
18286         /**
18287          * @event beforeselect
18288          * Fires before a list item is selected. Return false to cancel the selection.
18289              * @param {Roo.form.ComboBox} combo This combo box
18290              * @param {Roo.data.Record} record The data record returned from the underlying store
18291              * @param {Number} index The index of the selected item in the dropdown list
18292              */
18293         'beforeselect' : true,
18294         /**
18295          * @event select
18296          * Fires when a list item is selected
18297              * @param {Roo.form.ComboBox} combo This combo box
18298              * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
18299              * @param {Number} index The index of the selected item in the dropdown list
18300              */
18301         'select' : true,
18302         /**
18303          * @event beforequery
18304          * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
18305          * The event object passed has these properties:
18306              * @param {Roo.form.ComboBox} combo This combo box
18307              * @param {String} query The query
18308              * @param {Boolean} forceAll true to force "all" query
18309              * @param {Boolean} cancel true to cancel the query
18310              * @param {Object} e The query event object
18311              */
18312         'beforequery': true,
18313          /**
18314          * @event add
18315          * Fires when the 'add' icon is pressed (add a listener to enable add button)
18316              * @param {Roo.form.ComboBox} combo This combo box
18317              */
18318         'add' : true,
18319         /**
18320          * @event edit
18321          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
18322              * @param {Roo.form.ComboBox} combo This combo box
18323              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
18324              */
18325         'edit' : true
18326         
18327         
18328     });
18329     if(this.transform){
18330         this.allowDomMove = false;
18331         var s = Roo.getDom(this.transform);
18332         if(!this.hiddenName){
18333             this.hiddenName = s.name;
18334         }
18335         if(!this.store){
18336             this.mode = 'local';
18337             var d = [], opts = s.options;
18338             for(var i = 0, len = opts.length;i < len; i++){
18339                 var o = opts[i];
18340                 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
18341                 if(o.selected) {
18342                     this.value = value;
18343                 }
18344                 d.push([value, o.text]);
18345             }
18346             this.store = new Roo.data.SimpleStore({
18347                 'id': 0,
18348                 fields: ['value', 'text'],
18349                 data : d
18350             });
18351             this.valueField = 'value';
18352             this.displayField = 'text';
18353         }
18354         s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
18355         if(!this.lazyRender){
18356             this.target = true;
18357             this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
18358             s.parentNode.removeChild(s); // remove it
18359             this.render(this.el.parentNode);
18360         }else{
18361             s.parentNode.removeChild(s); // remove it
18362         }
18363
18364     }
18365     if (this.store) {
18366         this.store = Roo.factory(this.store, Roo.data);
18367     }
18368     
18369     this.selectedIndex = -1;
18370     if(this.mode == 'local'){
18371         if(config.queryDelay === undefined){
18372             this.queryDelay = 10;
18373         }
18374         if(config.minChars === undefined){
18375             this.minChars = 0;
18376         }
18377     }
18378 };
18379
18380 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
18381     /**
18382      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
18383      */
18384     /**
18385      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
18386      * rendering into an Roo.Editor, defaults to false)
18387      */
18388     /**
18389      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
18390      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
18391      */
18392     /**
18393      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
18394      */
18395     /**
18396      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
18397      * the dropdown list (defaults to undefined, with no header element)
18398      */
18399
18400      /**
18401      * @cfg {String/Roo.Template} tpl The template to use to render the output
18402      */
18403      
18404     // private
18405     defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
18406     /**
18407      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
18408      */
18409     listWidth: undefined,
18410     /**
18411      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
18412      * mode = 'remote' or 'text' if mode = 'local')
18413      */
18414     displayField: undefined,
18415     /**
18416      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
18417      * mode = 'remote' or 'value' if mode = 'local'). 
18418      * Note: use of a valueField requires the user make a selection
18419      * in order for a value to be mapped.
18420      */
18421     valueField: undefined,
18422     
18423     
18424     /**
18425      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
18426      * field's data value (defaults to the underlying DOM element's name)
18427      */
18428     hiddenName: undefined,
18429     /**
18430      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
18431      */
18432     listClass: '',
18433     /**
18434      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
18435      */
18436     selectedClass: 'x-combo-selected',
18437     /**
18438      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
18439      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
18440      * which displays a downward arrow icon).
18441      */
18442     triggerClass : 'x-form-arrow-trigger',
18443     /**
18444      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
18445      */
18446     shadow:'sides',
18447     /**
18448      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
18449      * anchor positions (defaults to 'tl-bl')
18450      */
18451     listAlign: 'tl-bl?',
18452     /**
18453      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
18454      */
18455     maxHeight: 300,
18456     /**
18457      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
18458      * query specified by the allQuery config option (defaults to 'query')
18459      */
18460     triggerAction: 'query',
18461     /**
18462      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
18463      * (defaults to 4, does not apply if editable = false)
18464      */
18465     minChars : 4,
18466     /**
18467      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
18468      * delay (typeAheadDelay) if it matches a known value (defaults to false)
18469      */
18470     typeAhead: false,
18471     /**
18472      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
18473      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
18474      */
18475     queryDelay: 500,
18476     /**
18477      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
18478      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
18479      */
18480     pageSize: 0,
18481     /**
18482      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
18483      * when editable = true (defaults to false)
18484      */
18485     selectOnFocus:false,
18486     /**
18487      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
18488      */
18489     queryParam: 'query',
18490     /**
18491      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
18492      * when mode = 'remote' (defaults to 'Loading...')
18493      */
18494     loadingText: 'Loading...',
18495     /**
18496      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
18497      */
18498     resizable: false,
18499     /**
18500      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
18501      */
18502     handleHeight : 8,
18503     /**
18504      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
18505      * traditional select (defaults to true)
18506      */
18507     editable: true,
18508     /**
18509      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
18510      */
18511     allQuery: '',
18512     /**
18513      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
18514      */
18515     mode: 'remote',
18516     /**
18517      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
18518      * listWidth has a higher value)
18519      */
18520     minListWidth : 70,
18521     /**
18522      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
18523      * allow the user to set arbitrary text into the field (defaults to false)
18524      */
18525     forceSelection:false,
18526     /**
18527      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
18528      * if typeAhead = true (defaults to 250)
18529      */
18530     typeAheadDelay : 250,
18531     /**
18532      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
18533      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
18534      */
18535     valueNotFoundText : undefined,
18536     /**
18537      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
18538      */
18539     blockFocus : false,
18540     
18541     /**
18542      * @cfg {Boolean} disableClear Disable showing of clear button.
18543      */
18544     disableClear : false,
18545     /**
18546      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
18547      */
18548     alwaysQuery : false,
18549     
18550     //private
18551     addicon : false,
18552     editicon: false,
18553     
18554     // element that contains real text value.. (when hidden is used..)
18555      
18556     // private
18557     onRender : function(ct, position)
18558     {
18559         Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
18560         
18561         if(this.hiddenName){
18562             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id:  (this.hiddenId||this.hiddenName)},
18563                     'before', true);
18564             this.hiddenField.value =
18565                 this.hiddenValue !== undefined ? this.hiddenValue :
18566                 this.value !== undefined ? this.value : '';
18567
18568             // prevent input submission
18569             this.el.dom.removeAttribute('name');
18570              
18571              
18572         }
18573         
18574         if(Roo.isGecko){
18575             this.el.dom.setAttribute('autocomplete', 'off');
18576         }
18577
18578         var cls = 'x-combo-list';
18579
18580         this.list = new Roo.Layer({
18581             shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
18582         });
18583
18584         var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
18585         this.list.setWidth(lw);
18586         this.list.swallowEvent('mousewheel');
18587         this.assetHeight = 0;
18588
18589         if(this.title){
18590             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
18591             this.assetHeight += this.header.getHeight();
18592         }
18593
18594         this.innerList = this.list.createChild({cls:cls+'-inner'});
18595         this.innerList.on('mouseover', this.onViewOver, this);
18596         this.innerList.on('mousemove', this.onViewMove, this);
18597         this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
18598         
18599         if(this.allowBlank && !this.pageSize && !this.disableClear){
18600             this.footer = this.list.createChild({cls:cls+'-ft'});
18601             this.pageTb = new Roo.Toolbar(this.footer);
18602            
18603         }
18604         if(this.pageSize){
18605             this.footer = this.list.createChild({cls:cls+'-ft'});
18606             this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
18607                     {pageSize: this.pageSize});
18608             
18609         }
18610         
18611         if (this.pageTb && this.allowBlank && !this.disableClear) {
18612             var _this = this;
18613             this.pageTb.add(new Roo.Toolbar.Fill(), {
18614                 cls: 'x-btn-icon x-btn-clear',
18615                 text: '&#160;',
18616                 handler: function()
18617                 {
18618                     _this.collapse();
18619                     _this.clearValue();
18620                     _this.onSelect(false, -1);
18621                 }
18622             });
18623         }
18624         if (this.footer) {
18625             this.assetHeight += this.footer.getHeight();
18626         }
18627         
18628
18629         if(!this.tpl){
18630             this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
18631         }
18632
18633         this.view = new Roo.View(this.innerList, this.tpl, {
18634             singleSelect:true,
18635             store: this.store,
18636             selectedClass: this.selectedClass
18637         });
18638
18639         this.view.on('click', this.onViewClick, this);
18640
18641         this.store.on('beforeload', this.onBeforeLoad, this);
18642         this.store.on('load', this.onLoad, this);
18643         this.store.on('loadexception', this.onLoadException, this);
18644
18645         if(this.resizable){
18646             this.resizer = new Roo.Resizable(this.list,  {
18647                pinned:true, handles:'se'
18648             });
18649             this.resizer.on('resize', function(r, w, h){
18650                 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
18651                 this.listWidth = w;
18652                 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
18653                 this.restrictHeight();
18654             }, this);
18655             this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
18656         }
18657         if(!this.editable){
18658             this.editable = true;
18659             this.setEditable(false);
18660         }  
18661         
18662         
18663         if (typeof(this.events.add.listeners) != 'undefined') {
18664             
18665             this.addicon = this.wrap.createChild(
18666                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });  
18667        
18668             this.addicon.on('click', function(e) {
18669                 this.fireEvent('add', this);
18670             }, this);
18671         }
18672         if (typeof(this.events.edit.listeners) != 'undefined') {
18673             
18674             this.editicon = this.wrap.createChild(
18675                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });  
18676             if (this.addicon) {
18677                 this.editicon.setStyle('margin-left', '40px');
18678             }
18679             this.editicon.on('click', function(e) {
18680                 
18681                 // we fire even  if inothing is selected..
18682                 this.fireEvent('edit', this, this.lastData );
18683                 
18684             }, this);
18685         }
18686         
18687         
18688         
18689     },
18690
18691     // private
18692     initEvents : function(){
18693         Roo.form.ComboBox.superclass.initEvents.call(this);
18694
18695         this.keyNav = new Roo.KeyNav(this.el, {
18696             "up" : function(e){
18697                 this.inKeyMode = true;
18698                 this.selectPrev();
18699             },
18700
18701             "down" : function(e){
18702                 if(!this.isExpanded()){
18703                     this.onTriggerClick();
18704                 }else{
18705                     this.inKeyMode = true;
18706                     this.selectNext();
18707                 }
18708             },
18709
18710             "enter" : function(e){
18711                 this.onViewClick();
18712                 //return true;
18713             },
18714
18715             "esc" : function(e){
18716                 this.collapse();
18717             },
18718
18719             "tab" : function(e){
18720                 this.onViewClick(false);
18721                 this.fireEvent("specialkey", this, e);
18722                 return true;
18723             },
18724
18725             scope : this,
18726
18727             doRelay : function(foo, bar, hname){
18728                 if(hname == 'down' || this.scope.isExpanded()){
18729                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
18730                 }
18731                 return true;
18732             },
18733
18734             forceKeyDown: true
18735         });
18736         this.queryDelay = Math.max(this.queryDelay || 10,
18737                 this.mode == 'local' ? 10 : 250);
18738         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
18739         if(this.typeAhead){
18740             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
18741         }
18742         if(this.editable !== false){
18743             this.el.on("keyup", this.onKeyUp, this);
18744         }
18745         if(this.forceSelection){
18746             this.on('blur', this.doForce, this);
18747         }
18748     },
18749
18750     onDestroy : function(){
18751         if(this.view){
18752             this.view.setStore(null);
18753             this.view.el.removeAllListeners();
18754             this.view.el.remove();
18755             this.view.purgeListeners();
18756         }
18757         if(this.list){
18758             this.list.destroy();
18759         }
18760         if(this.store){
18761             this.store.un('beforeload', this.onBeforeLoad, this);
18762             this.store.un('load', this.onLoad, this);
18763             this.store.un('loadexception', this.onLoadException, this);
18764         }
18765         Roo.form.ComboBox.superclass.onDestroy.call(this);
18766     },
18767
18768     // private
18769     fireKey : function(e){
18770         if(e.isNavKeyPress() && !this.list.isVisible()){
18771             this.fireEvent("specialkey", this, e);
18772         }
18773     },
18774
18775     // private
18776     onResize: function(w, h){
18777         Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
18778         
18779         if(typeof w != 'number'){
18780             // we do not handle it!?!?
18781             return;
18782         }
18783         var tw = this.trigger.getWidth();
18784         tw += this.addicon ? this.addicon.getWidth() : 0;
18785         tw += this.editicon ? this.editicon.getWidth() : 0;
18786         var x = w - tw;
18787         this.el.setWidth( this.adjustWidth('input', x));
18788             
18789         this.trigger.setStyle('left', x+'px');
18790         
18791         if(this.list && this.listWidth === undefined){
18792             var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
18793             this.list.setWidth(lw);
18794             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
18795         }
18796         
18797     
18798         
18799     },
18800
18801     /**
18802      * Allow or prevent the user from directly editing the field text.  If false is passed,
18803      * the user will only be able to select from the items defined in the dropdown list.  This method
18804      * is the runtime equivalent of setting the 'editable' config option at config time.
18805      * @param {Boolean} value True to allow the user to directly edit the field text
18806      */
18807     setEditable : function(value){
18808         if(value == this.editable){
18809             return;
18810         }
18811         this.editable = value;
18812         if(!value){
18813             this.el.dom.setAttribute('readOnly', true);
18814             this.el.on('mousedown', this.onTriggerClick,  this);
18815             this.el.addClass('x-combo-noedit');
18816         }else{
18817             this.el.dom.setAttribute('readOnly', false);
18818             this.el.un('mousedown', this.onTriggerClick,  this);
18819             this.el.removeClass('x-combo-noedit');
18820         }
18821     },
18822
18823     // private
18824     onBeforeLoad : function(){
18825         if(!this.hasFocus){
18826             return;
18827         }
18828         this.innerList.update(this.loadingText ?
18829                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
18830         this.restrictHeight();
18831         this.selectedIndex = -1;
18832     },
18833
18834     // private
18835     onLoad : function(){
18836         if(!this.hasFocus){
18837             return;
18838         }
18839         if(this.store.getCount() > 0){
18840             this.expand();
18841             this.restrictHeight();
18842             if(this.lastQuery == this.allQuery){
18843                 if(this.editable){
18844                     this.el.dom.select();
18845                 }
18846                 if(!this.selectByValue(this.value, true)){
18847                     this.select(0, true);
18848                 }
18849             }else{
18850                 this.selectNext();
18851                 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
18852                     this.taTask.delay(this.typeAheadDelay);
18853                 }
18854             }
18855         }else{
18856             this.onEmptyResults();
18857         }
18858         //this.el.focus();
18859     },
18860     // private
18861     onLoadException : function()
18862     {
18863         this.collapse();
18864         Roo.log(this.store.reader.jsonData);
18865         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
18866             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
18867         }
18868         
18869         
18870     },
18871     // private
18872     onTypeAhead : function(){
18873         if(this.store.getCount() > 0){
18874             var r = this.store.getAt(0);
18875             var newValue = r.data[this.displayField];
18876             var len = newValue.length;
18877             var selStart = this.getRawValue().length;
18878             if(selStart != len){
18879                 this.setRawValue(newValue);
18880                 this.selectText(selStart, newValue.length);
18881             }
18882         }
18883     },
18884
18885     // private
18886     onSelect : function(record, index){
18887         if(this.fireEvent('beforeselect', this, record, index) !== false){
18888             this.setFromData(index > -1 ? record.data : false);
18889             this.collapse();
18890             this.fireEvent('select', this, record, index);
18891         }
18892     },
18893
18894     /**
18895      * Returns the currently selected field value or empty string if no value is set.
18896      * @return {String} value The selected value
18897      */
18898     getValue : function(){
18899         if(this.valueField){
18900             return typeof this.value != 'undefined' ? this.value : '';
18901         }
18902         return Roo.form.ComboBox.superclass.getValue.call(this);
18903     },
18904
18905     /**
18906      * Clears any text/value currently set in the field
18907      */
18908     clearValue : function(){
18909         if(this.hiddenField){
18910             this.hiddenField.value = '';
18911         }
18912         this.value = '';
18913         this.setRawValue('');
18914         this.lastSelectionText = '';
18915         
18916     },
18917
18918     /**
18919      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
18920      * will be displayed in the field.  If the value does not match the data value of an existing item,
18921      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
18922      * Otherwise the field will be blank (although the value will still be set).
18923      * @param {String} value The value to match
18924      */
18925     setValue : function(v){
18926         var text = v;
18927         if(this.valueField){
18928             var r = this.findRecord(this.valueField, v);
18929             if(r){
18930                 text = r.data[this.displayField];
18931             }else if(this.valueNotFoundText !== undefined){
18932                 text = this.valueNotFoundText;
18933             }
18934         }
18935         this.lastSelectionText = text;
18936         if(this.hiddenField){
18937             this.hiddenField.value = v;
18938         }
18939         Roo.form.ComboBox.superclass.setValue.call(this, text);
18940         this.value = v;
18941     },
18942     /**
18943      * @property {Object} the last set data for the element
18944      */
18945     
18946     lastData : false,
18947     /**
18948      * Sets the value of the field based on a object which is related to the record format for the store.
18949      * @param {Object} value the value to set as. or false on reset?
18950      */
18951     setFromData : function(o){
18952         var dv = ''; // display value
18953         var vv = ''; // value value..
18954         this.lastData = o;
18955         if (this.displayField) {
18956             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
18957         } else {
18958             // this is an error condition!!!
18959             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
18960         }
18961         
18962         if(this.valueField){
18963             vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
18964         }
18965         if(this.hiddenField){
18966             this.hiddenField.value = vv;
18967             
18968             this.lastSelectionText = dv;
18969             Roo.form.ComboBox.superclass.setValue.call(this, dv);
18970             this.value = vv;
18971             return;
18972         }
18973         // no hidden field.. - we store the value in 'value', but still display
18974         // display field!!!!
18975         this.lastSelectionText = dv;
18976         Roo.form.ComboBox.superclass.setValue.call(this, dv);
18977         this.value = vv;
18978         
18979         
18980     },
18981     // private
18982     reset : function(){
18983         // overridden so that last data is reset..
18984         this.setValue(this.resetValue);
18985         this.originalValue = this.getValue();
18986         this.clearInvalid();
18987         this.lastData = false;
18988         if (this.view) {
18989             this.view.clearSelections();
18990         }
18991     },
18992     // private
18993     findRecord : function(prop, value){
18994         var record;
18995         if(this.store.getCount() > 0){
18996             this.store.each(function(r){
18997                 if(r.data[prop] == value){
18998                     record = r;
18999                     return false;
19000                 }
19001                 return true;
19002             });
19003         }
19004         return record;
19005     },
19006     
19007     getName: function()
19008     {
19009         // returns hidden if it's set..
19010         if (!this.rendered) {return ''};
19011         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
19012         
19013     },
19014     // private
19015     onViewMove : function(e, t){
19016         this.inKeyMode = false;
19017     },
19018
19019     // private
19020     onViewOver : function(e, t){
19021         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
19022             return;
19023         }
19024         var item = this.view.findItemFromChild(t);
19025         if(item){
19026             var index = this.view.indexOf(item);
19027             this.select(index, false);
19028         }
19029     },
19030
19031     // private
19032     onViewClick : function(doFocus)
19033     {
19034         var index = this.view.getSelectedIndexes()[0];
19035         var r = this.store.getAt(index);
19036         if(r){
19037             this.onSelect(r, index);
19038         }
19039         if(doFocus !== false && !this.blockFocus){
19040             this.el.focus();
19041         }
19042     },
19043
19044     // private
19045     restrictHeight : function(){
19046         this.innerList.dom.style.height = '';
19047         var inner = this.innerList.dom;
19048         var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
19049         this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
19050         this.list.beginUpdate();
19051         this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
19052         this.list.alignTo(this.el, this.listAlign);
19053         this.list.endUpdate();
19054     },
19055
19056     // private
19057     onEmptyResults : function(){
19058         this.collapse();
19059     },
19060
19061     /**
19062      * Returns true if the dropdown list is expanded, else false.
19063      */
19064     isExpanded : function(){
19065         return this.list.isVisible();
19066     },
19067
19068     /**
19069      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
19070      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
19071      * @param {String} value The data value of the item to select
19072      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
19073      * selected item if it is not currently in view (defaults to true)
19074      * @return {Boolean} True if the value matched an item in the list, else false
19075      */
19076     selectByValue : function(v, scrollIntoView){
19077         if(v !== undefined && v !== null){
19078             var r = this.findRecord(this.valueField || this.displayField, v);
19079             if(r){
19080                 this.select(this.store.indexOf(r), scrollIntoView);
19081                 return true;
19082             }
19083         }
19084         return false;
19085     },
19086
19087     /**
19088      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
19089      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
19090      * @param {Number} index The zero-based index of the list item to select
19091      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
19092      * selected item if it is not currently in view (defaults to true)
19093      */
19094     select : function(index, scrollIntoView){
19095         this.selectedIndex = index;
19096         this.view.select(index);
19097         if(scrollIntoView !== false){
19098             var el = this.view.getNode(index);
19099             if(el){
19100                 this.innerList.scrollChildIntoView(el, false);
19101             }
19102         }
19103     },
19104
19105     // private
19106     selectNext : function(){
19107         var ct = this.store.getCount();
19108         if(ct > 0){
19109             if(this.selectedIndex == -1){
19110                 this.select(0);
19111             }else if(this.selectedIndex < ct-1){
19112                 this.select(this.selectedIndex+1);
19113             }
19114         }
19115     },
19116
19117     // private
19118     selectPrev : function(){
19119         var ct = this.store.getCount();
19120         if(ct > 0){
19121             if(this.selectedIndex == -1){
19122                 this.select(0);
19123             }else if(this.selectedIndex != 0){
19124                 this.select(this.selectedIndex-1);
19125             }
19126         }
19127     },
19128
19129     // private
19130     onKeyUp : function(e){
19131         if(this.editable !== false && !e.isSpecialKey()){
19132             this.lastKey = e.getKey();
19133             this.dqTask.delay(this.queryDelay);
19134         }
19135     },
19136
19137     // private
19138     validateBlur : function(){
19139         return !this.list || !this.list.isVisible();   
19140     },
19141
19142     // private
19143     initQuery : function(){
19144         this.doQuery(this.getRawValue());
19145     },
19146
19147     // private
19148     doForce : function(){
19149         if(this.el.dom.value.length > 0){
19150             this.el.dom.value =
19151                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
19152              
19153         }
19154     },
19155
19156     /**
19157      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
19158      * query allowing the query action to be canceled if needed.
19159      * @param {String} query The SQL query to execute
19160      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
19161      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
19162      * saved in the current store (defaults to false)
19163      */
19164     doQuery : function(q, forceAll){
19165         if(q === undefined || q === null){
19166             q = '';
19167         }
19168         var qe = {
19169             query: q,
19170             forceAll: forceAll,
19171             combo: this,
19172             cancel:false
19173         };
19174         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
19175             return false;
19176         }
19177         q = qe.query;
19178         forceAll = qe.forceAll;
19179         if(forceAll === true || (q.length >= this.minChars)){
19180             if(this.lastQuery != q || this.alwaysQuery){
19181                 this.lastQuery = q;
19182                 if(this.mode == 'local'){
19183                     this.selectedIndex = -1;
19184                     if(forceAll){
19185                         this.store.clearFilter();
19186                     }else{
19187                         this.store.filter(this.displayField, q);
19188                     }
19189                     this.onLoad();
19190                 }else{
19191                     this.store.baseParams[this.queryParam] = q;
19192                     this.store.load({
19193                         params: this.getParams(q)
19194                     });
19195                     this.expand();
19196                 }
19197             }else{
19198                 this.selectedIndex = -1;
19199                 this.onLoad();   
19200             }
19201         }
19202     },
19203
19204     // private
19205     getParams : function(q){
19206         var p = {};
19207         //p[this.queryParam] = q;
19208         if(this.pageSize){
19209             p.start = 0;
19210             p.limit = this.pageSize;
19211         }
19212         return p;
19213     },
19214
19215     /**
19216      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
19217      */
19218     collapse : function(){
19219         if(!this.isExpanded()){
19220             return;
19221         }
19222         this.list.hide();
19223         Roo.get(document).un('mousedown', this.collapseIf, this);
19224         Roo.get(document).un('mousewheel', this.collapseIf, this);
19225         if (!this.editable) {
19226             Roo.get(document).un('keydown', this.listKeyPress, this);
19227         }
19228         this.fireEvent('collapse', this);
19229     },
19230
19231     // private
19232     collapseIf : function(e){
19233         if(!e.within(this.wrap) && !e.within(this.list)){
19234             this.collapse();
19235         }
19236     },
19237
19238     /**
19239      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
19240      */
19241     expand : function(){
19242         if(this.isExpanded() || !this.hasFocus){
19243             return;
19244         }
19245         this.list.alignTo(this.el, this.listAlign);
19246         this.list.show();
19247         Roo.get(document).on('mousedown', this.collapseIf, this);
19248         Roo.get(document).on('mousewheel', this.collapseIf, this);
19249         if (!this.editable) {
19250             Roo.get(document).on('keydown', this.listKeyPress, this);
19251         }
19252         
19253         this.fireEvent('expand', this);
19254     },
19255
19256     // private
19257     // Implements the default empty TriggerField.onTriggerClick function
19258     onTriggerClick : function(){
19259         if(this.disabled){
19260             return;
19261         }
19262         if(this.isExpanded()){
19263             this.collapse();
19264             if (!this.blockFocus) {
19265                 this.el.focus();
19266             }
19267             
19268         }else {
19269             this.hasFocus = true;
19270             if(this.triggerAction == 'all') {
19271                 this.doQuery(this.allQuery, true);
19272             } else {
19273                 this.doQuery(this.getRawValue());
19274             }
19275             if (!this.blockFocus) {
19276                 this.el.focus();
19277             }
19278         }
19279     },
19280     listKeyPress : function(e)
19281     {
19282         //Roo.log('listkeypress');
19283         // scroll to first matching element based on key pres..
19284         if (e.isSpecialKey()) {
19285             return false;
19286         }
19287         var k = String.fromCharCode(e.getKey()).toUpperCase();
19288         //Roo.log(k);
19289         var match  = false;
19290         var csel = this.view.getSelectedNodes();
19291         var cselitem = false;
19292         if (csel.length) {
19293             var ix = this.view.indexOf(csel[0]);
19294             cselitem  = this.store.getAt(ix);
19295             if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
19296                 cselitem = false;
19297             }
19298             
19299         }
19300         
19301         this.store.each(function(v) { 
19302             if (cselitem) {
19303                 // start at existing selection.
19304                 if (cselitem.id == v.id) {
19305                     cselitem = false;
19306                 }
19307                 return;
19308             }
19309                 
19310             if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
19311                 match = this.store.indexOf(v);
19312                 return false;
19313             }
19314         }, this);
19315         
19316         if (match === false) {
19317             return true; // no more action?
19318         }
19319         // scroll to?
19320         this.view.select(match);
19321         var sn = Roo.get(this.view.getSelectedNodes()[0]);
19322         sn.scrollIntoView(sn.dom.parentNode, false);
19323     } 
19324
19325     /** 
19326     * @cfg {Boolean} grow 
19327     * @hide 
19328     */
19329     /** 
19330     * @cfg {Number} growMin 
19331     * @hide 
19332     */
19333     /** 
19334     * @cfg {Number} growMax 
19335     * @hide 
19336     */
19337     /**
19338      * @hide
19339      * @method autoSize
19340      */
19341 });/*
19342  * Copyright(c) 2010-2012, Roo J Solutions Limited
19343  *
19344  * Licence LGPL
19345  *
19346  */
19347
19348 /**
19349  * @class Roo.form.ComboBoxArray
19350  * @extends Roo.form.TextField
19351  * A facebook style adder... for lists of email / people / countries  etc...
19352  * pick multiple items from a combo box, and shows each one.
19353  *
19354  *  Fred [x]  Brian [x]  [Pick another |v]
19355  *
19356  *
19357  *  For this to work: it needs various extra information
19358  *    - normal combo problay has
19359  *      name, hiddenName
19360  *    + displayField, valueField
19361  *
19362  *    For our purpose...
19363  *
19364  *
19365  *   If we change from 'extends' to wrapping...
19366  *   
19367  *  
19368  *
19369  
19370  
19371  * @constructor
19372  * Create a new ComboBoxArray.
19373  * @param {Object} config Configuration options
19374  */
19375  
19376
19377 Roo.form.ComboBoxArray = function(config)
19378 {
19379     this.addEvents({
19380         /**
19381          * @event beforeremove
19382          * Fires before remove the value from the list
19383              * @param {Roo.form.ComboBoxArray} _self This combo box array
19384              * @param {Roo.form.ComboBoxArray.Item} item removed item
19385              */
19386         'beforeremove' : true,
19387         /**
19388          * @event remove
19389          * Fires when remove the value from the list
19390              * @param {Roo.form.ComboBoxArray} _self This combo box array
19391              * @param {Roo.form.ComboBoxArray.Item} item removed item
19392              */
19393         'remove' : true
19394         
19395         
19396     });
19397     
19398     Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
19399     
19400     this.items = new Roo.util.MixedCollection(false);
19401     
19402     // construct the child combo...
19403     
19404     
19405     
19406     
19407    
19408     
19409 }
19410
19411  
19412 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
19413
19414     /**
19415      * @cfg {Roo.form.ComboBox} combo [required] The combo box that is wrapped
19416      */
19417     
19418     lastData : false,
19419     
19420     // behavies liek a hiddne field
19421     inputType:      'hidden',
19422     /**
19423      * @cfg {Number} width The width of the box that displays the selected element
19424      */ 
19425     width:          300,
19426
19427     
19428     
19429     /**
19430      * @cfg {String} name    The name of the visable items on this form (eg. titles not ids)
19431      */
19432     name : false,
19433     /**
19434      * @cfg {String} hiddenName    The hidden name of the field, often contains an comma seperated list of names
19435      */
19436     hiddenName : false,
19437       /**
19438      * @cfg {String} seperator    The value seperator normally ',' 
19439      */
19440     seperator : ',',
19441     
19442     // private the array of items that are displayed..
19443     items  : false,
19444     // private - the hidden field el.
19445     hiddenEl : false,
19446     // private - the filed el..
19447     el : false,
19448     
19449     //validateValue : function() { return true; }, // all values are ok!
19450     //onAddClick: function() { },
19451     
19452     onRender : function(ct, position) 
19453     {
19454         
19455         // create the standard hidden element
19456         //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
19457         
19458         
19459         // give fake names to child combo;
19460         this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
19461         this.combo.name = this.name ? (this.name+'-subcombo') : this.name;
19462         
19463         this.combo = Roo.factory(this.combo, Roo.form);
19464         this.combo.onRender(ct, position);
19465         if (typeof(this.combo.width) != 'undefined') {
19466             this.combo.onResize(this.combo.width,0);
19467         }
19468         
19469         this.combo.initEvents();
19470         
19471         // assigned so form know we need to do this..
19472         this.store          = this.combo.store;
19473         this.valueField     = this.combo.valueField;
19474         this.displayField   = this.combo.displayField ;
19475         
19476         
19477         this.combo.wrap.addClass('x-cbarray-grp');
19478         
19479         var cbwrap = this.combo.wrap.createChild(
19480             {tag: 'div', cls: 'x-cbarray-cb'},
19481             this.combo.el.dom
19482         );
19483         
19484              
19485         this.hiddenEl = this.combo.wrap.createChild({
19486             tag: 'input',  type:'hidden' , name: this.hiddenName, value : ''
19487         });
19488         this.el = this.combo.wrap.createChild({
19489             tag: 'input',  type:'hidden' , name: this.name, value : ''
19490         });
19491          //   this.el.dom.removeAttribute("name");
19492         
19493         
19494         this.outerWrap = this.combo.wrap;
19495         this.wrap = cbwrap;
19496         
19497         this.outerWrap.setWidth(this.width);
19498         this.outerWrap.dom.removeChild(this.el.dom);
19499         
19500         this.wrap.dom.appendChild(this.el.dom);
19501         this.outerWrap.dom.removeChild(this.combo.trigger.dom);
19502         this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
19503         
19504         this.combo.trigger.setStyle('position','relative');
19505         this.combo.trigger.setStyle('left', '0px');
19506         this.combo.trigger.setStyle('top', '2px');
19507         
19508         this.combo.el.setStyle('vertical-align', 'text-bottom');
19509         
19510         //this.trigger.setStyle('vertical-align', 'top');
19511         
19512         // this should use the code from combo really... on('add' ....)
19513         if (this.adder) {
19514             
19515         
19516             this.adder = this.outerWrap.createChild(
19517                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});  
19518             var _t = this;
19519             this.adder.on('click', function(e) {
19520                 _t.fireEvent('adderclick', this, e);
19521             }, _t);
19522         }
19523         //var _t = this;
19524         //this.adder.on('click', this.onAddClick, _t);
19525         
19526         
19527         this.combo.on('select', function(cb, rec, ix) {
19528             this.addItem(rec.data);
19529             
19530             cb.setValue('');
19531             cb.el.dom.value = '';
19532             //cb.lastData = rec.data;
19533             // add to list
19534             
19535         }, this);
19536         
19537         
19538     },
19539     
19540     
19541     getName: function()
19542     {
19543         // returns hidden if it's set..
19544         if (!this.rendered) {return ''};
19545         return  this.hiddenName ? this.hiddenName : this.name;
19546         
19547     },
19548     
19549     
19550     onResize: function(w, h){
19551         
19552         return;
19553         // not sure if this is needed..
19554         //this.combo.onResize(w,h);
19555         
19556         if(typeof w != 'number'){
19557             // we do not handle it!?!?
19558             return;
19559         }
19560         var tw = this.combo.trigger.getWidth();
19561         tw += this.addicon ? this.addicon.getWidth() : 0;
19562         tw += this.editicon ? this.editicon.getWidth() : 0;
19563         var x = w - tw;
19564         this.combo.el.setWidth( this.combo.adjustWidth('input', x));
19565             
19566         this.combo.trigger.setStyle('left', '0px');
19567         
19568         if(this.list && this.listWidth === undefined){
19569             var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
19570             this.list.setWidth(lw);
19571             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
19572         }
19573         
19574     
19575         
19576     },
19577     
19578     addItem: function(rec)
19579     {
19580         var valueField = this.combo.valueField;
19581         var displayField = this.combo.displayField;
19582         
19583         if (this.items.indexOfKey(rec[valueField]) > -1) {
19584             //console.log("GOT " + rec.data.id);
19585             return;
19586         }
19587         
19588         var x = new Roo.form.ComboBoxArray.Item({
19589             //id : rec[this.idField],
19590             data : rec,
19591             displayField : displayField ,
19592             tipField : displayField ,
19593             cb : this
19594         });
19595         // use the 
19596         this.items.add(rec[valueField],x);
19597         // add it before the element..
19598         this.updateHiddenEl();
19599         x.render(this.outerWrap, this.wrap.dom);
19600         // add the image handler..
19601     },
19602     
19603     updateHiddenEl : function()
19604     {
19605         this.validate();
19606         if (!this.hiddenEl) {
19607             return;
19608         }
19609         var ar = [];
19610         var idField = this.combo.valueField;
19611         
19612         this.items.each(function(f) {
19613             ar.push(f.data[idField]);
19614         });
19615         this.hiddenEl.dom.value = ar.join(this.seperator);
19616         this.validate();
19617     },
19618     
19619     reset : function()
19620     {
19621         this.items.clear();
19622         
19623         Roo.each(this.outerWrap.select('.x-cbarray-item', true).elements, function(el){
19624            el.remove();
19625         });
19626         
19627         this.el.dom.value = '';
19628         if (this.hiddenEl) {
19629             this.hiddenEl.dom.value = '';
19630         }
19631         
19632     },
19633     getValue: function()
19634     {
19635         return this.hiddenEl ? this.hiddenEl.dom.value : '';
19636     },
19637     setValue: function(v) // not a valid action - must use addItems..
19638     {
19639         
19640         this.reset();
19641          
19642         if (this.store.isLocal && (typeof(v) == 'string')) {
19643             // then we can use the store to find the values..
19644             // comma seperated at present.. this needs to allow JSON based encoding..
19645             this.hiddenEl.value  = v;
19646             var v_ar = [];
19647             Roo.each(v.split(this.seperator), function(k) {
19648                 Roo.log("CHECK " + this.valueField + ',' + k);
19649                 var li = this.store.query(this.valueField, k);
19650                 if (!li.length) {
19651                     return;
19652                 }
19653                 var add = {};
19654                 add[this.valueField] = k;
19655                 add[this.displayField] = li.item(0).data[this.displayField];
19656                 
19657                 this.addItem(add);
19658             }, this) 
19659              
19660         }
19661         if (typeof(v) == 'object' ) {
19662             // then let's assume it's an array of objects..
19663             Roo.each(v, function(l) {
19664                 var add = l;
19665                 if (typeof(l) == 'string') {
19666                     add = {};
19667                     add[this.valueField] = l;
19668                     add[this.displayField] = l
19669                 }
19670                 this.addItem(add);
19671             }, this);
19672              
19673         }
19674         
19675         
19676     },
19677     setFromData: function(v)
19678     {
19679         // this recieves an object, if setValues is called.
19680         this.reset();
19681         this.el.dom.value = v[this.displayField];
19682         this.hiddenEl.dom.value = v[this.valueField];
19683         if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
19684             return;
19685         }
19686         var kv = v[this.valueField];
19687         var dv = v[this.displayField];
19688         kv = typeof(kv) != 'string' ? '' : kv;
19689         dv = typeof(dv) != 'string' ? '' : dv;
19690         
19691         
19692         var keys = kv.split(this.seperator);
19693         var display = dv.split(this.seperator);
19694         for (var i = 0 ; i < keys.length; i++) {
19695             add = {};
19696             add[this.valueField] = keys[i];
19697             add[this.displayField] = display[i];
19698             this.addItem(add);
19699         }
19700       
19701         
19702     },
19703     
19704     /**
19705      * Validates the combox array value
19706      * @return {Boolean} True if the value is valid, else false
19707      */
19708     validate : function(){
19709         if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
19710             this.clearInvalid();
19711             return true;
19712         }
19713         return false;
19714     },
19715     
19716     validateValue : function(value){
19717         return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
19718         
19719     },
19720     
19721     /*@
19722      * overide
19723      * 
19724      */
19725     isDirty : function() {
19726         if(this.disabled) {
19727             return false;
19728         }
19729         
19730         try {
19731             var d = Roo.decode(String(this.originalValue));
19732         } catch (e) {
19733             return String(this.getValue()) !== String(this.originalValue);
19734         }
19735         
19736         var originalValue = [];
19737         
19738         for (var i = 0; i < d.length; i++){
19739             originalValue.push(d[i][this.valueField]);
19740         }
19741         
19742         return String(this.getValue()) !== String(originalValue.join(this.seperator));
19743         
19744     }
19745     
19746 });
19747
19748
19749
19750 /**
19751  * @class Roo.form.ComboBoxArray.Item
19752  * @extends Roo.BoxComponent
19753  * A selected item in the list
19754  *  Fred [x]  Brian [x]  [Pick another |v]
19755  * 
19756  * @constructor
19757  * Create a new item.
19758  * @param {Object} config Configuration options
19759  */
19760  
19761 Roo.form.ComboBoxArray.Item = function(config) {
19762     config.id = Roo.id();
19763     Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
19764 }
19765
19766 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
19767     data : {},
19768     cb: false,
19769     displayField : false,
19770     tipField : false,
19771     
19772     
19773     defaultAutoCreate : {
19774         tag: 'div',
19775         cls: 'x-cbarray-item',
19776         cn : [ 
19777             { tag: 'div' },
19778             {
19779                 tag: 'img',
19780                 width:16,
19781                 height : 16,
19782                 src : Roo.BLANK_IMAGE_URL ,
19783                 align: 'center'
19784             }
19785         ]
19786         
19787     },
19788     
19789  
19790     onRender : function(ct, position)
19791     {
19792         Roo.form.Field.superclass.onRender.call(this, ct, position);
19793         
19794         if(!this.el){
19795             var cfg = this.getAutoCreate();
19796             this.el = ct.createChild(cfg, position);
19797         }
19798         
19799         this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
19800         
19801         this.el.child('div').dom.innerHTML = this.cb.renderer ? 
19802             this.cb.renderer(this.data) :
19803             String.format('{0}',this.data[this.displayField]);
19804         
19805             
19806         this.el.child('div').dom.setAttribute('qtip',
19807                         String.format('{0}',this.data[this.tipField])
19808         );
19809         
19810         this.el.child('img').on('click', this.remove, this);
19811         
19812     },
19813    
19814     remove : function()
19815     {
19816         if(this.cb.disabled){
19817             return;
19818         }
19819         
19820         if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
19821             this.cb.items.remove(this);
19822             this.el.child('img').un('click', this.remove, this);
19823             this.el.remove();
19824             this.cb.updateHiddenEl();
19825
19826             this.cb.fireEvent('remove', this.cb, this);
19827         }
19828         
19829     }
19830 });/*
19831  * RooJS Library 1.1.1
19832  * Copyright(c) 2008-2011  Alan Knowles
19833  *
19834  * License - LGPL
19835  */
19836  
19837
19838 /**
19839  * @class Roo.form.ComboNested
19840  * @extends Roo.form.ComboBox
19841  * A combobox for that allows selection of nested items in a list,
19842  * eg.
19843  *
19844  *  Book
19845  *    -> red
19846  *    -> green
19847  *  Table
19848  *    -> square
19849  *      ->red
19850  *      ->green
19851  *    -> rectangle
19852  *      ->green
19853  *      
19854  * 
19855  * @constructor
19856  * Create a new ComboNested
19857  * @param {Object} config Configuration options
19858  */
19859 Roo.form.ComboNested = function(config){
19860     Roo.form.ComboCheck.superclass.constructor.call(this, config);
19861     // should verify some data...
19862     // like
19863     // hiddenName = required..
19864     // displayField = required
19865     // valudField == required
19866     var req= [ 'hiddenName', 'displayField', 'valueField' ];
19867     var _t = this;
19868     Roo.each(req, function(e) {
19869         if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
19870             throw "Roo.form.ComboNested : missing value for: " + e;
19871         }
19872     });
19873      
19874     
19875 };
19876
19877 Roo.extend(Roo.form.ComboNested, Roo.form.ComboBox, {
19878    
19879     /*
19880      * @config {Number} max Number of columns to show
19881      */
19882     
19883     maxColumns : 3,
19884    
19885     list : null, // the outermost div..
19886     innerLists : null, // the
19887     views : null,
19888     stores : null,
19889     // private
19890     loadingChildren : false,
19891     
19892     onRender : function(ct, position)
19893     {
19894         Roo.form.ComboBox.superclass.onRender.call(this, ct, position); // skip parent call - got to above..
19895         
19896         if(this.hiddenName){
19897             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id:  (this.hiddenId||this.hiddenName)},
19898                     'before', true);
19899             this.hiddenField.value =
19900                 this.hiddenValue !== undefined ? this.hiddenValue :
19901                 this.value !== undefined ? this.value : '';
19902
19903             // prevent input submission
19904             this.el.dom.removeAttribute('name');
19905              
19906              
19907         }
19908         
19909         if(Roo.isGecko){
19910             this.el.dom.setAttribute('autocomplete', 'off');
19911         }
19912
19913         var cls = 'x-combo-list';
19914
19915         this.list = new Roo.Layer({
19916             shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
19917         });
19918
19919         var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
19920         this.list.setWidth(lw);
19921         this.list.swallowEvent('mousewheel');
19922         this.assetHeight = 0;
19923
19924         if(this.title){
19925             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
19926             this.assetHeight += this.header.getHeight();
19927         }
19928         this.innerLists = [];
19929         this.views = [];
19930         this.stores = [];
19931         for (var i =0 ; i < this.maxColumns; i++) {
19932             this.onRenderList( cls, i);
19933         }
19934         
19935         // always needs footer, as we are going to have an 'OK' button.
19936         this.footer = this.list.createChild({cls:cls+'-ft'});
19937         this.pageTb = new Roo.Toolbar(this.footer);  
19938         var _this = this;
19939         this.pageTb.add(  {
19940             
19941             text: 'Done',
19942             handler: function()
19943             {
19944                 _this.collapse();
19945             }
19946         });
19947         
19948         if ( this.allowBlank && !this.disableClear) {
19949             
19950             this.pageTb.add(new Roo.Toolbar.Fill(), {
19951                 cls: 'x-btn-icon x-btn-clear',
19952                 text: '&#160;',
19953                 handler: function()
19954                 {
19955                     _this.collapse();
19956                     _this.clearValue();
19957                     _this.onSelect(false, -1);
19958                 }
19959             });
19960         }
19961         if (this.footer) {
19962             this.assetHeight += this.footer.getHeight();
19963         }
19964         
19965     },
19966     onRenderList : function (  cls, i)
19967     {
19968         
19969         var lw = Math.floor(
19970                 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
19971         );
19972         
19973         this.list.setWidth(lw); // default to '1'
19974
19975         var il = this.innerLists[i] = this.list.createChild({cls:cls+'-inner'});
19976         //il.on('mouseover', this.onViewOver, this, { list:  i });
19977         //il.on('mousemove', this.onViewMove, this, { list:  i });
19978         il.setWidth(lw);
19979         il.setStyle({ 'overflow-x' : 'hidden'});
19980
19981         if(!this.tpl){
19982             this.tpl = new Roo.Template({
19983                 html :  '<div class="'+cls+'-item '+cls+'-item-{cn:this.isEmpty}">{' + this.displayField + '}</div>',
19984                 isEmpty: function (value, allValues) {
19985                     //Roo.log(value);
19986                     var dl = typeof(value.data) != 'undefined' ? value.data.length : value.length; ///json is a nested response..
19987                     return dl ? 'has-children' : 'no-children'
19988                 }
19989             });
19990         }
19991         
19992         var store  = this.store;
19993         if (i > 0) {
19994             store  = new Roo.data.SimpleStore({
19995                 //fields : this.store.reader.meta.fields,
19996                 reader : this.store.reader,
19997                 data : [ ]
19998             });
19999         }
20000         this.stores[i]  = store;
20001                   
20002         var view = this.views[i] = new Roo.View(
20003             il,
20004             this.tpl,
20005             {
20006                 singleSelect:true,
20007                 store: store,
20008                 selectedClass: this.selectedClass
20009             }
20010         );
20011         view.getEl().setWidth(lw);
20012         view.getEl().setStyle({
20013             position: i < 1 ? 'relative' : 'absolute',
20014             top: 0,
20015             left: (i * lw ) + 'px',
20016             display : i > 0 ? 'none' : 'block'
20017         });
20018         view.on('selectionchange', this.onSelectChange.createDelegate(this, {list : i }, true));
20019         view.on('dblclick', this.onDoubleClick.createDelegate(this, {list : i }, true));
20020         //view.on('click', this.onViewClick, this, { list : i });
20021
20022         store.on('beforeload', this.onBeforeLoad, this);
20023         store.on('load',  this.onLoad, this, { list  : i});
20024         store.on('loadexception', this.onLoadException, this);
20025
20026         // hide the other vies..
20027         
20028         
20029         
20030     },
20031       
20032     restrictHeight : function()
20033     {
20034         var mh = 0;
20035         Roo.each(this.innerLists, function(il,i) {
20036             var el = this.views[i].getEl();
20037             el.dom.style.height = '';
20038             var inner = el.dom;
20039             var h = Math.max(il.clientHeight, il.offsetHeight, il.scrollHeight);
20040             // only adjust heights on other ones..
20041             mh = Math.max(h, mh);
20042             if (i < 1) {
20043                 
20044                 el.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
20045                 il.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
20046                
20047             }
20048             
20049             
20050         }, this);
20051         
20052         this.list.beginUpdate();
20053         this.list.setHeight(mh+this.list.getFrameWidth('tb')+this.assetHeight);
20054         this.list.alignTo(this.el, this.listAlign);
20055         this.list.endUpdate();
20056         
20057     },
20058      
20059     
20060     // -- store handlers..
20061     // private
20062     onBeforeLoad : function()
20063     {
20064         if(!this.hasFocus){
20065             return;
20066         }
20067         this.innerLists[0].update(this.loadingText ?
20068                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
20069         this.restrictHeight();
20070         this.selectedIndex = -1;
20071     },
20072     // private
20073     onLoad : function(a,b,c,d)
20074     {
20075         if (!this.loadingChildren) {
20076             // then we are loading the top level. - hide the children
20077             for (var i = 1;i < this.views.length; i++) {
20078                 this.views[i].getEl().setStyle({ display : 'none' });
20079             }
20080             var lw = Math.floor(
20081                 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
20082             );
20083         
20084              this.list.setWidth(lw); // default to '1'
20085
20086             
20087         }
20088         if(!this.hasFocus){
20089             return;
20090         }
20091         
20092         if(this.store.getCount() > 0) {
20093             this.expand();
20094             this.restrictHeight();   
20095         } else {
20096             this.onEmptyResults();
20097         }
20098         
20099         if (!this.loadingChildren) {
20100             this.selectActive();
20101         }
20102         /*
20103         this.stores[1].loadData([]);
20104         this.stores[2].loadData([]);
20105         this.views
20106         */    
20107     
20108         //this.el.focus();
20109     },
20110     
20111     
20112     // private
20113     onLoadException : function()
20114     {
20115         this.collapse();
20116         Roo.log(this.store.reader.jsonData);
20117         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
20118             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
20119         }
20120         
20121         
20122     },
20123     // no cleaning of leading spaces on blur here.
20124     cleanLeadingSpace : function(e) { },
20125     
20126
20127     onSelectChange : function (view, sels, opts )
20128     {
20129         var ix = view.getSelectedIndexes();
20130          
20131         if (opts.list > this.maxColumns - 2) {
20132             if (view.store.getCount()<  1) {
20133                 this.views[opts.list ].getEl().setStyle({ display :   'none' });
20134
20135             } else  {
20136                 if (ix.length) {
20137                     // used to clear ?? but if we are loading unselected 
20138                     this.setFromData(view.store.getAt(ix[0]).data);
20139                 }
20140                 
20141             }
20142             
20143             return;
20144         }
20145         
20146         if (!ix.length) {
20147             // this get's fired when trigger opens..
20148            // this.setFromData({});
20149             var str = this.stores[opts.list+1];
20150             str.data.clear(); // removeall wihtout the fire events..
20151             return;
20152         }
20153         
20154         var rec = view.store.getAt(ix[0]);
20155          
20156         this.setFromData(rec.data);
20157         this.fireEvent('select', this, rec, ix[0]);
20158         
20159         var lw = Math.floor(
20160              (
20161                 (this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')
20162              ) / this.maxColumns
20163         );
20164         this.loadingChildren = true;
20165         this.stores[opts.list+1].loadDataFromChildren( rec );
20166         this.loadingChildren = false;
20167         var dl = this.stores[opts.list+1]. getTotalCount();
20168         
20169         this.views[opts.list+1].getEl().setHeight( this.innerLists[0].getHeight());
20170         
20171         this.views[opts.list+1].getEl().setStyle({ display : dl ? 'block' : 'none' });
20172         for (var i = opts.list+2; i < this.views.length;i++) {
20173             this.views[i].getEl().setStyle({ display : 'none' });
20174         }
20175         
20176         this.innerLists[opts.list+1].setHeight( this.innerLists[0].getHeight());
20177         this.list.setWidth(lw * (opts.list + (dl ? 2 : 1)));
20178         
20179         if (this.isLoading) {
20180            // this.selectActive(opts.list);
20181         }
20182          
20183     },
20184     
20185     
20186     
20187     
20188     onDoubleClick : function()
20189     {
20190         this.collapse(); //??
20191     },
20192     
20193      
20194     
20195     
20196     
20197     // private
20198     recordToStack : function(store, prop, value, stack)
20199     {
20200         var cstore = new Roo.data.SimpleStore({
20201             //fields : this.store.reader.meta.fields, // we need array reader.. for
20202             reader : this.store.reader,
20203             data : [ ]
20204         });
20205         var _this = this;
20206         var record  = false;
20207         var srec = false;
20208         if(store.getCount() < 1){
20209             return false;
20210         }
20211         store.each(function(r){
20212             if(r.data[prop] == value){
20213                 record = r;
20214             srec = r;
20215                 return false;
20216             }
20217             if (r.data.cn && r.data.cn.length) {
20218                 cstore.loadDataFromChildren( r);
20219                 var cret = _this.recordToStack(cstore, prop, value, stack);
20220                 if (cret !== false) {
20221                     record = cret;
20222                     srec = r;
20223                     return false;
20224                 }
20225             }
20226              
20227             return true;
20228         });
20229         if (record == false) {
20230             return false
20231         }
20232         stack.unshift(srec);
20233         return record;
20234     },
20235     
20236     /*
20237      * find the stack of stores that match our value.
20238      *
20239      * 
20240      */
20241     
20242     selectActive : function ()
20243     {
20244         // if store is not loaded, then we will need to wait for that to happen first.
20245         var stack = [];
20246         this.recordToStack(this.store, this.valueField, this.getValue(), stack);
20247         for (var i = 0; i < stack.length; i++ ) {
20248             this.views[i].select(stack[i].store.indexOf(stack[i]), false, false );
20249         }
20250         
20251     }
20252         
20253          
20254     
20255     
20256     
20257     
20258 });/*
20259  * Based on:
20260  * Ext JS Library 1.1.1
20261  * Copyright(c) 2006-2007, Ext JS, LLC.
20262  *
20263  * Originally Released Under LGPL - original licence link has changed is not relivant.
20264  *
20265  * Fork - LGPL
20266  * <script type="text/javascript">
20267  */
20268 /**
20269  * @class Roo.form.Checkbox
20270  * @extends Roo.form.Field
20271  * Single checkbox field.  Can be used as a direct replacement for traditional checkbox fields.
20272  * @constructor
20273  * Creates a new Checkbox
20274  * @param {Object} config Configuration options
20275  */
20276 Roo.form.Checkbox = function(config){
20277     Roo.form.Checkbox.superclass.constructor.call(this, config);
20278     this.addEvents({
20279         /**
20280          * @event check
20281          * Fires when the checkbox is checked or unchecked.
20282              * @param {Roo.form.Checkbox} this This checkbox
20283              * @param {Boolean} checked The new checked value
20284              */
20285         check : true
20286     });
20287 };
20288
20289 Roo.extend(Roo.form.Checkbox, Roo.form.Field,  {
20290     /**
20291      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
20292      */
20293     focusClass : undefined,
20294     /**
20295      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
20296      */
20297     fieldClass: "x-form-field",
20298     /**
20299      * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
20300      */
20301     checked: false,
20302     /**
20303      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
20304      * {tag: "input", type: "checkbox", autocomplete: "off"})
20305      */
20306     defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
20307     /**
20308      * @cfg {String} boxLabel The text that appears beside the checkbox
20309      */
20310     boxLabel : "",
20311     /**
20312      * @cfg {String} inputValue The value that should go into the generated input element's value attribute
20313      */  
20314     inputValue : '1',
20315     /**
20316      * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
20317      */
20318      valueOff: '0', // value when not checked..
20319
20320     actionMode : 'viewEl', 
20321     //
20322     // private
20323     itemCls : 'x-menu-check-item x-form-item',
20324     groupClass : 'x-menu-group-item',
20325     inputType : 'hidden',
20326     
20327     
20328     inSetChecked: false, // check that we are not calling self...
20329     
20330     inputElement: false, // real input element?
20331     basedOn: false, // ????
20332     
20333     isFormField: true, // not sure where this is needed!!!!
20334
20335     onResize : function(){
20336         Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
20337         if(!this.boxLabel){
20338             this.el.alignTo(this.wrap, 'c-c');
20339         }
20340     },
20341
20342     initEvents : function(){
20343         Roo.form.Checkbox.superclass.initEvents.call(this);
20344         this.el.on("click", this.onClick,  this);
20345         this.el.on("change", this.onClick,  this);
20346     },
20347
20348
20349     getResizeEl : function(){
20350         return this.wrap;
20351     },
20352
20353     getPositionEl : function(){
20354         return this.wrap;
20355     },
20356
20357     // private
20358     onRender : function(ct, position){
20359         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
20360         /*
20361         if(this.inputValue !== undefined){
20362             this.el.dom.value = this.inputValue;
20363         }
20364         */
20365         //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
20366         this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
20367         var viewEl = this.wrap.createChild({ 
20368             tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
20369         this.viewEl = viewEl;   
20370         this.wrap.on('click', this.onClick,  this); 
20371         
20372         this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
20373         this.el.on('propertychange', this.setFromHidden,  this);  //ie
20374         
20375         
20376         
20377         if(this.boxLabel){
20378             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
20379         //    viewEl.on('click', this.onClick,  this); 
20380         }
20381         //if(this.checked){
20382             this.setChecked(this.checked);
20383         //}else{
20384             //this.checked = this.el.dom;
20385         //}
20386
20387     },
20388
20389     // private
20390     initValue : Roo.emptyFn,
20391
20392     /**
20393      * Returns the checked state of the checkbox.
20394      * @return {Boolean} True if checked, else false
20395      */
20396     getValue : function(){
20397         if(this.el){
20398             return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
20399         }
20400         return this.valueOff;
20401         
20402     },
20403
20404         // private
20405     onClick : function(){ 
20406         if (this.disabled) {
20407             return;
20408         }
20409         this.setChecked(!this.checked);
20410
20411         //if(this.el.dom.checked != this.checked){
20412         //    this.setValue(this.el.dom.checked);
20413        // }
20414     },
20415
20416     /**
20417      * Sets the checked state of the checkbox.
20418      * On is always based on a string comparison between inputValue and the param.
20419      * @param {Boolean/String} value - the value to set 
20420      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
20421      */
20422     setValue : function(v,suppressEvent){
20423         
20424         
20425         //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
20426         //if(this.el && this.el.dom){
20427         //    this.el.dom.checked = this.checked;
20428         //    this.el.dom.defaultChecked = this.checked;
20429         //}
20430         this.setChecked(String(v) === String(this.inputValue), suppressEvent);
20431         //this.fireEvent("check", this, this.checked);
20432     },
20433     // private..
20434     setChecked : function(state,suppressEvent)
20435     {
20436         if (this.inSetChecked) {
20437             this.checked = state;
20438             return;
20439         }
20440         
20441     
20442         if(this.wrap){
20443             this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
20444         }
20445         this.checked = state;
20446         if(suppressEvent !== true){
20447             this.fireEvent('check', this, state);
20448         }
20449         this.inSetChecked = true;
20450         this.el.dom.value = state ? this.inputValue : this.valueOff;
20451         this.inSetChecked = false;
20452         
20453     },
20454     // handle setting of hidden value by some other method!!?!?
20455     setFromHidden: function()
20456     {
20457         if(!this.el){
20458             return;
20459         }
20460         //console.log("SET FROM HIDDEN");
20461         //alert('setFrom hidden');
20462         this.setValue(this.el.dom.value);
20463     },
20464     
20465     onDestroy : function()
20466     {
20467         if(this.viewEl){
20468             Roo.get(this.viewEl).remove();
20469         }
20470          
20471         Roo.form.Checkbox.superclass.onDestroy.call(this);
20472     },
20473     
20474     setBoxLabel : function(str)
20475     {
20476         this.wrap.select('.x-form-cb-label', true).first().dom.innerHTML = str;
20477     }
20478
20479 });/*
20480  * Based on:
20481  * Ext JS Library 1.1.1
20482  * Copyright(c) 2006-2007, Ext JS, LLC.
20483  *
20484  * Originally Released Under LGPL - original licence link has changed is not relivant.
20485  *
20486  * Fork - LGPL
20487  * <script type="text/javascript">
20488  */
20489  
20490 /**
20491  * @class Roo.form.Radio
20492  * @extends Roo.form.Checkbox
20493  * Single radio field.  Same as Checkbox, but provided as a convenience for automatically setting the input type.
20494  * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
20495  * @constructor
20496  * Creates a new Radio
20497  * @param {Object} config Configuration options
20498  */
20499 Roo.form.Radio = function(){
20500     Roo.form.Radio.superclass.constructor.apply(this, arguments);
20501 };
20502 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
20503     inputType: 'radio',
20504
20505     /**
20506      * If this radio is part of a group, it will return the selected value
20507      * @return {String}
20508      */
20509     getGroupValue : function(){
20510         return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
20511     },
20512     
20513     
20514     onRender : function(ct, position){
20515         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
20516         
20517         if(this.inputValue !== undefined){
20518             this.el.dom.value = this.inputValue;
20519         }
20520          
20521         this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
20522         //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
20523         //var viewEl = this.wrap.createChild({ 
20524         //    tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
20525         //this.viewEl = viewEl;   
20526         //this.wrap.on('click', this.onClick,  this); 
20527         
20528         //this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
20529         //this.el.on('propertychange', this.setFromHidden,  this);  //ie
20530         
20531         
20532         
20533         if(this.boxLabel){
20534             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
20535         //    viewEl.on('click', this.onClick,  this); 
20536         }
20537          if(this.checked){
20538             this.el.dom.checked =   'checked' ;
20539         }
20540          
20541     } 
20542     
20543     
20544 });Roo.htmleditor = {}; 
20545 /**
20546  * @class Roo.htmleditor.Filter
20547  * Base Class for filtering htmleditor stuff. - do not use this directly - extend it.
20548  * @cfg {DomElement} node The node to iterate and filter
20549  * @cfg {boolean|String|Array} tag Tags to replace 
20550  * @constructor
20551  * Create a new Filter.
20552  * @param {Object} config Configuration options
20553  */
20554
20555
20556
20557 Roo.htmleditor.Filter = function(cfg) {
20558     Roo.apply(this.cfg);
20559     // this does not actually call walk as it's really just a abstract class
20560 }
20561
20562
20563 Roo.htmleditor.Filter.prototype = {
20564     
20565     node: false,
20566     
20567     tag: false,
20568
20569     // overrride to do replace comments.
20570     replaceComment : false,
20571     
20572     // overrride to do replace or do stuff with tags..
20573     replaceTag : false,
20574     
20575     walk : function(dom)
20576     {
20577         Roo.each( Array.from(dom.childNodes), function( e ) {
20578             switch(true) {
20579                 
20580                 case e.nodeType == 8 && typeof(this.replaceComment) != 'undefined': // comment
20581                     this.replaceComment(e);
20582                     return;
20583                 
20584                 case e.nodeType != 1: //not a node.
20585                     return;
20586                 
20587                 case this.tag === true: // everything
20588                 case typeof(this.tag) == 'object' && this.tag.indexOf(e.tagName) > -1: // array and it matches.
20589                 case typeof(this.tag) == 'string' && this.tag == e.tagName: // array and it matches.
20590                     if (this.replaceTag && false === this.replaceTag(e)) {
20591                         return;
20592                     }
20593                     if (e.hasChildNodes()) {
20594                         this.walk(e);
20595                     }
20596                     return;
20597                 
20598                 default:    // tags .. that do not match.
20599                     if (e.hasChildNodes()) {
20600                         this.walk(e);
20601                     }
20602             }
20603             
20604         }, this);
20605         
20606     }
20607 }; 
20608
20609 /**
20610  * @class Roo.htmleditor.FilterAttributes
20611  * clean attributes and  styles including http:// etc.. in attribute
20612  * @constructor
20613 * Run a new Attribute Filter
20614 * @param {Object} config Configuration options
20615  */
20616 Roo.htmleditor.FilterAttributes = function(cfg)
20617 {
20618     Roo.apply(this, cfg);
20619     this.attrib_black = this.attrib_black || [];
20620     this.attrib_clean = this.attrib_clean || [];
20621     this.style_white = this.style_white || [];
20622     this.style_black = this.style_black || [];
20623     this.walk(cfg.node);
20624 }
20625
20626 Roo.extend(Roo.htmleditor.FilterAttributes, Roo.htmleditor.Filter,
20627 {
20628     tag: true, // all tags
20629     
20630     attrib_black : false, // array
20631     attrib_clean : false,
20632     style_white : false,
20633     style_black : false,
20634      
20635      
20636     replaceTag : function(node)
20637     {
20638         if (!node.attributes || !node.attributes.length) {
20639             return true;
20640         }
20641         
20642         for (var i = node.attributes.length-1; i > -1 ; i--) {
20643             var a = node.attributes[i];
20644             //console.log(a);
20645             
20646             if (a.name.toLowerCase().substr(0,2)=='on')  {
20647                 node.removeAttribute(a.name);
20648                 continue;
20649             }
20650             
20651             
20652             if (this.attrib_black.indexOf(a.name.toLowerCase()) > -1) {
20653                 node.removeAttribute(a.name);
20654                 continue;
20655             }
20656             if (this.attrib_clean.indexOf(a.name.toLowerCase()) > -1) {
20657                 this.cleanAttr(node,a.name,a.value); // fixme..
20658                 continue;
20659             }
20660             if (a.name == 'style') {
20661                 this.cleanStyle(node,a.name,a.value);
20662                 continue;
20663             }
20664             /// clean up MS crap..
20665             // tecnically this should be a list of valid class'es..
20666             
20667             
20668             if (a.name == 'class') {
20669                 if (a.value.match(/^Mso/)) {
20670                     node.removeAttribute('class');
20671                 }
20672                 
20673                 if (a.value.match(/^body$/)) {
20674                     node.removeAttribute('class');
20675                 }
20676                 continue;
20677             }
20678             
20679             
20680             // style cleanup!?
20681             // class cleanup?
20682             
20683         }
20684         return true; // clean children
20685     },
20686         
20687     cleanAttr: function(node, n,v)
20688     {
20689         
20690         if (v.match(/^\./) || v.match(/^\//)) {
20691             return;
20692         }
20693         if (v.match(/^(http|https):\/\//) || v.match(/^mailto:/) || v.match(/^ftp:/)) {
20694             return;
20695         }
20696         if (v.match(/^#/)) {
20697             return;
20698         }
20699         if (v.match(/^\{/)) { // allow template editing.
20700             return;
20701         }
20702 //            Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
20703         node.removeAttribute(n);
20704         
20705     },
20706     cleanStyle : function(node,  n,v)
20707     {
20708         if (v.match(/expression/)) { //XSS?? should we even bother..
20709             node.removeAttribute(n);
20710             return;
20711         }
20712         
20713         var parts = v.split(/;/);
20714         var clean = [];
20715         
20716         Roo.each(parts, function(p) {
20717             p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
20718             if (!p.length) {
20719                 return true;
20720             }
20721             var l = p.split(':').shift().replace(/\s+/g,'');
20722             l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
20723             
20724             if ( this.style_black.length && (this.style_black.indexOf(l) > -1 || this.style_black.indexOf(l.toLowerCase()) > -1)) {
20725                 return true;
20726             }
20727             //Roo.log()
20728             // only allow 'c whitelisted system attributes'
20729             if ( this.style_white.length &&  style_white.indexOf(l) < 0 && style_white.indexOf(l.toLowerCase()) < 0 ) {
20730                 return true;
20731             }
20732             
20733             
20734             clean.push(p);
20735             return true;
20736         },this);
20737         if (clean.length) { 
20738             node.setAttribute(n, clean.join(';'));
20739         } else {
20740             node.removeAttribute(n);
20741         }
20742         
20743     }
20744         
20745         
20746         
20747     
20748 });/**
20749  * @class Roo.htmleditor.FilterBlack
20750  * remove blacklisted elements.
20751  * @constructor
20752  * Run a new Blacklisted Filter
20753  * @param {Object} config Configuration options
20754  */
20755
20756 Roo.htmleditor.FilterBlack = function(cfg)
20757 {
20758     Roo.apply(this, cfg);
20759     this.walk(cfg.node);
20760 }
20761
20762 Roo.extend(Roo.htmleditor.FilterBlack, Roo.htmleditor.Filter,
20763 {
20764     tag : true, // all elements.
20765    
20766     replace : function(n)
20767     {
20768         n.parentNode.removeChild(n);
20769     }
20770 });
20771 /**
20772  * @class Roo.htmleditor.FilterComment
20773  * remove comments.
20774  * @constructor
20775 * Run a new Comments Filter
20776 * @param {Object} config Configuration options
20777  */
20778 Roo.htmleditor.FilterComment = function(cfg)
20779 {
20780     this.walk(cfg.node);
20781 }
20782
20783 Roo.extend(Roo.htmleditor.FilterComment, Roo.htmleditor.Filter,
20784 {
20785   
20786     replaceComment : function(n)
20787     {
20788         n.parentNode.removeChild(n);
20789     }
20790 });/**
20791  * @class Roo.htmleditor.FilterKeepChildren
20792  * remove tags but keep children
20793  * @constructor
20794  * Run a new Keep Children Filter
20795  * @param {Object} config Configuration options
20796  */
20797
20798 Roo.htmleditor.FilterKeepChildren = function(cfg)
20799 {
20800     Roo.apply(this, cfg);
20801     this.walk(cfg.node);
20802 }
20803
20804 Roo.extend(Roo.htmleditor.FilterKeepChildren, Roo.htmleditor.FilterBlack,
20805 {
20806     
20807   
20808     replaceTag : function(node)
20809     {
20810         // walk children...
20811         var ar = Array.from(node.childNodes);
20812         for (var i = 0; i < ar.length; i++) {
20813             node.removeChild(ar[i]);
20814             // what if we need to walk these???
20815             node.parentNode.insertBefore(ar[i], node);
20816             this.walk(ar[i]);
20817         }
20818         node.parentNode.removeChild(node);
20819         return false; // don't walk children
20820         
20821         
20822     }
20823 });/**
20824  * @class Roo.htmleditor.FilterParagraph
20825  * paragraphs cause a nightmare for shared content - this filter is designed to be called ? at various points when editing
20826  * like on 'push' to remove the <p> tags and replace them with line breaks.
20827  * @constructor
20828  * Run a new Paragraph Filter
20829  * @param {Object} config Configuration options
20830  */
20831
20832 Roo.htmleditor.FilterParagraph = function(cfg)
20833 {
20834     // no need to apply config.
20835     this.walk(cfg.node);
20836 }
20837
20838 Roo.extend(Roo.htmleditor.FilterParagraph, Roo.htmleditor.Filter,
20839 {
20840     
20841      
20842     tag : 'P',
20843     
20844      
20845     replaceTag : function(node)
20846     {
20847         
20848         if (node.childNodes.length == 1 &&
20849             node.childNodes[0].nodeType == 3 &&
20850             node.childNodes[0].textContent.trim().length < 1
20851             ) {
20852             // remove and replace with '<BR>';
20853             node.parentNode.replaceChild(node.ownerDocument.createElement('BR'),node);
20854             return false; // no need to walk..
20855         }
20856         var ar = Array.from(node.childNodes);
20857         for (var i = 0; i < ar.length; i++) {
20858             node.removeChild(ar[i]);
20859             // what if we need to walk these???
20860             node.parentNode.insertBefore(ar[i], node);
20861         }
20862         // now what about this?
20863         // <p> &nbsp; </p>
20864         
20865         // double BR.
20866         node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
20867         node.parentNode.removeChild(node);
20868         
20869         return false;
20870
20871     }
20872     
20873 });/**
20874  * @class Roo.htmleditor.FilterSpan
20875  * filter span's with no attributes out..
20876  * @constructor
20877  * Run a new Span Filter
20878  * @param {Object} config Configuration options
20879  */
20880
20881 Roo.htmleditor.FilterSpan = function(cfg)
20882 {
20883     // no need to apply config.
20884     this.walk(cfg.node);
20885 }
20886
20887 Roo.extend(Roo.htmleditor.FilterSpan, Roo.htmleditor.FilterKeepChildren,
20888 {
20889      
20890     tag : 'SPAN',
20891      
20892  
20893     replaceTag : function(node)
20894     {
20895         if (node.attributes && node.attributes.length > 0) {
20896             return true; // walk if there are any.
20897         }
20898         Roo.htmleditor.FilterKeepChildren.prototype.replaceTag.call(this, node);
20899         return false;
20900      
20901     }
20902     
20903 });/**
20904  * @class Roo.htmleditor.FilterTableWidth
20905   try and remove table width data - as that frequently messes up other stuff.
20906  * 
20907  *      was cleanTableWidths.
20908  *
20909  * Quite often pasting from word etc.. results in tables with column and widths.
20910  * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
20911  *
20912  * @constructor
20913  * Run a new Table Filter
20914  * @param {Object} config Configuration options
20915  */
20916
20917 Roo.htmleditor.FilterTableWidth = function(cfg)
20918 {
20919     // no need to apply config.
20920     this.tag = ['TABLE', 'TD', 'TR', 'TH', 'THEAD', 'TBODY' ];
20921     this.walk(cfg.node);
20922 }
20923
20924 Roo.extend(Roo.htmleditor.FilterTableWidth, Roo.htmleditor.Filter,
20925 {
20926      
20927      
20928     
20929     replaceTag: function(node) {
20930         
20931         
20932       
20933         if (node.hasAttribute('width')) {
20934             node.removeAttribute('width');
20935         }
20936         
20937          
20938         if (node.hasAttribute("style")) {
20939             // pretty basic...
20940             
20941             var styles = node.getAttribute("style").split(";");
20942             var nstyle = [];
20943             Roo.each(styles, function(s) {
20944                 if (!s.match(/:/)) {
20945                     return;
20946                 }
20947                 var kv = s.split(":");
20948                 if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
20949                     return;
20950                 }
20951                 // what ever is left... we allow.
20952                 nstyle.push(s);
20953             });
20954             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
20955             if (!nstyle.length) {
20956                 node.removeAttribute('style');
20957             }
20958         }
20959         
20960         return true; // continue doing children..
20961     }
20962 });/**
20963  * @class Roo.htmleditor.FilterWord
20964  * try and clean up all the mess that Word generates.
20965  * 
20966  * This is the 'nice version' - see 'Heavy' that white lists a very short list of elements, and multi-filters 
20967  
20968  * @constructor
20969  * Run a new Span Filter
20970  * @param {Object} config Configuration options
20971  */
20972
20973 Roo.htmleditor.FilterWord = function(cfg)
20974 {
20975     // no need to apply config.
20976     this.walk(cfg.node);
20977 }
20978
20979 Roo.extend(Roo.htmleditor.FilterWord, Roo.htmleditor.Filter,
20980 {
20981     tag: true,
20982      
20983     
20984     /**
20985      * Clean up MS wordisms...
20986      */
20987     replaceTag : function(node)
20988     {
20989          
20990         // no idea what this does - span with text, replaceds with just text.
20991         if(
20992                 node.nodeName == 'SPAN' &&
20993                 !node.hasAttributes() &&
20994                 node.childNodes.length == 1 &&
20995                 node.firstChild.nodeName == "#text"  
20996         ) {
20997             var textNode = node.firstChild;
20998             node.removeChild(textNode);
20999             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
21000                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" "), node);
21001             }
21002             node.parentNode.insertBefore(textNode, node);
21003             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
21004                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" ") , node);
21005             }
21006             
21007             node.parentNode.removeChild(node);
21008             return false; // dont do chidren - we have remove our node - so no need to do chdhilren?
21009         }
21010         
21011    
21012         
21013         if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
21014             node.parentNode.removeChild(node);
21015             return false; // dont do chidlren
21016         }
21017         //Roo.log(node.tagName);
21018         // remove - but keep children..
21019         if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|v:|font)/)) {
21020             //Roo.log('-- removed');
21021             while (node.childNodes.length) {
21022                 var cn = node.childNodes[0];
21023                 node.removeChild(cn);
21024                 node.parentNode.insertBefore(cn, node);
21025                 // move node to parent - and clean it..
21026                 this.replaceTag(cn);
21027             }
21028             node.parentNode.removeChild(node);
21029             /// no need to iterate chidlren = it's got none..
21030             //this.iterateChildren(node, this.cleanWord);
21031             return false; // no need to iterate children.
21032         }
21033         // clean styles
21034         if (node.className.length) {
21035             
21036             var cn = node.className.split(/\W+/);
21037             var cna = [];
21038             Roo.each(cn, function(cls) {
21039                 if (cls.match(/Mso[a-zA-Z]+/)) {
21040                     return;
21041                 }
21042                 cna.push(cls);
21043             });
21044             node.className = cna.length ? cna.join(' ') : '';
21045             if (!cna.length) {
21046                 node.removeAttribute("class");
21047             }
21048         }
21049         
21050         if (node.hasAttribute("lang")) {
21051             node.removeAttribute("lang");
21052         }
21053         
21054         if (node.hasAttribute("style")) {
21055             
21056             var styles = node.getAttribute("style").split(";");
21057             var nstyle = [];
21058             Roo.each(styles, function(s) {
21059                 if (!s.match(/:/)) {
21060                     return;
21061                 }
21062                 var kv = s.split(":");
21063                 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
21064                     return;
21065                 }
21066                 // what ever is left... we allow.
21067                 nstyle.push(s);
21068             });
21069             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
21070             if (!nstyle.length) {
21071                 node.removeAttribute('style');
21072             }
21073         }
21074         return true; // do children
21075         
21076         
21077         
21078     }
21079 });
21080 /**
21081  * @class Roo.htmleditor.Tidy
21082  * Tidy HTML 
21083  * @cfg {Roo.HtmlEditorCore} core the editor.
21084  * @constructor
21085  * Create a new Filter.
21086  * @param {Object} config Configuration options
21087  */
21088
21089
21090 Roo.htmleditor.Tidy = function(cfg) {
21091     Roo.apply(this, cfg);
21092     
21093     this.core.doc.body.innerHTML = this.tidy(this.core.doc.body, '');
21094      
21095 }
21096
21097 Roo.htmleditor.Tidy.toString = function(node)
21098 {
21099     return Roo.htmleditor.Tidy.prototype.tidy(node, '');
21100 }
21101
21102 Roo.htmleditor.Tidy.prototype = {
21103     
21104     
21105     wrap : function(s) {
21106         return s.replace(/\n/g, " ").replace(/(?![^\n]{1,80}$)([^\n]{1,80})\s/g, '$1\n');
21107     },
21108
21109     
21110     tidy : function(node, indent) {
21111      
21112         if  (node.nodeType == 3) {
21113             // text.
21114             
21115             
21116             return indent === false ? node.nodeValue : this.wrap(node.nodeValue.trim()).split("\n").join("\n" + indent);
21117                 
21118             
21119         }
21120         
21121         if  (node.nodeType != 1) {
21122             return '';
21123         }
21124         
21125         
21126         
21127         if (node.tagName == 'BODY') {
21128             
21129             return this.cn(node, '');
21130         }
21131              
21132              // Prints the node tagName, such as <A>, <IMG>, etc
21133         var ret = "<" + node.tagName +  this.attr(node) ;
21134         
21135         // elements with no children..
21136         if (['IMG', 'BR', 'HR', 'INPUT'].indexOf(node.tagName) > -1) {
21137                 return ret + '/>';
21138         }
21139         ret += '>';
21140         
21141         
21142         var cindent = indent === false ? '' : (indent + '  ');
21143         // tags where we will not pad the children.. (inline text tags etc..)
21144         if (['PRE', 'TEXTAREA', 'TD', 'A', 'SPAN', 'B', 'I', 'S'].indexOf(node.tagName) > -1) { // or code?
21145             cindent = false;
21146             
21147             
21148         }
21149         
21150         var cn = this.cn(node, cindent );
21151         
21152         return ret + cn  + '</' + node.tagName + '>';
21153         
21154     },
21155     cn: function(node, indent)
21156     {
21157         var ret = [];
21158         
21159         var ar = Array.from(node.childNodes);
21160         for (var i = 0 ; i < ar.length ; i++) {
21161             if (indent !== false   // indent==false preservies everything
21162                 && i > 0
21163                 && ar[i].nodeType == 3 
21164                 && ar[i].nodeValue.length > 0
21165                 && ar[i].nodeValue.match(/^\s+/)
21166             ) {
21167                 ret.push(" "); // add a space if i'm a text item with a space at the front, as tidy will strip spaces.
21168             }
21169             if (indent !== false
21170                 && ar[i].nodeType == 1 // element - and indent is not set... 
21171             ) {
21172                 ret.push("\n" + indent); 
21173             }
21174             
21175             ret.push(this.tidy(ar[i], indent));
21176             // text + trailing indent 
21177             if (indent !== false
21178                 && ar[i].nodeType == 3
21179                 && ar[i].nodeValue.length > 0
21180                 && ar[i].nodeValue.match(/\s+$/)
21181             ){
21182                 ret.push("\n" + indent); 
21183             }
21184             
21185             
21186             
21187             
21188         }
21189         // what if all text?
21190         
21191         
21192         return ret.join('');
21193     },
21194     
21195          
21196         
21197     attr : function(node)
21198     {
21199         var attr = [];
21200         for(i = 0; i < node.attributes.length;i++) {
21201             
21202             // skip empty values?
21203             if (!node.attributes.item(i).value.length) {
21204                 continue;
21205             }
21206             attr.push(  node.attributes.item(i).name + '="' +
21207                     Roo.util.Format.htmlEncode(node.attributes.item(i).value) + '"'
21208             );
21209         }
21210         return attr.length ? (' ' + attr.join(' ') ) : '';
21211         
21212     }
21213     
21214     
21215     
21216 }
21217 /**
21218  * @class Roo.htmleditor.KeyEnter
21219  * Handle Enter press..
21220  * @cfg {Roo.HtmlEditorCore} core the editor.
21221  * @constructor
21222  * Create a new Filter.
21223  * @param {Object} config Configuration options
21224  */
21225
21226
21227
21228 Roo.htmleditor.KeyEnter = function(cfg) {
21229     Roo.apply(this, cfg);
21230     // this does not actually call walk as it's really just a abstract class
21231  
21232     Roo.get(this.core.doc.body).on('keypress', this.keypress, this);
21233 }
21234
21235
21236 Roo.htmleditor.KeyEnter.prototype = {
21237     
21238     core : false,
21239     
21240     keypress : function(e) {
21241         if (e.charCode != 13) {
21242             return true;
21243         }
21244         e.preventDefault();
21245         // https://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome
21246         var doc = this.core.doc;
21247         
21248         var docFragment = doc.createDocumentFragment();
21249     
21250         //add a new line
21251         var newEle = doc.createTextNode('\n');
21252         docFragment.appendChild(newEle);
21253     
21254         //add the br, or p, or something else
21255         newEle = doc.createElement('br');
21256         docFragment.appendChild(newEle);
21257     
21258         //make the br replace selection
21259         var range = this.core.win.getSelection().getRangeAt(0);
21260         range.deleteContents();
21261         range.insertNode(docFragment);
21262     
21263         //create a new range
21264         range = doc.createRange();
21265         range.setStartAfter(newEle);
21266         range.collapse(true);
21267     
21268         //make the cursor there
21269         var sel = this.core.win.getSelection();
21270         sel.removeAllRanges();
21271         sel.addRange(range);
21272     
21273         return false;
21274          
21275     }
21276 };
21277     //<script type="text/javascript">
21278
21279 /*
21280  * Based  Ext JS Library 1.1.1
21281  * Copyright(c) 2006-2007, Ext JS, LLC.
21282  * LGPL
21283  *
21284  */
21285  
21286 /**
21287  * @class Roo.HtmlEditorCore
21288  * @extends Roo.Component
21289  * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
21290  *
21291  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
21292  */
21293
21294 Roo.HtmlEditorCore = function(config){
21295     
21296     
21297     Roo.HtmlEditorCore.superclass.constructor.call(this, config);
21298     
21299     
21300     this.addEvents({
21301         /**
21302          * @event initialize
21303          * Fires when the editor is fully initialized (including the iframe)
21304          * @param {Roo.HtmlEditorCore} this
21305          */
21306         initialize: true,
21307         /**
21308          * @event activate
21309          * Fires when the editor is first receives the focus. Any insertion must wait
21310          * until after this event.
21311          * @param {Roo.HtmlEditorCore} this
21312          */
21313         activate: true,
21314          /**
21315          * @event beforesync
21316          * Fires before the textarea is updated with content from the editor iframe. Return false
21317          * to cancel the sync.
21318          * @param {Roo.HtmlEditorCore} this
21319          * @param {String} html
21320          */
21321         beforesync: true,
21322          /**
21323          * @event beforepush
21324          * Fires before the iframe editor is updated with content from the textarea. Return false
21325          * to cancel the push.
21326          * @param {Roo.HtmlEditorCore} this
21327          * @param {String} html
21328          */
21329         beforepush: true,
21330          /**
21331          * @event sync
21332          * Fires when the textarea is updated with content from the editor iframe.
21333          * @param {Roo.HtmlEditorCore} this
21334          * @param {String} html
21335          */
21336         sync: true,
21337          /**
21338          * @event push
21339          * Fires when the iframe editor is updated with content from the textarea.
21340          * @param {Roo.HtmlEditorCore} this
21341          * @param {String} html
21342          */
21343         push: true,
21344         
21345         /**
21346          * @event editorevent
21347          * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
21348          * @param {Roo.HtmlEditorCore} this
21349          */
21350         editorevent: true
21351         
21352     });
21353     
21354     // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
21355     
21356     // defaults : white / black...
21357     this.applyBlacklists();
21358     
21359     
21360     
21361 };
21362
21363
21364 Roo.extend(Roo.HtmlEditorCore, Roo.Component,  {
21365
21366
21367      /**
21368      * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field 
21369      */
21370     
21371     owner : false,
21372     
21373      /**
21374      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
21375      *                        Roo.resizable.
21376      */
21377     resizable : false,
21378      /**
21379      * @cfg {Number} height (in pixels)
21380      */   
21381     height: 300,
21382    /**
21383      * @cfg {Number} width (in pixels)
21384      */   
21385     width: 500,
21386     
21387     /**
21388      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
21389      * 
21390      */
21391     stylesheets: false,
21392     
21393     /**
21394      * @cfg {boolean} allowComments - default false - allow comments in HTML source - by default they are stripped - if you are editing email you may need this.
21395      */
21396     allowComments: false,
21397     // id of frame..
21398     frameId: false,
21399     
21400     // private properties
21401     validationEvent : false,
21402     deferHeight: true,
21403     initialized : false,
21404     activated : false,
21405     sourceEditMode : false,
21406     onFocus : Roo.emptyFn,
21407     iframePad:3,
21408     hideMode:'offsets',
21409     
21410     clearUp: true,
21411     
21412     // blacklist + whitelisted elements..
21413     black: false,
21414     white: false,
21415      
21416     bodyCls : '',
21417
21418     /**
21419      * Protected method that will not generally be called directly. It
21420      * is called when the editor initializes the iframe with HTML contents. Override this method if you
21421      * want to change the initialization markup of the iframe (e.g. to add stylesheets).
21422      */
21423     getDocMarkup : function(){
21424         // body styles..
21425         var st = '';
21426         
21427         // inherit styels from page...?? 
21428         if (this.stylesheets === false) {
21429             
21430             Roo.get(document.head).select('style').each(function(node) {
21431                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
21432             });
21433             
21434             Roo.get(document.head).select('link').each(function(node) { 
21435                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
21436             });
21437             
21438         } else if (!this.stylesheets.length) {
21439                 // simple..
21440                 st = '<style type="text/css">' +
21441                     'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
21442                    '</style>';
21443         } else {
21444             for (var i in this.stylesheets) {
21445                 if (typeof(this.stylesheets[i]) != 'string') {
21446                     continue;
21447                 }
21448                 st += '<link rel="stylesheet" href="' + this.stylesheets[i] +'" type="text/css">';
21449             }
21450             
21451         }
21452         
21453         st +=  '<style type="text/css">' +
21454             'IMG { cursor: pointer } ' +
21455         '</style>';
21456
21457         var cls = 'roo-htmleditor-body';
21458         
21459         if(this.bodyCls.length){
21460             cls += ' ' + this.bodyCls;
21461         }
21462         
21463         return '<html><head>' + st  +
21464             //<style type="text/css">' +
21465             //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
21466             //'</style>' +
21467             ' </head><body contenteditable="true" data-enable-grammerly="true" class="' +  cls + '"></body></html>';
21468     },
21469
21470     // private
21471     onRender : function(ct, position)
21472     {
21473         var _t = this;
21474         //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
21475         this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
21476         
21477         
21478         this.el.dom.style.border = '0 none';
21479         this.el.dom.setAttribute('tabIndex', -1);
21480         this.el.addClass('x-hidden hide');
21481         
21482         
21483         
21484         if(Roo.isIE){ // fix IE 1px bogus margin
21485             this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
21486         }
21487        
21488         
21489         this.frameId = Roo.id();
21490         
21491          
21492         
21493         var iframe = this.owner.wrap.createChild({
21494             tag: 'iframe',
21495             cls: 'form-control', // bootstrap..
21496             id: this.frameId,
21497             name: this.frameId,
21498             frameBorder : 'no',
21499             'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL  :  "javascript:false"
21500         }, this.el
21501         );
21502         
21503         
21504         this.iframe = iframe.dom;
21505
21506          this.assignDocWin();
21507         
21508         this.doc.designMode = 'on';
21509        
21510         this.doc.open();
21511         this.doc.write(this.getDocMarkup());
21512         this.doc.close();
21513
21514         
21515         var task = { // must defer to wait for browser to be ready
21516             run : function(){
21517                 //console.log("run task?" + this.doc.readyState);
21518                 this.assignDocWin();
21519                 if(this.doc.body || this.doc.readyState == 'complete'){
21520                     try {
21521                         this.doc.designMode="on";
21522                     } catch (e) {
21523                         return;
21524                     }
21525                     Roo.TaskMgr.stop(task);
21526                     this.initEditor.defer(10, this);
21527                 }
21528             },
21529             interval : 10,
21530             duration: 10000,
21531             scope: this
21532         };
21533         Roo.TaskMgr.start(task);
21534
21535     },
21536
21537     // private
21538     onResize : function(w, h)
21539     {
21540          Roo.log('resize: ' +w + ',' + h );
21541         //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
21542         if(!this.iframe){
21543             return;
21544         }
21545         if(typeof w == 'number'){
21546             
21547             this.iframe.style.width = w + 'px';
21548         }
21549         if(typeof h == 'number'){
21550             
21551             this.iframe.style.height = h + 'px';
21552             if(this.doc){
21553                 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
21554             }
21555         }
21556         
21557     },
21558
21559     /**
21560      * Toggles the editor between standard and source edit mode.
21561      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
21562      */
21563     toggleSourceEdit : function(sourceEditMode){
21564         
21565         this.sourceEditMode = sourceEditMode === true;
21566         
21567         if(this.sourceEditMode){
21568  
21569             Roo.get(this.iframe).addClass(['x-hidden','hide', 'd-none']);     //FIXME - what's the BS styles for these
21570             
21571         }else{
21572             Roo.get(this.iframe).removeClass(['x-hidden','hide', 'd-none']);
21573             //this.iframe.className = '';
21574             this.deferFocus();
21575         }
21576         //this.setSize(this.owner.wrap.getSize());
21577         //this.fireEvent('editmodechange', this, this.sourceEditMode);
21578     },
21579
21580     
21581   
21582
21583     /**
21584      * Protected method that will not generally be called directly. If you need/want
21585      * custom HTML cleanup, this is the method you should override.
21586      * @param {String} html The HTML to be cleaned
21587      * return {String} The cleaned HTML
21588      */
21589     cleanHtml : function(html){
21590         html = String(html);
21591         if(html.length > 5){
21592             if(Roo.isSafari){ // strip safari nonsense
21593                 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
21594             }
21595         }
21596         if(html == '&nbsp;'){
21597             html = '';
21598         }
21599         return html;
21600     },
21601
21602     /**
21603      * HTML Editor -> Textarea
21604      * Protected method that will not generally be called directly. Syncs the contents
21605      * of the editor iframe with the textarea.
21606      */
21607     syncValue : function(){
21608         if(this.initialized){
21609             var bd = (this.doc.body || this.doc.documentElement);
21610             //this.cleanUpPaste(); -- this is done else where and causes havoc..
21611             var html = bd.innerHTML;
21612             if(Roo.isSafari){
21613                 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
21614                 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
21615                 if(m && m[1]){
21616                     html = '<div style="'+m[0]+'">' + html + '</div>';
21617                 }
21618             }
21619             html = this.cleanHtml(html);
21620             // fix up the special chars.. normaly like back quotes in word...
21621             // however we do not want to do this with chinese..
21622             html = html.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u0080-\uFFFF]/g, function(match) {
21623                 
21624                 var cc = match.charCodeAt();
21625
21626                 // Get the character value, handling surrogate pairs
21627                 if (match.length == 2) {
21628                     // It's a surrogate pair, calculate the Unicode code point
21629                     var high = match.charCodeAt(0) - 0xD800;
21630                     var low  = match.charCodeAt(1) - 0xDC00;
21631                     cc = (high * 0x400) + low + 0x10000;
21632                 }  else if (
21633                     (cc >= 0x4E00 && cc < 0xA000 ) ||
21634                     (cc >= 0x3400 && cc < 0x4E00 ) ||
21635                     (cc >= 0xf900 && cc < 0xfb00 )
21636                 ) {
21637                         return match;
21638                 }  
21639          
21640                 // No, use a numeric entity. Here we brazenly (and possibly mistakenly)
21641                 return "&#" + cc + ";";
21642                 
21643                 
21644             });
21645             
21646             
21647              
21648             if(this.owner.fireEvent('beforesync', this, html) !== false){
21649                 this.el.dom.value = html;
21650                 this.owner.fireEvent('sync', this, html);
21651             }
21652         }
21653     },
21654
21655     /**
21656      * Protected method that will not generally be called directly. Pushes the value of the textarea
21657      * into the iframe editor.
21658      */
21659     pushValue : function(){
21660         if(this.initialized){
21661             var v = this.el.dom.value.trim();
21662             
21663 //            if(v.length < 1){
21664 //                v = '&#160;';
21665 //            }
21666             
21667             if(this.owner.fireEvent('beforepush', this, v) !== false){
21668                 var d = (this.doc.body || this.doc.documentElement);
21669                 d.innerHTML = v;
21670                 this.cleanUpPaste();
21671                 this.el.dom.value = d.innerHTML;
21672                 this.owner.fireEvent('push', this, v);
21673             }
21674         }
21675     },
21676
21677     // private
21678     deferFocus : function(){
21679         this.focus.defer(10, this);
21680     },
21681
21682     // doc'ed in Field
21683     focus : function(){
21684         if(this.win && !this.sourceEditMode){
21685             this.win.focus();
21686         }else{
21687             this.el.focus();
21688         }
21689     },
21690     
21691     assignDocWin: function()
21692     {
21693         var iframe = this.iframe;
21694         
21695          if(Roo.isIE){
21696             this.doc = iframe.contentWindow.document;
21697             this.win = iframe.contentWindow;
21698         } else {
21699 //            if (!Roo.get(this.frameId)) {
21700 //                return;
21701 //            }
21702 //            this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
21703 //            this.win = Roo.get(this.frameId).dom.contentWindow;
21704             
21705             if (!Roo.get(this.frameId) && !iframe.contentDocument) {
21706                 return;
21707             }
21708             
21709             this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
21710             this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
21711         }
21712     },
21713     
21714     // private
21715     initEditor : function(){
21716         //console.log("INIT EDITOR");
21717         this.assignDocWin();
21718         
21719         
21720         
21721         this.doc.designMode="on";
21722         this.doc.open();
21723         this.doc.write(this.getDocMarkup());
21724         this.doc.close();
21725         
21726         var dbody = (this.doc.body || this.doc.documentElement);
21727         //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
21728         // this copies styles from the containing element into thsi one..
21729         // not sure why we need all of this..
21730         //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
21731         
21732         //var ss = this.el.getStyles( 'background-image', 'background-repeat');
21733         //ss['background-attachment'] = 'fixed'; // w3c
21734         dbody.bgProperties = 'fixed'; // ie
21735         //Roo.DomHelper.applyStyles(dbody, ss);
21736         Roo.EventManager.on(this.doc, {
21737             //'mousedown': this.onEditorEvent,
21738             'mouseup': this.onEditorEvent,
21739             'dblclick': this.onEditorEvent,
21740             'click': this.onEditorEvent,
21741             'keyup': this.onEditorEvent,
21742             buffer:100,
21743             scope: this
21744         });
21745         if(Roo.isGecko){
21746             Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
21747         }
21748         if(Roo.isIE || Roo.isSafari || Roo.isOpera){
21749             Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
21750         }
21751         this.initialized = true;
21752
21753         
21754         // initialize special key events - enter
21755         new Roo.htmleditor.KeyEnter({core : this});
21756         
21757         
21758         
21759         
21760         this.owner.fireEvent('initialize', this);
21761         this.pushValue();
21762     },
21763
21764     // private
21765     onDestroy : function(){
21766         
21767         
21768         
21769         if(this.rendered){
21770             
21771             //for (var i =0; i < this.toolbars.length;i++) {
21772             //    // fixme - ask toolbars for heights?
21773             //    this.toolbars[i].onDestroy();
21774            // }
21775             
21776             //this.wrap.dom.innerHTML = '';
21777             //this.wrap.remove();
21778         }
21779     },
21780
21781     // private
21782     onFirstFocus : function(){
21783         
21784         this.assignDocWin();
21785         
21786         
21787         this.activated = true;
21788          
21789     
21790         if(Roo.isGecko){ // prevent silly gecko errors
21791             this.win.focus();
21792             var s = this.win.getSelection();
21793             if(!s.focusNode || s.focusNode.nodeType != 3){
21794                 var r = s.getRangeAt(0);
21795                 r.selectNodeContents((this.doc.body || this.doc.documentElement));
21796                 r.collapse(true);
21797                 this.deferFocus();
21798             }
21799             try{
21800                 this.execCmd('useCSS', true);
21801                 this.execCmd('styleWithCSS', false);
21802             }catch(e){}
21803         }
21804         this.owner.fireEvent('activate', this);
21805     },
21806
21807     // private
21808     adjustFont: function(btn){
21809         var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
21810         //if(Roo.isSafari){ // safari
21811         //    adjust *= 2;
21812        // }
21813         var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
21814         if(Roo.isSafari){ // safari
21815             var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
21816             v =  (v < 10) ? 10 : v;
21817             v =  (v > 48) ? 48 : v;
21818             v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
21819             
21820         }
21821         
21822         
21823         v = Math.max(1, v+adjust);
21824         
21825         this.execCmd('FontSize', v  );
21826     },
21827
21828     onEditorEvent : function(e)
21829     {
21830         this.owner.fireEvent('editorevent', this, e);
21831       //  this.updateToolbar();
21832         this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
21833     },
21834
21835     insertTag : function(tg)
21836     {
21837         // could be a bit smarter... -> wrap the current selected tRoo..
21838         if (tg.toLowerCase() == 'span' ||
21839             tg.toLowerCase() == 'code' ||
21840             tg.toLowerCase() == 'sup' ||
21841             tg.toLowerCase() == 'sub' 
21842             ) {
21843             
21844             range = this.createRange(this.getSelection());
21845             var wrappingNode = this.doc.createElement(tg.toLowerCase());
21846             wrappingNode.appendChild(range.extractContents());
21847             range.insertNode(wrappingNode);
21848
21849             return;
21850             
21851             
21852             
21853         }
21854         this.execCmd("formatblock",   tg);
21855         
21856     },
21857     
21858     insertText : function(txt)
21859     {
21860         
21861         
21862         var range = this.createRange();
21863         range.deleteContents();
21864                //alert(Sender.getAttribute('label'));
21865                
21866         range.insertNode(this.doc.createTextNode(txt));
21867     } ,
21868     
21869      
21870
21871     /**
21872      * Executes a Midas editor command on the editor document and performs necessary focus and
21873      * toolbar updates. <b>This should only be called after the editor is initialized.</b>
21874      * @param {String} cmd The Midas command
21875      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
21876      */
21877     relayCmd : function(cmd, value){
21878         this.win.focus();
21879         this.execCmd(cmd, value);
21880         this.owner.fireEvent('editorevent', this);
21881         //this.updateToolbar();
21882         this.owner.deferFocus();
21883     },
21884
21885     /**
21886      * Executes a Midas editor command directly on the editor document.
21887      * For visual commands, you should use {@link #relayCmd} instead.
21888      * <b>This should only be called after the editor is initialized.</b>
21889      * @param {String} cmd The Midas command
21890      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
21891      */
21892     execCmd : function(cmd, value){
21893         this.doc.execCommand(cmd, false, value === undefined ? null : value);
21894         this.syncValue();
21895     },
21896  
21897  
21898    
21899     /**
21900      * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
21901      * to insert tRoo.
21902      * @param {String} text | dom node.. 
21903      */
21904     insertAtCursor : function(text)
21905     {
21906         
21907         if(!this.activated){
21908             return;
21909         }
21910         /*
21911         if(Roo.isIE){
21912             this.win.focus();
21913             var r = this.doc.selection.createRange();
21914             if(r){
21915                 r.collapse(true);
21916                 r.pasteHTML(text);
21917                 this.syncValue();
21918                 this.deferFocus();
21919             
21920             }
21921             return;
21922         }
21923         */
21924         if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
21925             this.win.focus();
21926             
21927             
21928             // from jquery ui (MIT licenced)
21929             var range, node;
21930             var win = this.win;
21931             
21932             if (win.getSelection && win.getSelection().getRangeAt) {
21933                 range = win.getSelection().getRangeAt(0);
21934                 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
21935                 range.insertNode(node);
21936             } else if (win.document.selection && win.document.selection.createRange) {
21937                 // no firefox support
21938                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
21939                 win.document.selection.createRange().pasteHTML(txt);
21940             } else {
21941                 // no firefox support
21942                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
21943                 this.execCmd('InsertHTML', txt);
21944             } 
21945             
21946             this.syncValue();
21947             
21948             this.deferFocus();
21949         }
21950     },
21951  // private
21952     mozKeyPress : function(e){
21953         if(e.ctrlKey){
21954             var c = e.getCharCode(), cmd;
21955           
21956             if(c > 0){
21957                 c = String.fromCharCode(c).toLowerCase();
21958                 switch(c){
21959                     case 'b':
21960                         cmd = 'bold';
21961                         break;
21962                     case 'i':
21963                         cmd = 'italic';
21964                         break;
21965                     
21966                     case 'u':
21967                         cmd = 'underline';
21968                         break;
21969                     
21970                     case 'v':
21971                         this.cleanUpPaste.defer(100, this);
21972                         return;
21973                         
21974                 }
21975                 if(cmd){
21976                     this.win.focus();
21977                     this.execCmd(cmd);
21978                     this.deferFocus();
21979                     e.preventDefault();
21980                 }
21981                 
21982             }
21983         }
21984     },
21985
21986     // private
21987     fixKeys : function(){ // load time branching for fastest keydown performance
21988         if(Roo.isIE){
21989             return function(e){
21990                 var k = e.getKey(), r;
21991                 if(k == e.TAB){
21992                     e.stopEvent();
21993                     r = this.doc.selection.createRange();
21994                     if(r){
21995                         r.collapse(true);
21996                         r.pasteHTML('&#160;&#160;&#160;&#160;');
21997                         this.deferFocus();
21998                     }
21999                     return;
22000                 }
22001                 
22002                 if(k == e.ENTER){
22003                     r = this.doc.selection.createRange();
22004                     if(r){
22005                         var target = r.parentElement();
22006                         if(!target || target.tagName.toLowerCase() != 'li'){
22007                             e.stopEvent();
22008                             r.pasteHTML('<br />');
22009                             r.collapse(false);
22010                             r.select();
22011                         }
22012                     }
22013                 }
22014                 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
22015                     this.cleanUpPaste.defer(100, this);
22016                     return;
22017                 }
22018                 
22019                 
22020             };
22021         }else if(Roo.isOpera){
22022             return function(e){
22023                 var k = e.getKey();
22024                 if(k == e.TAB){
22025                     e.stopEvent();
22026                     this.win.focus();
22027                     this.execCmd('InsertHTML','&#160;&#160;&#160;&#160;');
22028                     this.deferFocus();
22029                 }
22030                 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
22031                     this.cleanUpPaste.defer(100, this);
22032                     return;
22033                 }
22034                 
22035             };
22036         }else if(Roo.isSafari){
22037             return function(e){
22038                 var k = e.getKey();
22039                 
22040                 if(k == e.TAB){
22041                     e.stopEvent();
22042                     this.execCmd('InsertText','\t');
22043                     this.deferFocus();
22044                     return;
22045                 }
22046                if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
22047                     this.cleanUpPaste.defer(100, this);
22048                     return;
22049                 }
22050                 
22051              };
22052         }
22053     }(),
22054     
22055     getAllAncestors: function()
22056     {
22057         var p = this.getSelectedNode();
22058         var a = [];
22059         if (!p) {
22060             a.push(p); // push blank onto stack..
22061             p = this.getParentElement();
22062         }
22063         
22064         
22065         while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
22066             a.push(p);
22067             p = p.parentNode;
22068         }
22069         a.push(this.doc.body);
22070         return a;
22071     },
22072     lastSel : false,
22073     lastSelNode : false,
22074     
22075     
22076     getSelection : function() 
22077     {
22078         this.assignDocWin();
22079         return Roo.isIE ? this.doc.selection : this.win.getSelection();
22080     },
22081     
22082     getSelectedNode: function() 
22083     {
22084         // this may only work on Gecko!!!
22085         
22086         // should we cache this!!!!
22087         
22088         
22089         
22090          
22091         var range = this.createRange(this.getSelection()).cloneRange();
22092         
22093         if (Roo.isIE) {
22094             var parent = range.parentElement();
22095             while (true) {
22096                 var testRange = range.duplicate();
22097                 testRange.moveToElementText(parent);
22098                 if (testRange.inRange(range)) {
22099                     break;
22100                 }
22101                 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
22102                     break;
22103                 }
22104                 parent = parent.parentElement;
22105             }
22106             return parent;
22107         }
22108         
22109         // is ancestor a text element.
22110         var ac =  range.commonAncestorContainer;
22111         if (ac.nodeType == 3) {
22112             ac = ac.parentNode;
22113         }
22114         
22115         var ar = ac.childNodes;
22116          
22117         var nodes = [];
22118         var other_nodes = [];
22119         var has_other_nodes = false;
22120         for (var i=0;i<ar.length;i++) {
22121             if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ? 
22122                 continue;
22123             }
22124             // fullly contained node.
22125             
22126             if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
22127                 nodes.push(ar[i]);
22128                 continue;
22129             }
22130             
22131             // probably selected..
22132             if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
22133                 other_nodes.push(ar[i]);
22134                 continue;
22135             }
22136             // outer..
22137             if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0))  {
22138                 continue;
22139             }
22140             
22141             
22142             has_other_nodes = true;
22143         }
22144         if (!nodes.length && other_nodes.length) {
22145             nodes= other_nodes;
22146         }
22147         if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
22148             return false;
22149         }
22150         
22151         return nodes[0];
22152     },
22153     createRange: function(sel)
22154     {
22155         // this has strange effects when using with 
22156         // top toolbar - not sure if it's a great idea.
22157         //this.editor.contentWindow.focus();
22158         if (typeof sel != "undefined") {
22159             try {
22160                 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
22161             } catch(e) {
22162                 return this.doc.createRange();
22163             }
22164         } else {
22165             return this.doc.createRange();
22166         }
22167     },
22168     getParentElement: function()
22169     {
22170         
22171         this.assignDocWin();
22172         var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
22173         
22174         var range = this.createRange(sel);
22175          
22176         try {
22177             var p = range.commonAncestorContainer;
22178             while (p.nodeType == 3) { // text node
22179                 p = p.parentNode;
22180             }
22181             return p;
22182         } catch (e) {
22183             return null;
22184         }
22185     
22186     },
22187     /***
22188      *
22189      * Range intersection.. the hard stuff...
22190      *  '-1' = before
22191      *  '0' = hits..
22192      *  '1' = after.
22193      *         [ -- selected range --- ]
22194      *   [fail]                        [fail]
22195      *
22196      *    basically..
22197      *      if end is before start or  hits it. fail.
22198      *      if start is after end or hits it fail.
22199      *
22200      *   if either hits (but other is outside. - then it's not 
22201      *   
22202      *    
22203      **/
22204     
22205     
22206     // @see http://www.thismuchiknow.co.uk/?p=64.
22207     rangeIntersectsNode : function(range, node)
22208     {
22209         var nodeRange = node.ownerDocument.createRange();
22210         try {
22211             nodeRange.selectNode(node);
22212         } catch (e) {
22213             nodeRange.selectNodeContents(node);
22214         }
22215     
22216         var rangeStartRange = range.cloneRange();
22217         rangeStartRange.collapse(true);
22218     
22219         var rangeEndRange = range.cloneRange();
22220         rangeEndRange.collapse(false);
22221     
22222         var nodeStartRange = nodeRange.cloneRange();
22223         nodeStartRange.collapse(true);
22224     
22225         var nodeEndRange = nodeRange.cloneRange();
22226         nodeEndRange.collapse(false);
22227     
22228         return rangeStartRange.compareBoundaryPoints(
22229                  Range.START_TO_START, nodeEndRange) == -1 &&
22230                rangeEndRange.compareBoundaryPoints(
22231                  Range.START_TO_START, nodeStartRange) == 1;
22232         
22233          
22234     },
22235     rangeCompareNode : function(range, node)
22236     {
22237         var nodeRange = node.ownerDocument.createRange();
22238         try {
22239             nodeRange.selectNode(node);
22240         } catch (e) {
22241             nodeRange.selectNodeContents(node);
22242         }
22243         
22244         
22245         range.collapse(true);
22246     
22247         nodeRange.collapse(true);
22248      
22249         var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
22250         var ee = range.compareBoundaryPoints(  Range.END_TO_END, nodeRange);
22251          
22252         //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
22253         
22254         var nodeIsBefore   =  ss == 1;
22255         var nodeIsAfter    = ee == -1;
22256         
22257         if (nodeIsBefore && nodeIsAfter) {
22258             return 0; // outer
22259         }
22260         if (!nodeIsBefore && nodeIsAfter) {
22261             return 1; //right trailed.
22262         }
22263         
22264         if (nodeIsBefore && !nodeIsAfter) {
22265             return 2;  // left trailed.
22266         }
22267         // fully contined.
22268         return 3;
22269     },
22270
22271     // private? - in a new class?
22272     cleanUpPaste :  function()
22273     {
22274         // cleans up the whole document..
22275         Roo.log('cleanuppaste');
22276         
22277         this.cleanUpChild(this.doc.body);
22278         var clean = this.cleanWordChars(this.doc.body.innerHTML);
22279         if (clean != this.doc.body.innerHTML) {
22280             this.doc.body.innerHTML = clean;
22281         }
22282         
22283     },
22284     
22285     cleanWordChars : function(input) {// change the chars to hex code
22286         var he = Roo.HtmlEditorCore;
22287         
22288         var output = input;
22289         Roo.each(he.swapCodes, function(sw) { 
22290             var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
22291             
22292             output = output.replace(swapper, sw[1]);
22293         });
22294         
22295         return output;
22296     },
22297     
22298      
22299     
22300         
22301     
22302     cleanUpChild : function (node)
22303     {
22304         
22305         new Roo.htmleditor.FilterComment({node : node});
22306         new Roo.htmleditor.FilterAttributes({
22307                 node : node,
22308                 attrib_black : this.ablack,
22309                 attrib_clean : this.aclean,
22310                 style_white : this.cwhite,
22311                 style_black : this.cblack
22312         });
22313         new Roo.htmleditor.FilterBlack({ node : node, tag : this.black});
22314         new Roo.htmleditor.FilterKeepChildren({node : node, tag : this.tag_remove} );
22315          
22316         
22317     },
22318     
22319     /**
22320      * Clean up MS wordisms...
22321      * @deprecated - use filter directly
22322      */
22323     cleanWord : function(node)
22324     {
22325         new Roo.htmleditor.FilterWord({ node : node ? node : this.doc.body });
22326         
22327     },
22328    
22329     
22330     /**
22331
22332      * @deprecated - use filters
22333      */
22334     cleanTableWidths : function(node)
22335     {
22336         new Roo.htmleditor.FilterTableWidth({ node : node ? node : this.doc.body});
22337         
22338  
22339     },
22340     
22341      
22342         
22343     applyBlacklists : function()
22344     {
22345         var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white  : [];
22346         var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black :  [];
22347         
22348         this.aclean = typeof(this.owner.aclean) != 'undefined' && this.owner.aclean ? this.owner.aclean :  Roo.HtmlEditorCore.aclean;
22349         this.ablack = typeof(this.owner.ablack) != 'undefined' && this.owner.ablack ? this.owner.ablack :  Roo.HtmlEditorCore.ablack;
22350         this.tag_remove = typeof(this.owner.tag_remove) != 'undefined' && this.owner.tag_remove ? this.owner.tag_remove :  Roo.HtmlEditorCore.tag_remove;
22351         
22352         this.white = [];
22353         this.black = [];
22354         Roo.each(Roo.HtmlEditorCore.white, function(tag) {
22355             if (b.indexOf(tag) > -1) {
22356                 return;
22357             }
22358             this.white.push(tag);
22359             
22360         }, this);
22361         
22362         Roo.each(w, function(tag) {
22363             if (b.indexOf(tag) > -1) {
22364                 return;
22365             }
22366             if (this.white.indexOf(tag) > -1) {
22367                 return;
22368             }
22369             this.white.push(tag);
22370             
22371         }, this);
22372         
22373         
22374         Roo.each(Roo.HtmlEditorCore.black, function(tag) {
22375             if (w.indexOf(tag) > -1) {
22376                 return;
22377             }
22378             this.black.push(tag);
22379             
22380         }, this);
22381         
22382         Roo.each(b, function(tag) {
22383             if (w.indexOf(tag) > -1) {
22384                 return;
22385             }
22386             if (this.black.indexOf(tag) > -1) {
22387                 return;
22388             }
22389             this.black.push(tag);
22390             
22391         }, this);
22392         
22393         
22394         w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite  : [];
22395         b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack :  [];
22396         
22397         this.cwhite = [];
22398         this.cblack = [];
22399         Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
22400             if (b.indexOf(tag) > -1) {
22401                 return;
22402             }
22403             this.cwhite.push(tag);
22404             
22405         }, this);
22406         
22407         Roo.each(w, function(tag) {
22408             if (b.indexOf(tag) > -1) {
22409                 return;
22410             }
22411             if (this.cwhite.indexOf(tag) > -1) {
22412                 return;
22413             }
22414             this.cwhite.push(tag);
22415             
22416         }, this);
22417         
22418         
22419         Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
22420             if (w.indexOf(tag) > -1) {
22421                 return;
22422             }
22423             this.cblack.push(tag);
22424             
22425         }, this);
22426         
22427         Roo.each(b, function(tag) {
22428             if (w.indexOf(tag) > -1) {
22429                 return;
22430             }
22431             if (this.cblack.indexOf(tag) > -1) {
22432                 return;
22433             }
22434             this.cblack.push(tag);
22435             
22436         }, this);
22437     },
22438     
22439     setStylesheets : function(stylesheets)
22440     {
22441         if(typeof(stylesheets) == 'string'){
22442             Roo.get(this.iframe.contentDocument.head).createChild({
22443                 tag : 'link',
22444                 rel : 'stylesheet',
22445                 type : 'text/css',
22446                 href : stylesheets
22447             });
22448             
22449             return;
22450         }
22451         var _this = this;
22452      
22453         Roo.each(stylesheets, function(s) {
22454             if(!s.length){
22455                 return;
22456             }
22457             
22458             Roo.get(_this.iframe.contentDocument.head).createChild({
22459                 tag : 'link',
22460                 rel : 'stylesheet',
22461                 type : 'text/css',
22462                 href : s
22463             });
22464         });
22465
22466         
22467     },
22468     
22469     removeStylesheets : function()
22470     {
22471         var _this = this;
22472         
22473         Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
22474             s.remove();
22475         });
22476     },
22477     
22478     setStyle : function(style)
22479     {
22480         Roo.get(this.iframe.contentDocument.head).createChild({
22481             tag : 'style',
22482             type : 'text/css',
22483             html : style
22484         });
22485
22486         return;
22487     }
22488     
22489     // hide stuff that is not compatible
22490     /**
22491      * @event blur
22492      * @hide
22493      */
22494     /**
22495      * @event change
22496      * @hide
22497      */
22498     /**
22499      * @event focus
22500      * @hide
22501      */
22502     /**
22503      * @event specialkey
22504      * @hide
22505      */
22506     /**
22507      * @cfg {String} fieldClass @hide
22508      */
22509     /**
22510      * @cfg {String} focusClass @hide
22511      */
22512     /**
22513      * @cfg {String} autoCreate @hide
22514      */
22515     /**
22516      * @cfg {String} inputType @hide
22517      */
22518     /**
22519      * @cfg {String} invalidClass @hide
22520      */
22521     /**
22522      * @cfg {String} invalidText @hide
22523      */
22524     /**
22525      * @cfg {String} msgFx @hide
22526      */
22527     /**
22528      * @cfg {String} validateOnBlur @hide
22529      */
22530 });
22531
22532 Roo.HtmlEditorCore.white = [
22533         'area', 'br', 'img', 'input', 'hr', 'wbr',
22534         
22535        'address', 'blockquote', 'center', 'dd',      'dir',       'div', 
22536        'dl',      'dt',         'h1',     'h2',      'h3',        'h4', 
22537        'h5',      'h6',         'hr',     'isindex', 'listing',   'marquee', 
22538        'menu',    'multicol',   'ol',     'p',       'plaintext', 'pre', 
22539        'table',   'ul',         'xmp', 
22540        
22541        'caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th', 
22542       'thead',   'tr', 
22543      
22544       'dir', 'menu', 'ol', 'ul', 'dl',
22545        
22546       'embed',  'object'
22547 ];
22548
22549
22550 Roo.HtmlEditorCore.black = [
22551     //    'embed',  'object', // enable - backend responsiblity to clean thiese
22552         'applet', // 
22553         'base',   'basefont', 'bgsound', 'blink',  'body', 
22554         'frame',  'frameset', 'head',    'html',   'ilayer', 
22555         'iframe', 'layer',  'link',     'meta',    'object',   
22556         'script', 'style' ,'title',  'xml' // clean later..
22557 ];
22558 Roo.HtmlEditorCore.clean = [
22559     'script', 'style', 'title', 'xml'
22560 ];
22561 Roo.HtmlEditorCore.tag_remove = [
22562     'font'
22563 ];
22564 // attributes..
22565
22566 Roo.HtmlEditorCore.ablack = [
22567     'on'
22568 ];
22569     
22570 Roo.HtmlEditorCore.aclean = [ 
22571     'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc' 
22572 ];
22573
22574 // protocols..
22575 Roo.HtmlEditorCore.pwhite= [
22576         'http',  'https',  'mailto'
22577 ];
22578
22579 // white listed style attributes.
22580 Roo.HtmlEditorCore.cwhite= [
22581       //  'text-align', /// default is to allow most things..
22582       
22583          
22584 //        'font-size'//??
22585 ];
22586
22587 // black listed style attributes.
22588 Roo.HtmlEditorCore.cblack= [
22589       //  'font-size' -- this can be set by the project 
22590 ];
22591
22592
22593 Roo.HtmlEditorCore.swapCodes   =[ 
22594     [    8211, "&#8211;" ], 
22595     [    8212, "&#8212;" ], 
22596     [    8216,  "'" ],  
22597     [    8217, "'" ],  
22598     [    8220, '"' ],  
22599     [    8221, '"' ],  
22600     [    8226, "*" ],  
22601     [    8230, "..." ]
22602 ]; 
22603
22604     //<script type="text/javascript">
22605
22606 /*
22607  * Ext JS Library 1.1.1
22608  * Copyright(c) 2006-2007, Ext JS, LLC.
22609  * Licence LGPL
22610  * 
22611  */
22612  
22613  
22614 Roo.form.HtmlEditor = function(config){
22615     
22616     
22617     
22618     Roo.form.HtmlEditor.superclass.constructor.call(this, config);
22619     
22620     if (!this.toolbars) {
22621         this.toolbars = [];
22622     }
22623     this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
22624     
22625     
22626 };
22627
22628 /**
22629  * @class Roo.form.HtmlEditor
22630  * @extends Roo.form.Field
22631  * Provides a lightweight HTML Editor component.
22632  *
22633  * This has been tested on Fireforx / Chrome.. IE may not be so great..
22634  * 
22635  * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
22636  * supported by this editor.</b><br/><br/>
22637  * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
22638  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
22639  */
22640 Roo.extend(Roo.form.HtmlEditor, Roo.form.Field, {
22641     /**
22642      * @cfg {Boolean} clearUp
22643      */
22644     clearUp : true,
22645       /**
22646      * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
22647      */
22648     toolbars : false,
22649    
22650      /**
22651      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
22652      *                        Roo.resizable.
22653      */
22654     resizable : false,
22655      /**
22656      * @cfg {Number} height (in pixels)
22657      */   
22658     height: 300,
22659    /**
22660      * @cfg {Number} width (in pixels)
22661      */   
22662     width: 500,
22663     
22664     /**
22665      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets - this is usally a good idea  rootURL + '/roojs1/css/undoreset.css',   .
22666      * 
22667      */
22668     stylesheets: false,
22669     
22670     
22671      /**
22672      * @cfg {Array} blacklist of css styles style attributes (blacklist overrides whitelist)
22673      * 
22674      */
22675     cblack: false,
22676     /**
22677      * @cfg {Array} whitelist of css styles style attributes (blacklist overrides whitelist)
22678      * 
22679      */
22680     cwhite: false,
22681     
22682      /**
22683      * @cfg {Array} blacklist of html tags - in addition to standard blacklist.
22684      * 
22685      */
22686     black: false,
22687     /**
22688      * @cfg {Array} whitelist of html tags - in addition to statndard whitelist
22689      * 
22690      */
22691     white: false,
22692     /**
22693      * @cfg {boolean} allowComments - default false - allow comments in HTML source - by default they are stripped - if you are editing email you may need this.
22694      */
22695     allowComments: false,
22696     /**
22697      * @cfg {string} bodyCls- default '' default classes to add to body of editable area - usually undoreset is a good start..
22698      */
22699     
22700     
22701      bodyCls : '',
22702     
22703     // id of frame..
22704     frameId: false,
22705     
22706     // private properties
22707     validationEvent : false,
22708     deferHeight: true,
22709     initialized : false,
22710     activated : false,
22711     
22712     onFocus : Roo.emptyFn,
22713     iframePad:3,
22714     hideMode:'offsets',
22715     
22716     actionMode : 'container', // defaults to hiding it...
22717     
22718     defaultAutoCreate : { // modified by initCompnoent..
22719         tag: "textarea",
22720         style:"width:500px;height:300px;",
22721         autocomplete: "new-password"
22722     },
22723
22724     // private
22725     initComponent : function(){
22726         this.addEvents({
22727             /**
22728              * @event initialize
22729              * Fires when the editor is fully initialized (including the iframe)
22730              * @param {HtmlEditor} this
22731              */
22732             initialize: true,
22733             /**
22734              * @event activate
22735              * Fires when the editor is first receives the focus. Any insertion must wait
22736              * until after this event.
22737              * @param {HtmlEditor} this
22738              */
22739             activate: true,
22740              /**
22741              * @event beforesync
22742              * Fires before the textarea is updated with content from the editor iframe. Return false
22743              * to cancel the sync.
22744              * @param {HtmlEditor} this
22745              * @param {String} html
22746              */
22747             beforesync: true,
22748              /**
22749              * @event beforepush
22750              * Fires before the iframe editor is updated with content from the textarea. Return false
22751              * to cancel the push.
22752              * @param {HtmlEditor} this
22753              * @param {String} html
22754              */
22755             beforepush: true,
22756              /**
22757              * @event sync
22758              * Fires when the textarea is updated with content from the editor iframe.
22759              * @param {HtmlEditor} this
22760              * @param {String} html
22761              */
22762             sync: true,
22763              /**
22764              * @event push
22765              * Fires when the iframe editor is updated with content from the textarea.
22766              * @param {HtmlEditor} this
22767              * @param {String} html
22768              */
22769             push: true,
22770              /**
22771              * @event editmodechange
22772              * Fires when the editor switches edit modes
22773              * @param {HtmlEditor} this
22774              * @param {Boolean} sourceEdit True if source edit, false if standard editing.
22775              */
22776             editmodechange: true,
22777             /**
22778              * @event editorevent
22779              * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
22780              * @param {HtmlEditor} this
22781              */
22782             editorevent: true,
22783             /**
22784              * @event firstfocus
22785              * Fires when on first focus - needed by toolbars..
22786              * @param {HtmlEditor} this
22787              */
22788             firstfocus: true,
22789             /**
22790              * @event autosave
22791              * Auto save the htmlEditor value as a file into Events
22792              * @param {HtmlEditor} this
22793              */
22794             autosave: true,
22795             /**
22796              * @event savedpreview
22797              * preview the saved version of htmlEditor
22798              * @param {HtmlEditor} this
22799              */
22800             savedpreview: true,
22801             
22802             /**
22803             * @event stylesheetsclick
22804             * Fires when press the Sytlesheets button
22805             * @param {Roo.HtmlEditorCore} this
22806             */
22807             stylesheetsclick: true
22808         });
22809         this.defaultAutoCreate =  {
22810             tag: "textarea",
22811             style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
22812             autocomplete: "new-password"
22813         };
22814     },
22815
22816     /**
22817      * Protected method that will not generally be called directly. It
22818      * is called when the editor creates its toolbar. Override this method if you need to
22819      * add custom toolbar buttons.
22820      * @param {HtmlEditor} editor
22821      */
22822     createToolbar : function(editor){
22823         Roo.log("create toolbars");
22824         if (!editor.toolbars || !editor.toolbars.length) {
22825             editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
22826         }
22827         
22828         for (var i =0 ; i < editor.toolbars.length;i++) {
22829             editor.toolbars[i] = Roo.factory(
22830                     typeof(editor.toolbars[i]) == 'string' ?
22831                         { xtype: editor.toolbars[i]} : editor.toolbars[i],
22832                 Roo.form.HtmlEditor);
22833             editor.toolbars[i].init(editor);
22834         }
22835          
22836         
22837     },
22838
22839      
22840     // private
22841     onRender : function(ct, position)
22842     {
22843         var _t = this;
22844         Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
22845         
22846         this.wrap = this.el.wrap({
22847             cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
22848         });
22849         
22850         this.editorcore.onRender(ct, position);
22851          
22852         if (this.resizable) {
22853             this.resizeEl = new Roo.Resizable(this.wrap, {
22854                 pinned : true,
22855                 wrap: true,
22856                 dynamic : true,
22857                 minHeight : this.height,
22858                 height: this.height,
22859                 handles : this.resizable,
22860                 width: this.width,
22861                 listeners : {
22862                     resize : function(r, w, h) {
22863                         _t.onResize(w,h); // -something
22864                     }
22865                 }
22866             });
22867             
22868         }
22869         this.createToolbar(this);
22870        
22871         
22872         if(!this.width){
22873             this.setSize(this.wrap.getSize());
22874         }
22875         if (this.resizeEl) {
22876             this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
22877             // should trigger onReize..
22878         }
22879         
22880         this.keyNav = new Roo.KeyNav(this.el, {
22881             
22882             "tab" : function(e){
22883                 e.preventDefault();
22884                 
22885                 var value = this.getValue();
22886                 
22887                 var start = this.el.dom.selectionStart;
22888                 var end = this.el.dom.selectionEnd;
22889                 
22890                 if(!e.shiftKey){
22891                     
22892                     this.setValue(value.substring(0, start) + "\t" + value.substring(end));
22893                     this.el.dom.setSelectionRange(end + 1, end + 1);
22894                     return;
22895                 }
22896                 
22897                 var f = value.substring(0, start).split("\t");
22898                 
22899                 if(f.pop().length != 0){
22900                     return;
22901                 }
22902                 
22903                 this.setValue(f.join("\t") + value.substring(end));
22904                 this.el.dom.setSelectionRange(start - 1, start - 1);
22905                 
22906             },
22907             
22908             "home" : function(e){
22909                 e.preventDefault();
22910                 
22911                 var curr = this.el.dom.selectionStart;
22912                 var lines = this.getValue().split("\n");
22913                 
22914                 if(!lines.length){
22915                     return;
22916                 }
22917                 
22918                 if(e.ctrlKey){
22919                     this.el.dom.setSelectionRange(0, 0);
22920                     return;
22921                 }
22922                 
22923                 var pos = 0;
22924                 
22925                 for (var i = 0; i < lines.length;i++) {
22926                     pos += lines[i].length;
22927                     
22928                     if(i != 0){
22929                         pos += 1;
22930                     }
22931                     
22932                     if(pos < curr){
22933                         continue;
22934                     }
22935                     
22936                     pos -= lines[i].length;
22937                     
22938                     break;
22939                 }
22940                 
22941                 if(!e.shiftKey){
22942                     this.el.dom.setSelectionRange(pos, pos);
22943                     return;
22944                 }
22945                 
22946                 this.el.dom.selectionStart = pos;
22947                 this.el.dom.selectionEnd = curr;
22948             },
22949             
22950             "end" : function(e){
22951                 e.preventDefault();
22952                 
22953                 var curr = this.el.dom.selectionStart;
22954                 var lines = this.getValue().split("\n");
22955                 
22956                 if(!lines.length){
22957                     return;
22958                 }
22959                 
22960                 if(e.ctrlKey){
22961                     this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
22962                     return;
22963                 }
22964                 
22965                 var pos = 0;
22966                 
22967                 for (var i = 0; i < lines.length;i++) {
22968                     
22969                     pos += lines[i].length;
22970                     
22971                     if(i != 0){
22972                         pos += 1;
22973                     }
22974                     
22975                     if(pos < curr){
22976                         continue;
22977                     }
22978                     
22979                     break;
22980                 }
22981                 
22982                 if(!e.shiftKey){
22983                     this.el.dom.setSelectionRange(pos, pos);
22984                     return;
22985                 }
22986                 
22987                 this.el.dom.selectionStart = curr;
22988                 this.el.dom.selectionEnd = pos;
22989             },
22990
22991             scope : this,
22992
22993             doRelay : function(foo, bar, hname){
22994                 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
22995             },
22996
22997             forceKeyDown: true
22998         });
22999         
23000 //        if(this.autosave && this.w){
23001 //            this.autoSaveFn = setInterval(this.autosave, 1000);
23002 //        }
23003     },
23004
23005     // private
23006     onResize : function(w, h)
23007     {
23008         Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
23009         var ew = false;
23010         var eh = false;
23011         
23012         if(this.el ){
23013             if(typeof w == 'number'){
23014                 var aw = w - this.wrap.getFrameWidth('lr');
23015                 this.el.setWidth(this.adjustWidth('textarea', aw));
23016                 ew = aw;
23017             }
23018             if(typeof h == 'number'){
23019                 var tbh = 0;
23020                 for (var i =0; i < this.toolbars.length;i++) {
23021                     // fixme - ask toolbars for heights?
23022                     tbh += this.toolbars[i].tb.el.getHeight();
23023                     if (this.toolbars[i].footer) {
23024                         tbh += this.toolbars[i].footer.el.getHeight();
23025                     }
23026                 }
23027                 
23028                 
23029                 
23030                 
23031                 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
23032                 ah -= 5; // knock a few pixes off for look..
23033 //                Roo.log(ah);
23034                 this.el.setHeight(this.adjustWidth('textarea', ah));
23035                 var eh = ah;
23036             }
23037         }
23038         Roo.log('onResize:' + [w,h,ew,eh].join(',') );
23039         this.editorcore.onResize(ew,eh);
23040         
23041     },
23042
23043     /**
23044      * Toggles the editor between standard and source edit mode.
23045      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
23046      */
23047     toggleSourceEdit : function(sourceEditMode)
23048     {
23049         this.editorcore.toggleSourceEdit(sourceEditMode);
23050         
23051         if(this.editorcore.sourceEditMode){
23052             Roo.log('editor - showing textarea');
23053             
23054 //            Roo.log('in');
23055 //            Roo.log(this.syncValue());
23056             this.editorcore.syncValue();
23057             this.el.removeClass('x-hidden');
23058             this.el.dom.removeAttribute('tabIndex');
23059             this.el.focus();
23060             
23061             for (var i = 0; i < this.toolbars.length; i++) {
23062                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
23063                     this.toolbars[i].tb.hide();
23064                     this.toolbars[i].footer.hide();
23065                 }
23066             }
23067             
23068         }else{
23069             Roo.log('editor - hiding textarea');
23070 //            Roo.log('out')
23071 //            Roo.log(this.pushValue()); 
23072             this.editorcore.pushValue();
23073             
23074             this.el.addClass('x-hidden');
23075             this.el.dom.setAttribute('tabIndex', -1);
23076             
23077             for (var i = 0; i < this.toolbars.length; i++) {
23078                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
23079                     this.toolbars[i].tb.show();
23080                     this.toolbars[i].footer.show();
23081                 }
23082             }
23083             
23084             //this.deferFocus();
23085         }
23086         
23087         this.setSize(this.wrap.getSize());
23088         this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
23089         
23090         this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
23091     },
23092  
23093     // private (for BoxComponent)
23094     adjustSize : Roo.BoxComponent.prototype.adjustSize,
23095
23096     // private (for BoxComponent)
23097     getResizeEl : function(){
23098         return this.wrap;
23099     },
23100
23101     // private (for BoxComponent)
23102     getPositionEl : function(){
23103         return this.wrap;
23104     },
23105
23106     // private
23107     initEvents : function(){
23108         this.originalValue = this.getValue();
23109     },
23110
23111     /**
23112      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
23113      * @method
23114      */
23115     markInvalid : Roo.emptyFn,
23116     /**
23117      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
23118      * @method
23119      */
23120     clearInvalid : Roo.emptyFn,
23121
23122     setValue : function(v){
23123         Roo.form.HtmlEditor.superclass.setValue.call(this, v);
23124         this.editorcore.pushValue();
23125     },
23126
23127      
23128     // private
23129     deferFocus : function(){
23130         this.focus.defer(10, this);
23131     },
23132
23133     // doc'ed in Field
23134     focus : function(){
23135         this.editorcore.focus();
23136         
23137     },
23138       
23139
23140     // private
23141     onDestroy : function(){
23142         
23143         
23144         
23145         if(this.rendered){
23146             
23147             for (var i =0; i < this.toolbars.length;i++) {
23148                 // fixme - ask toolbars for heights?
23149                 this.toolbars[i].onDestroy();
23150             }
23151             
23152             this.wrap.dom.innerHTML = '';
23153             this.wrap.remove();
23154         }
23155     },
23156
23157     // private
23158     onFirstFocus : function(){
23159         //Roo.log("onFirstFocus");
23160         this.editorcore.onFirstFocus();
23161          for (var i =0; i < this.toolbars.length;i++) {
23162             this.toolbars[i].onFirstFocus();
23163         }
23164         
23165     },
23166     
23167     // private
23168     syncValue : function()
23169     {
23170         this.editorcore.syncValue();
23171     },
23172     
23173     pushValue : function()
23174     {
23175         this.editorcore.pushValue();
23176     },
23177     
23178     setStylesheets : function(stylesheets)
23179     {
23180         this.editorcore.setStylesheets(stylesheets);
23181     },
23182     
23183     removeStylesheets : function()
23184     {
23185         this.editorcore.removeStylesheets();
23186     }
23187      
23188     
23189     // hide stuff that is not compatible
23190     /**
23191      * @event blur
23192      * @hide
23193      */
23194     /**
23195      * @event change
23196      * @hide
23197      */
23198     /**
23199      * @event focus
23200      * @hide
23201      */
23202     /**
23203      * @event specialkey
23204      * @hide
23205      */
23206     /**
23207      * @cfg {String} fieldClass @hide
23208      */
23209     /**
23210      * @cfg {String} focusClass @hide
23211      */
23212     /**
23213      * @cfg {String} autoCreate @hide
23214      */
23215     /**
23216      * @cfg {String} inputType @hide
23217      */
23218     /**
23219      * @cfg {String} invalidClass @hide
23220      */
23221     /**
23222      * @cfg {String} invalidText @hide
23223      */
23224     /**
23225      * @cfg {String} msgFx @hide
23226      */
23227     /**
23228      * @cfg {String} validateOnBlur @hide
23229      */
23230 });
23231  
23232     // <script type="text/javascript">
23233 /*
23234  * Based on
23235  * Ext JS Library 1.1.1
23236  * Copyright(c) 2006-2007, Ext JS, LLC.
23237  *  
23238  
23239  */
23240
23241 /**
23242  * @class Roo.form.HtmlEditorToolbar1
23243  * Basic Toolbar
23244  * 
23245  * Usage:
23246  *
23247  new Roo.form.HtmlEditor({
23248     ....
23249     toolbars : [
23250         new Roo.form.HtmlEditorToolbar1({
23251             disable : { fonts: 1 , format: 1, ..., ... , ...],
23252             btns : [ .... ]
23253         })
23254     }
23255      
23256  * 
23257  * @cfg {Object} disable List of elements to disable..
23258  * @cfg {Array} btns List of additional buttons.
23259  * 
23260  * 
23261  * NEEDS Extra CSS? 
23262  * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
23263  */
23264  
23265 Roo.form.HtmlEditor.ToolbarStandard = function(config)
23266 {
23267     
23268     Roo.apply(this, config);
23269     
23270     // default disabled, based on 'good practice'..
23271     this.disable = this.disable || {};
23272     Roo.applyIf(this.disable, {
23273         fontSize : true,
23274         colors : true,
23275         specialElements : true
23276     });
23277     
23278     
23279     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
23280     // dont call parent... till later.
23281 }
23282
23283 Roo.apply(Roo.form.HtmlEditor.ToolbarStandard.prototype,  {
23284     
23285     tb: false,
23286     
23287     rendered: false,
23288     
23289     editor : false,
23290     editorcore : false,
23291     /**
23292      * @cfg {Object} disable  List of toolbar elements to disable
23293          
23294      */
23295     disable : false,
23296     
23297     
23298      /**
23299      * @cfg {String} createLinkText The default text for the create link prompt
23300      */
23301     createLinkText : 'Please enter the URL for the link:',
23302     /**
23303      * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
23304      */
23305     defaultLinkValue : 'http:/'+'/',
23306    
23307     
23308       /**
23309      * @cfg {Array} fontFamilies An array of available font families
23310      */
23311     fontFamilies : [
23312         'Arial',
23313         'Courier New',
23314         'Tahoma',
23315         'Times New Roman',
23316         'Verdana'
23317     ],
23318     
23319     specialChars : [
23320            "&#169;",
23321           "&#174;",     
23322           "&#8482;",    
23323           "&#163;" ,    
23324          // "&#8212;",    
23325           "&#8230;",    
23326           "&#247;" ,    
23327         //  "&#225;" ,     ?? a acute?
23328            "&#8364;"    , //Euro
23329        //   "&#8220;"    ,
23330         //  "&#8221;"    ,
23331         //  "&#8226;"    ,
23332           "&#176;"  //   , // degrees
23333
23334          // "&#233;"     , // e ecute
23335          // "&#250;"     , // u ecute?
23336     ],
23337     
23338     specialElements : [
23339         {
23340             text: "Insert Table",
23341             xtype: 'MenuItem',
23342             xns : Roo.Menu,
23343             ihtml :  '<table><tr><td>Cell</td></tr></table>' 
23344                 
23345         },
23346         {    
23347             text: "Insert Image",
23348             xtype: 'MenuItem',
23349             xns : Roo.Menu,
23350             ihtml : '<img src="about:blank"/>'
23351             
23352         }
23353         
23354          
23355     ],
23356     
23357     
23358     inputElements : [ 
23359             "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password", 
23360             "input:submit", "input:button", "select", "textarea", "label" ],
23361     formats : [
23362         ["p"] ,  
23363         ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"], 
23364         ["pre"],[ "code"], 
23365         ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
23366         ['div'],['span'],
23367         ['sup'],['sub']
23368     ],
23369     
23370     cleanStyles : [
23371         "font-size"
23372     ],
23373      /**
23374      * @cfg {String} defaultFont default font to use.
23375      */
23376     defaultFont: 'tahoma',
23377    
23378     fontSelect : false,
23379     
23380     
23381     formatCombo : false,
23382     
23383     init : function(editor)
23384     {
23385         this.editor = editor;
23386         this.editorcore = editor.editorcore ? editor.editorcore : editor;
23387         var editorcore = this.editorcore;
23388         
23389         var _t = this;
23390         
23391         var fid = editorcore.frameId;
23392         var etb = this;
23393         function btn(id, toggle, handler){
23394             var xid = fid + '-'+ id ;
23395             return {
23396                 id : xid,
23397                 cmd : id,
23398                 cls : 'x-btn-icon x-edit-'+id,
23399                 enableToggle:toggle !== false,
23400                 scope: _t, // was editor...
23401                 handler:handler||_t.relayBtnCmd,
23402                 clickEvent:'mousedown',
23403                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
23404                 tabIndex:-1
23405             };
23406         }
23407         
23408         
23409         
23410         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
23411         this.tb = tb;
23412          // stop form submits
23413         tb.el.on('click', function(e){
23414             e.preventDefault(); // what does this do?
23415         });
23416
23417         if(!this.disable.font) { // && !Roo.isSafari){
23418             /* why no safari for fonts 
23419             editor.fontSelect = tb.el.createChild({
23420                 tag:'select',
23421                 tabIndex: -1,
23422                 cls:'x-font-select',
23423                 html: this.createFontOptions()
23424             });
23425             
23426             editor.fontSelect.on('change', function(){
23427                 var font = editor.fontSelect.dom.value;
23428                 editor.relayCmd('fontname', font);
23429                 editor.deferFocus();
23430             }, editor);
23431             
23432             tb.add(
23433                 editor.fontSelect.dom,
23434                 '-'
23435             );
23436             */
23437             
23438         };
23439         if(!this.disable.formats){
23440             this.formatCombo = new Roo.form.ComboBox({
23441                 store: new Roo.data.SimpleStore({
23442                     id : 'tag',
23443                     fields: ['tag'],
23444                     data : this.formats // from states.js
23445                 }),
23446                 blockFocus : true,
23447                 name : '',
23448                 //autoCreate : {tag: "div",  size: "20"},
23449                 displayField:'tag',
23450                 typeAhead: false,
23451                 mode: 'local',
23452                 editable : false,
23453                 triggerAction: 'all',
23454                 emptyText:'Add tag',
23455                 selectOnFocus:true,
23456                 width:135,
23457                 listeners : {
23458                     'select': function(c, r, i) {
23459                         editorcore.insertTag(r.get('tag'));
23460                         editor.focus();
23461                     }
23462                 }
23463
23464             });
23465             tb.addField(this.formatCombo);
23466             
23467         }
23468         
23469         if(!this.disable.format){
23470             tb.add(
23471                 btn('bold'),
23472                 btn('italic'),
23473                 btn('underline'),
23474                 btn('strikethrough')
23475             );
23476         };
23477         if(!this.disable.fontSize){
23478             tb.add(
23479                 '-',
23480                 
23481                 
23482                 btn('increasefontsize', false, editorcore.adjustFont),
23483                 btn('decreasefontsize', false, editorcore.adjustFont)
23484             );
23485         };
23486         
23487         
23488         if(!this.disable.colors){
23489             tb.add(
23490                 '-', {
23491                     id:editorcore.frameId +'-forecolor',
23492                     cls:'x-btn-icon x-edit-forecolor',
23493                     clickEvent:'mousedown',
23494                     tooltip: this.buttonTips['forecolor'] || undefined,
23495                     tabIndex:-1,
23496                     menu : new Roo.menu.ColorMenu({
23497                         allowReselect: true,
23498                         focus: Roo.emptyFn,
23499                         value:'000000',
23500                         plain:true,
23501                         selectHandler: function(cp, color){
23502                             editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
23503                             editor.deferFocus();
23504                         },
23505                         scope: editorcore,
23506                         clickEvent:'mousedown'
23507                     })
23508                 }, {
23509                     id:editorcore.frameId +'backcolor',
23510                     cls:'x-btn-icon x-edit-backcolor',
23511                     clickEvent:'mousedown',
23512                     tooltip: this.buttonTips['backcolor'] || undefined,
23513                     tabIndex:-1,
23514                     menu : new Roo.menu.ColorMenu({
23515                         focus: Roo.emptyFn,
23516                         value:'FFFFFF',
23517                         plain:true,
23518                         allowReselect: true,
23519                         selectHandler: function(cp, color){
23520                             if(Roo.isGecko){
23521                                 editorcore.execCmd('useCSS', false);
23522                                 editorcore.execCmd('hilitecolor', color);
23523                                 editorcore.execCmd('useCSS', true);
23524                                 editor.deferFocus();
23525                             }else{
23526                                 editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor', 
23527                                     Roo.isSafari || Roo.isIE ? '#'+color : color);
23528                                 editor.deferFocus();
23529                             }
23530                         },
23531                         scope:editorcore,
23532                         clickEvent:'mousedown'
23533                     })
23534                 }
23535             );
23536         };
23537         // now add all the items...
23538         
23539
23540         if(!this.disable.alignments){
23541             tb.add(
23542                 '-',
23543                 btn('justifyleft'),
23544                 btn('justifycenter'),
23545                 btn('justifyright')
23546             );
23547         };
23548
23549         //if(!Roo.isSafari){
23550             if(!this.disable.links){
23551                 tb.add(
23552                     '-',
23553                     btn('createlink', false, this.createLink)    /// MOVE TO HERE?!!?!?!?!
23554                 );
23555             };
23556
23557             if(!this.disable.lists){
23558                 tb.add(
23559                     '-',
23560                     btn('insertorderedlist'),
23561                     btn('insertunorderedlist')
23562                 );
23563             }
23564             if(!this.disable.sourceEdit){
23565                 tb.add(
23566                     '-',
23567                     btn('sourceedit', true, function(btn){
23568                         this.toggleSourceEdit(btn.pressed);
23569                     })
23570                 );
23571             }
23572         //}
23573         
23574         var smenu = { };
23575         // special menu.. - needs to be tidied up..
23576         if (!this.disable.special) {
23577             smenu = {
23578                 text: "&#169;",
23579                 cls: 'x-edit-none',
23580                 
23581                 menu : {
23582                     items : []
23583                 }
23584             };
23585             for (var i =0; i < this.specialChars.length; i++) {
23586                 smenu.menu.items.push({
23587                     
23588                     html: this.specialChars[i],
23589                     handler: function(a,b) {
23590                         editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
23591                         //editor.insertAtCursor(a.html);
23592                         
23593                     },
23594                     tabIndex:-1
23595                 });
23596             }
23597             
23598             
23599             tb.add(smenu);
23600             
23601             
23602         }
23603         
23604         var cmenu = { };
23605         if (!this.disable.cleanStyles) {
23606             cmenu = {
23607                 cls: 'x-btn-icon x-btn-clear',
23608                 
23609                 menu : {
23610                     items : []
23611                 }
23612             };
23613             for (var i =0; i < this.cleanStyles.length; i++) {
23614                 cmenu.menu.items.push({
23615                     actiontype : this.cleanStyles[i],
23616                     html: 'Remove ' + this.cleanStyles[i],
23617                     handler: function(a,b) {
23618 //                        Roo.log(a);
23619 //                        Roo.log(b);
23620                         var c = Roo.get(editorcore.doc.body);
23621                         c.select('[style]').each(function(s) {
23622                             s.dom.style.removeProperty(a.actiontype);
23623                         });
23624                         editorcore.syncValue();
23625                     },
23626                     tabIndex:-1
23627                 });
23628             }
23629             cmenu.menu.items.push({
23630                 actiontype : 'tablewidths',
23631                 html: 'Remove Table Widths',
23632                 handler: function(a,b) {
23633                     editorcore.cleanTableWidths();
23634                     editorcore.syncValue();
23635                 },
23636                 tabIndex:-1
23637             });
23638             cmenu.menu.items.push({
23639                 actiontype : 'word',
23640                 html: 'Remove MS Word Formating',
23641                 handler: function(a,b) {
23642                     editorcore.cleanWord();
23643                     editorcore.syncValue();
23644                 },
23645                 tabIndex:-1
23646             });
23647             
23648             cmenu.menu.items.push({
23649                 actiontype : 'all',
23650                 html: 'Remove All Styles',
23651                 handler: function(a,b) {
23652                     
23653                     var c = Roo.get(editorcore.doc.body);
23654                     c.select('[style]').each(function(s) {
23655                         s.dom.removeAttribute('style');
23656                     });
23657                     editorcore.syncValue();
23658                 },
23659                 tabIndex:-1
23660             });
23661             
23662             cmenu.menu.items.push({
23663                 actiontype : 'all',
23664                 html: 'Remove All CSS Classes',
23665                 handler: function(a,b) {
23666                     
23667                     var c = Roo.get(editorcore.doc.body);
23668                     c.select('[class]').each(function(s) {
23669                         s.dom.removeAttribute('class');
23670                     });
23671                     editorcore.cleanWord();
23672                     editorcore.syncValue();
23673                 },
23674                 tabIndex:-1
23675             });
23676             
23677              cmenu.menu.items.push({
23678                 actiontype : 'tidy',
23679                 html: 'Tidy HTML Source',
23680                 handler: function(a,b) {
23681                     new Roo.htmleditor.Tidy(editorcore.doc.body);
23682                     editorcore.syncValue();
23683                 },
23684                 tabIndex:-1
23685             });
23686             
23687             
23688             tb.add(cmenu);
23689         }
23690          
23691         if (!this.disable.specialElements) {
23692             var semenu = {
23693                 text: "Other;",
23694                 cls: 'x-edit-none',
23695                 menu : {
23696                     items : []
23697                 }
23698             };
23699             for (var i =0; i < this.specialElements.length; i++) {
23700                 semenu.menu.items.push(
23701                     Roo.apply({ 
23702                         handler: function(a,b) {
23703                             editor.insertAtCursor(this.ihtml);
23704                         }
23705                     }, this.specialElements[i])
23706                 );
23707                     
23708             }
23709             
23710             tb.add(semenu);
23711             
23712             
23713         }
23714          
23715         
23716         if (this.btns) {
23717             for(var i =0; i< this.btns.length;i++) {
23718                 var b = Roo.factory(this.btns[i],Roo.form);
23719                 b.cls =  'x-edit-none';
23720                 
23721                 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
23722                     b.cls += ' x-init-enable';
23723                 }
23724                 
23725                 b.scope = editorcore;
23726                 tb.add(b);
23727             }
23728         
23729         }
23730         
23731         
23732         
23733         // disable everything...
23734         
23735         this.tb.items.each(function(item){
23736             
23737            if(
23738                 item.id != editorcore.frameId+ '-sourceedit' && 
23739                 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
23740             ){
23741                 
23742                 item.disable();
23743             }
23744         });
23745         this.rendered = true;
23746         
23747         // the all the btns;
23748         editor.on('editorevent', this.updateToolbar, this);
23749         // other toolbars need to implement this..
23750         //editor.on('editmodechange', this.updateToolbar, this);
23751     },
23752     
23753     
23754     relayBtnCmd : function(btn) {
23755         this.editorcore.relayCmd(btn.cmd);
23756     },
23757     // private used internally
23758     createLink : function(){
23759         Roo.log("create link?");
23760         var url = prompt(this.createLinkText, this.defaultLinkValue);
23761         if(url && url != 'http:/'+'/'){
23762             this.editorcore.relayCmd('createlink', url);
23763         }
23764     },
23765
23766     
23767     /**
23768      * Protected method that will not generally be called directly. It triggers
23769      * a toolbar update by reading the markup state of the current selection in the editor.
23770      */
23771     updateToolbar: function(){
23772
23773         if(!this.editorcore.activated){
23774             this.editor.onFirstFocus();
23775             return;
23776         }
23777
23778         var btns = this.tb.items.map, 
23779             doc = this.editorcore.doc,
23780             frameId = this.editorcore.frameId;
23781
23782         if(!this.disable.font && !Roo.isSafari){
23783             /*
23784             var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
23785             if(name != this.fontSelect.dom.value){
23786                 this.fontSelect.dom.value = name;
23787             }
23788             */
23789         }
23790         if(!this.disable.format){
23791             btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
23792             btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
23793             btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
23794             btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
23795         }
23796         if(!this.disable.alignments){
23797             btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
23798             btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
23799             btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
23800         }
23801         if(!Roo.isSafari && !this.disable.lists){
23802             btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
23803             btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
23804         }
23805         
23806         var ans = this.editorcore.getAllAncestors();
23807         if (this.formatCombo) {
23808             
23809             
23810             var store = this.formatCombo.store;
23811             this.formatCombo.setValue("");
23812             for (var i =0; i < ans.length;i++) {
23813                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
23814                     // select it..
23815                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
23816                     break;
23817                 }
23818             }
23819         }
23820         
23821         
23822         
23823         // hides menus... - so this cant be on a menu...
23824         Roo.menu.MenuMgr.hideAll();
23825
23826         //this.editorsyncValue();
23827     },
23828    
23829     
23830     createFontOptions : function(){
23831         var buf = [], fs = this.fontFamilies, ff, lc;
23832         
23833         
23834         
23835         for(var i = 0, len = fs.length; i< len; i++){
23836             ff = fs[i];
23837             lc = ff.toLowerCase();
23838             buf.push(
23839                 '<option value="',lc,'" style="font-family:',ff,';"',
23840                     (this.defaultFont == lc ? ' selected="true">' : '>'),
23841                     ff,
23842                 '</option>'
23843             );
23844         }
23845         return buf.join('');
23846     },
23847     
23848     toggleSourceEdit : function(sourceEditMode){
23849         
23850         Roo.log("toolbar toogle");
23851         if(sourceEditMode === undefined){
23852             sourceEditMode = !this.sourceEditMode;
23853         }
23854         this.sourceEditMode = sourceEditMode === true;
23855         var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
23856         // just toggle the button?
23857         if(btn.pressed !== this.sourceEditMode){
23858             btn.toggle(this.sourceEditMode);
23859             return;
23860         }
23861         
23862         if(sourceEditMode){
23863             Roo.log("disabling buttons");
23864             this.tb.items.each(function(item){
23865                 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
23866                     item.disable();
23867                 }
23868             });
23869           
23870         }else{
23871             Roo.log("enabling buttons");
23872             if(this.editorcore.initialized){
23873                 this.tb.items.each(function(item){
23874                     item.enable();
23875                 });
23876             }
23877             
23878         }
23879         Roo.log("calling toggole on editor");
23880         // tell the editor that it's been pressed..
23881         this.editor.toggleSourceEdit(sourceEditMode);
23882        
23883     },
23884      /**
23885      * Object collection of toolbar tooltips for the buttons in the editor. The key
23886      * is the command id associated with that button and the value is a valid QuickTips object.
23887      * For example:
23888 <pre><code>
23889 {
23890     bold : {
23891         title: 'Bold (Ctrl+B)',
23892         text: 'Make the selected text bold.',
23893         cls: 'x-html-editor-tip'
23894     },
23895     italic : {
23896         title: 'Italic (Ctrl+I)',
23897         text: 'Make the selected text italic.',
23898         cls: 'x-html-editor-tip'
23899     },
23900     ...
23901 </code></pre>
23902     * @type Object
23903      */
23904     buttonTips : {
23905         bold : {
23906             title: 'Bold (Ctrl+B)',
23907             text: 'Make the selected text bold.',
23908             cls: 'x-html-editor-tip'
23909         },
23910         italic : {
23911             title: 'Italic (Ctrl+I)',
23912             text: 'Make the selected text italic.',
23913             cls: 'x-html-editor-tip'
23914         },
23915         underline : {
23916             title: 'Underline (Ctrl+U)',
23917             text: 'Underline the selected text.',
23918             cls: 'x-html-editor-tip'
23919         },
23920         strikethrough : {
23921             title: 'Strikethrough',
23922             text: 'Strikethrough the selected text.',
23923             cls: 'x-html-editor-tip'
23924         },
23925         increasefontsize : {
23926             title: 'Grow Text',
23927             text: 'Increase the font size.',
23928             cls: 'x-html-editor-tip'
23929         },
23930         decreasefontsize : {
23931             title: 'Shrink Text',
23932             text: 'Decrease the font size.',
23933             cls: 'x-html-editor-tip'
23934         },
23935         backcolor : {
23936             title: 'Text Highlight Color',
23937             text: 'Change the background color of the selected text.',
23938             cls: 'x-html-editor-tip'
23939         },
23940         forecolor : {
23941             title: 'Font Color',
23942             text: 'Change the color of the selected text.',
23943             cls: 'x-html-editor-tip'
23944         },
23945         justifyleft : {
23946             title: 'Align Text Left',
23947             text: 'Align text to the left.',
23948             cls: 'x-html-editor-tip'
23949         },
23950         justifycenter : {
23951             title: 'Center Text',
23952             text: 'Center text in the editor.',
23953             cls: 'x-html-editor-tip'
23954         },
23955         justifyright : {
23956             title: 'Align Text Right',
23957             text: 'Align text to the right.',
23958             cls: 'x-html-editor-tip'
23959         },
23960         insertunorderedlist : {
23961             title: 'Bullet List',
23962             text: 'Start a bulleted list.',
23963             cls: 'x-html-editor-tip'
23964         },
23965         insertorderedlist : {
23966             title: 'Numbered List',
23967             text: 'Start a numbered list.',
23968             cls: 'x-html-editor-tip'
23969         },
23970         createlink : {
23971             title: 'Hyperlink',
23972             text: 'Make the selected text a hyperlink.',
23973             cls: 'x-html-editor-tip'
23974         },
23975         sourceedit : {
23976             title: 'Source Edit',
23977             text: 'Switch to source editing mode.',
23978             cls: 'x-html-editor-tip'
23979         }
23980     },
23981     // private
23982     onDestroy : function(){
23983         if(this.rendered){
23984             
23985             this.tb.items.each(function(item){
23986                 if(item.menu){
23987                     item.menu.removeAll();
23988                     if(item.menu.el){
23989                         item.menu.el.destroy();
23990                     }
23991                 }
23992                 item.destroy();
23993             });
23994              
23995         }
23996     },
23997     onFirstFocus: function() {
23998         this.tb.items.each(function(item){
23999            item.enable();
24000         });
24001     }
24002 });
24003
24004
24005
24006
24007 // <script type="text/javascript">
24008 /*
24009  * Based on
24010  * Ext JS Library 1.1.1
24011  * Copyright(c) 2006-2007, Ext JS, LLC.
24012  *  
24013  
24014  */
24015
24016  
24017 /**
24018  * @class Roo.form.HtmlEditor.ToolbarContext
24019  * Context Toolbar
24020  * 
24021  * Usage:
24022  *
24023  new Roo.form.HtmlEditor({
24024     ....
24025     toolbars : [
24026         { xtype: 'ToolbarStandard', styles : {} }
24027         { xtype: 'ToolbarContext', disable : {} }
24028     ]
24029 })
24030
24031      
24032  * 
24033  * @config : {Object} disable List of elements to disable.. (not done yet.)
24034  * @config : {Object} styles  Map of styles available.
24035  * 
24036  */
24037
24038 Roo.form.HtmlEditor.ToolbarContext = function(config)
24039 {
24040     
24041     Roo.apply(this, config);
24042     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
24043     // dont call parent... till later.
24044     this.styles = this.styles || {};
24045 }
24046
24047  
24048
24049 Roo.form.HtmlEditor.ToolbarContext.types = {
24050     'IMG' : {
24051         width : {
24052             title: "Width",
24053             width: 40
24054         },
24055         height:  {
24056             title: "Height",
24057             width: 40
24058         },
24059         align: {
24060             title: "Align",
24061             opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
24062             width : 80
24063             
24064         },
24065         border: {
24066             title: "Border",
24067             width: 40
24068         },
24069         alt: {
24070             title: "Alt",
24071             width: 120
24072         },
24073         src : {
24074             title: "Src",
24075             width: 220
24076         }
24077         
24078     },
24079     'A' : {
24080         name : {
24081             title: "Name",
24082             width: 50
24083         },
24084         target:  {
24085             title: "Target",
24086             width: 120
24087         },
24088         href:  {
24089             title: "Href",
24090             width: 220
24091         } // border?
24092         
24093     },
24094     'TABLE' : {
24095         rows : {
24096             title: "Rows",
24097             width: 20
24098         },
24099         cols : {
24100             title: "Cols",
24101             width: 20
24102         },
24103         width : {
24104             title: "Width",
24105             width: 40
24106         },
24107         height : {
24108             title: "Height",
24109             width: 40
24110         },
24111         border : {
24112             title: "Border",
24113             width: 20
24114         }
24115     },
24116     'TD' : {
24117         width : {
24118             title: "Width",
24119             width: 40
24120         },
24121         height : {
24122             title: "Height",
24123             width: 40
24124         },   
24125         align: {
24126             title: "Align",
24127             opts : [[""],[ "left"],[ "center"],[ "right"],[ "justify"],[ "char"]],
24128             width: 80
24129         },
24130         valign: {
24131             title: "Valign",
24132             opts : [[""],[ "top"],[ "middle"],[ "bottom"],[ "baseline"]],
24133             width: 80
24134         },
24135         colspan: {
24136             title: "Colspan",
24137             width: 20
24138             
24139         },
24140          'font-family'  : {
24141             title : "Font",
24142             style : 'fontFamily',
24143             displayField: 'display',
24144             optname : 'font-family',
24145             width: 140
24146         }
24147     },
24148     'INPUT' : {
24149         name : {
24150             title: "name",
24151             width: 120
24152         },
24153         value : {
24154             title: "Value",
24155             width: 120
24156         },
24157         width : {
24158             title: "Width",
24159             width: 40
24160         }
24161     },
24162     'LABEL' : {
24163         'for' : {
24164             title: "For",
24165             width: 120
24166         }
24167     },
24168     'TEXTAREA' : {
24169           name : {
24170             title: "name",
24171             width: 120
24172         },
24173         rows : {
24174             title: "Rows",
24175             width: 20
24176         },
24177         cols : {
24178             title: "Cols",
24179             width: 20
24180         }
24181     },
24182     'SELECT' : {
24183         name : {
24184             title: "name",
24185             width: 120
24186         },
24187         selectoptions : {
24188             title: "Options",
24189             width: 200
24190         }
24191     },
24192     
24193     // should we really allow this??
24194     // should this just be 
24195     'BODY' : {
24196         title : {
24197             title: "Title",
24198             width: 200,
24199             disabled : true
24200         }
24201     },
24202     'SPAN' : {
24203         'font-family'  : {
24204             title : "Font",
24205             style : 'fontFamily',
24206             displayField: 'display',
24207             optname : 'font-family',
24208             width: 140
24209         }
24210     },
24211     'DIV' : {
24212         'font-family'  : {
24213             title : "Font",
24214             style : 'fontFamily',
24215             displayField: 'display',
24216             optname : 'font-family',
24217             width: 140
24218         }
24219     },
24220      'P' : {
24221         'font-family'  : {
24222             title : "Font",
24223             style : 'fontFamily',
24224             displayField: 'display',
24225             optname : 'font-family',
24226             width: 140
24227         }
24228     },
24229     
24230     '*' : {
24231         // empty..
24232     }
24233
24234 };
24235
24236 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
24237 Roo.form.HtmlEditor.ToolbarContext.stores = false;
24238
24239 Roo.form.HtmlEditor.ToolbarContext.options = {
24240         'font-family'  : [ 
24241                 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
24242                 [ 'Courier New', 'Courier New'],
24243                 [ 'Tahoma', 'Tahoma'],
24244                 [ 'Times New Roman,serif', 'Times'],
24245                 [ 'Verdana','Verdana' ]
24246         ]
24247 };
24248
24249 // fixme - these need to be configurable..
24250  
24251
24252 //Roo.form.HtmlEditor.ToolbarContext.types
24253
24254
24255 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype,  {
24256     
24257     tb: false,
24258     
24259     rendered: false,
24260     
24261     editor : false,
24262     editorcore : false,
24263     /**
24264      * @cfg {Object} disable  List of toolbar elements to disable
24265          
24266      */
24267     disable : false,
24268     /**
24269      * @cfg {Object} styles List of styles 
24270      *    eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] } 
24271      *
24272      * These must be defined in the page, so they get rendered correctly..
24273      * .headline { }
24274      * TD.underline { }
24275      * 
24276      */
24277     styles : false,
24278     
24279     options: false,
24280     
24281     toolbars : false,
24282     
24283     init : function(editor)
24284     {
24285         this.editor = editor;
24286         this.editorcore = editor.editorcore ? editor.editorcore : editor;
24287         var editorcore = this.editorcore;
24288         
24289         var fid = editorcore.frameId;
24290         var etb = this;
24291         function btn(id, toggle, handler){
24292             var xid = fid + '-'+ id ;
24293             return {
24294                 id : xid,
24295                 cmd : id,
24296                 cls : 'x-btn-icon x-edit-'+id,
24297                 enableToggle:toggle !== false,
24298                 scope: editorcore, // was editor...
24299                 handler:handler||editorcore.relayBtnCmd,
24300                 clickEvent:'mousedown',
24301                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
24302                 tabIndex:-1
24303             };
24304         }
24305         // create a new element.
24306         var wdiv = editor.wrap.createChild({
24307                 tag: 'div'
24308             }, editor.wrap.dom.firstChild.nextSibling, true);
24309         
24310         // can we do this more than once??
24311         
24312          // stop form submits
24313       
24314  
24315         // disable everything...
24316         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
24317         this.toolbars = {};
24318            
24319         for (var i in  ty) {
24320           
24321             this.toolbars[i] = this.buildToolbar(ty[i],i);
24322         }
24323         this.tb = this.toolbars.BODY;
24324         this.tb.el.show();
24325         this.buildFooter();
24326         this.footer.show();
24327         editor.on('hide', function( ) { this.footer.hide() }, this);
24328         editor.on('show', function( ) { this.footer.show() }, this);
24329         
24330          
24331         this.rendered = true;
24332         
24333         // the all the btns;
24334         editor.on('editorevent', this.updateToolbar, this);
24335         // other toolbars need to implement this..
24336         //editor.on('editmodechange', this.updateToolbar, this);
24337     },
24338     
24339     
24340     
24341     /**
24342      * Protected method that will not generally be called directly. It triggers
24343      * a toolbar update by reading the markup state of the current selection in the editor.
24344      *
24345      * Note you can force an update by calling on('editorevent', scope, false)
24346      */
24347     updateToolbar: function(editor,ev,sel){
24348
24349         //Roo.log(ev);
24350         // capture mouse up - this is handy for selecting images..
24351         // perhaps should go somewhere else...
24352         if(!this.editorcore.activated){
24353              this.editor.onFirstFocus();
24354             return;
24355         }
24356         
24357         
24358         
24359         // http://developer.yahoo.com/yui/docs/simple-editor.js.html
24360         // selectNode - might want to handle IE?
24361         if (ev &&
24362             (ev.type == 'mouseup' || ev.type == 'click' ) &&
24363             ev.target && ev.target.tagName == 'IMG') {
24364             // they have click on an image...
24365             // let's see if we can change the selection...
24366             sel = ev.target;
24367          
24368               var nodeRange = sel.ownerDocument.createRange();
24369             try {
24370                 nodeRange.selectNode(sel);
24371             } catch (e) {
24372                 nodeRange.selectNodeContents(sel);
24373             }
24374             //nodeRange.collapse(true);
24375             var s = this.editorcore.win.getSelection();
24376             s.removeAllRanges();
24377             s.addRange(nodeRange);
24378         }  
24379         
24380       
24381         var updateFooter = sel ? false : true;
24382         
24383         
24384         var ans = this.editorcore.getAllAncestors();
24385         
24386         // pick
24387         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
24388         
24389         if (!sel) { 
24390             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editorcore.doc.body;
24391             sel = sel ? sel : this.editorcore.doc.body;
24392             sel = sel.tagName.length ? sel : this.editorcore.doc.body;
24393             
24394         }
24395         // pick a menu that exists..
24396         var tn = sel.tagName.toUpperCase();
24397         //sel = typeof(ty[tn]) != 'undefined' ? sel : this.editor.doc.body;
24398         
24399         tn = sel.tagName.toUpperCase();
24400         
24401         var lastSel = this.tb.selectedNode;
24402         
24403         this.tb.selectedNode = sel;
24404         
24405         // if current menu does not match..
24406         
24407         if ((this.tb.name != tn) || (lastSel != this.tb.selectedNode) || ev === false) {
24408                 
24409             this.tb.el.hide();
24410             ///console.log("show: " + tn);
24411             this.tb =  typeof(ty[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
24412             this.tb.el.show();
24413             // update name
24414             this.tb.items.first().el.innerHTML = tn + ':&nbsp;';
24415             
24416             
24417             // update attributes
24418             if (this.tb.fields) {
24419                 this.tb.fields.each(function(e) {
24420                     if (e.stylename) {
24421                         e.setValue(sel.style[e.stylename]);
24422                         return;
24423                     } 
24424                    e.setValue(sel.getAttribute(e.attrname));
24425                 });
24426             }
24427             
24428             var hasStyles = false;
24429             for(var i in this.styles) {
24430                 hasStyles = true;
24431                 break;
24432             }
24433             
24434             // update styles
24435             if (hasStyles) { 
24436                 var st = this.tb.fields.item(0);
24437                 
24438                 st.store.removeAll();
24439                
24440                 
24441                 var cn = sel.className.split(/\s+/);
24442                 
24443                 var avs = [];
24444                 if (this.styles['*']) {
24445                     
24446                     Roo.each(this.styles['*'], function(v) {
24447                         avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
24448                     });
24449                 }
24450                 if (this.styles[tn]) { 
24451                     Roo.each(this.styles[tn], function(v) {
24452                         avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
24453                     });
24454                 }
24455                 
24456                 st.store.loadData(avs);
24457                 st.collapse();
24458                 st.setValue(cn);
24459             }
24460             // flag our selected Node.
24461             this.tb.selectedNode = sel;
24462            
24463            
24464             Roo.menu.MenuMgr.hideAll();
24465
24466         }
24467         
24468         if (!updateFooter) {
24469             //this.footDisp.dom.innerHTML = ''; 
24470             return;
24471         }
24472         // update the footer
24473         //
24474         var html = '';
24475         
24476         this.footerEls = ans.reverse();
24477         Roo.each(this.footerEls, function(a,i) {
24478             if (!a) { return; }
24479             html += html.length ? ' &gt; '  :  '';
24480             
24481             html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
24482             
24483         });
24484        
24485         // 
24486         var sz = this.footDisp.up('td').getSize();
24487         this.footDisp.dom.style.width = (sz.width -10) + 'px';
24488         this.footDisp.dom.style.marginLeft = '5px';
24489         
24490         this.footDisp.dom.style.overflow = 'hidden';
24491         
24492         this.footDisp.dom.innerHTML = html;
24493             
24494         //this.editorsyncValue();
24495     },
24496      
24497     
24498    
24499        
24500     // private
24501     onDestroy : function(){
24502         if(this.rendered){
24503             
24504             this.tb.items.each(function(item){
24505                 if(item.menu){
24506                     item.menu.removeAll();
24507                     if(item.menu.el){
24508                         item.menu.el.destroy();
24509                     }
24510                 }
24511                 item.destroy();
24512             });
24513              
24514         }
24515     },
24516     onFirstFocus: function() {
24517         // need to do this for all the toolbars..
24518         this.tb.items.each(function(item){
24519            item.enable();
24520         });
24521     },
24522     buildToolbar: function(tlist, nm)
24523     {
24524         var editor = this.editor;
24525         var editorcore = this.editorcore;
24526          // create a new element.
24527         var wdiv = editor.wrap.createChild({
24528                 tag: 'div'
24529             }, editor.wrap.dom.firstChild.nextSibling, true);
24530         
24531        
24532         var tb = new Roo.Toolbar(wdiv);
24533         // add the name..
24534         
24535         tb.add(nm+ ":&nbsp;");
24536         
24537         var styles = [];
24538         for(var i in this.styles) {
24539             styles.push(i);
24540         }
24541         
24542         // styles...
24543         if (styles && styles.length) {
24544             
24545             // this needs a multi-select checkbox...
24546             tb.addField( new Roo.form.ComboBox({
24547                 store: new Roo.data.SimpleStore({
24548                     id : 'val',
24549                     fields: ['val', 'selected'],
24550                     data : [] 
24551                 }),
24552                 name : '-roo-edit-className',
24553                 attrname : 'className',
24554                 displayField: 'val',
24555                 typeAhead: false,
24556                 mode: 'local',
24557                 editable : false,
24558                 triggerAction: 'all',
24559                 emptyText:'Select Style',
24560                 selectOnFocus:true,
24561                 width: 130,
24562                 listeners : {
24563                     'select': function(c, r, i) {
24564                         // initial support only for on class per el..
24565                         tb.selectedNode.className =  r ? r.get('val') : '';
24566                         editorcore.syncValue();
24567                     }
24568                 }
24569     
24570             }));
24571         }
24572         
24573         var tbc = Roo.form.HtmlEditor.ToolbarContext;
24574         var tbops = tbc.options;
24575         
24576         for (var i in tlist) {
24577             
24578             var item = tlist[i];
24579             tb.add(item.title + ":&nbsp;");
24580             
24581             
24582             //optname == used so you can configure the options available..
24583             var opts = item.opts ? item.opts : false;
24584             if (item.optname) {
24585                 opts = tbops[item.optname];
24586            
24587             }
24588             
24589             if (opts) {
24590                 // opts == pulldown..
24591                 tb.addField( new Roo.form.ComboBox({
24592                     store:   typeof(tbc.stores[i]) != 'undefined' ?  Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
24593                         id : 'val',
24594                         fields: ['val', 'display'],
24595                         data : opts  
24596                     }),
24597                     name : '-roo-edit-' + i,
24598                     attrname : i,
24599                     stylename : item.style ? item.style : false,
24600                     displayField: item.displayField ? item.displayField : 'val',
24601                     valueField :  'val',
24602                     typeAhead: false,
24603                     mode: typeof(tbc.stores[i]) != 'undefined'  ? 'remote' : 'local',
24604                     editable : false,
24605                     triggerAction: 'all',
24606                     emptyText:'Select',
24607                     selectOnFocus:true,
24608                     width: item.width ? item.width  : 130,
24609                     listeners : {
24610                         'select': function(c, r, i) {
24611                             if (c.stylename) {
24612                                 tb.selectedNode.style[c.stylename] =  r.get('val');
24613                                 return;
24614                             }
24615                             if (r === false) {
24616                                 tb.selectedNode.removeAttribute(c.attrname);
24617                                 return;
24618                             }
24619                             tb.selectedNode.setAttribute(c.attrname, r.get('val'));
24620                         }
24621                     }
24622
24623                 }));
24624                 continue;
24625                     
24626                  
24627                 
24628                 tb.addField( new Roo.form.TextField({
24629                     name: i,
24630                     width: 100,
24631                     //allowBlank:false,
24632                     value: ''
24633                 }));
24634                 continue;
24635             }
24636             tb.addField( new Roo.form.TextField({
24637                 name: '-roo-edit-' + i,
24638                 attrname : i,
24639                 
24640                 width: item.width,
24641                 //allowBlank:true,
24642                 value: '',
24643                 listeners: {
24644                     'change' : function(f, nv, ov) {
24645                         tb.selectedNode.setAttribute(f.attrname, nv);
24646                         editorcore.syncValue();
24647                     }
24648                 }
24649             }));
24650              
24651         }
24652         
24653         var _this = this;
24654         
24655         if(nm == 'BODY'){
24656             tb.addSeparator();
24657         
24658             tb.addButton( {
24659                 text: 'Stylesheets',
24660
24661                 listeners : {
24662                     click : function ()
24663                     {
24664                         _this.editor.fireEvent('stylesheetsclick', _this.editor);
24665                     }
24666                 }
24667             });
24668         }
24669         
24670         tb.addFill();
24671         tb.addButton( {
24672             text: 'Remove Tag',
24673     
24674             listeners : {
24675                 click : function ()
24676                 {
24677                     // remove
24678                     // undo does not work.
24679                      
24680                     var sn = tb.selectedNode;
24681                     
24682                     var pn = sn.parentNode;
24683                     
24684                     var stn =  sn.childNodes[0];
24685                     var en = sn.childNodes[sn.childNodes.length - 1 ];
24686                     while (sn.childNodes.length) {
24687                         var node = sn.childNodes[0];
24688                         sn.removeChild(node);
24689                         //Roo.log(node);
24690                         pn.insertBefore(node, sn);
24691                         
24692                     }
24693                     pn.removeChild(sn);
24694                     var range = editorcore.createRange();
24695         
24696                     range.setStart(stn,0);
24697                     range.setEnd(en,0); //????
24698                     //range.selectNode(sel);
24699                     
24700                     
24701                     var selection = editorcore.getSelection();
24702                     selection.removeAllRanges();
24703                     selection.addRange(range);
24704                     
24705                     
24706                     
24707                     //_this.updateToolbar(null, null, pn);
24708                     _this.updateToolbar(null, null, null);
24709                     _this.footDisp.dom.innerHTML = ''; 
24710                 }
24711             }
24712             
24713                     
24714                 
24715             
24716         });
24717         
24718         
24719         tb.el.on('click', function(e){
24720             e.preventDefault(); // what does this do?
24721         });
24722         tb.el.setVisibilityMode( Roo.Element.DISPLAY);
24723         tb.el.hide();
24724         tb.name = nm;
24725         // dont need to disable them... as they will get hidden
24726         return tb;
24727          
24728         
24729     },
24730     buildFooter : function()
24731     {
24732         
24733         var fel = this.editor.wrap.createChild();
24734         this.footer = new Roo.Toolbar(fel);
24735         // toolbar has scrolly on left / right?
24736         var footDisp= new Roo.Toolbar.Fill();
24737         var _t = this;
24738         this.footer.add(
24739             {
24740                 text : '&lt;',
24741                 xtype: 'Button',
24742                 handler : function() {
24743                     _t.footDisp.scrollTo('left',0,true)
24744                 }
24745             }
24746         );
24747         this.footer.add( footDisp );
24748         this.footer.add( 
24749             {
24750                 text : '&gt;',
24751                 xtype: 'Button',
24752                 handler : function() {
24753                     // no animation..
24754                     _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
24755                 }
24756             }
24757         );
24758         var fel = Roo.get(footDisp.el);
24759         fel.addClass('x-editor-context');
24760         this.footDispWrap = fel; 
24761         this.footDispWrap.overflow  = 'hidden';
24762         
24763         this.footDisp = fel.createChild();
24764         this.footDispWrap.on('click', this.onContextClick, this)
24765         
24766         
24767     },
24768     onContextClick : function (ev,dom)
24769     {
24770         ev.preventDefault();
24771         var  cn = dom.className;
24772         //Roo.log(cn);
24773         if (!cn.match(/x-ed-loc-/)) {
24774             return;
24775         }
24776         var n = cn.split('-').pop();
24777         var ans = this.footerEls;
24778         var sel = ans[n];
24779         
24780          // pick
24781         var range = this.editorcore.createRange();
24782         
24783         range.selectNodeContents(sel);
24784         //range.selectNode(sel);
24785         
24786         
24787         var selection = this.editorcore.getSelection();
24788         selection.removeAllRanges();
24789         selection.addRange(range);
24790         
24791         
24792         
24793         this.updateToolbar(null, null, sel);
24794         
24795         
24796     }
24797     
24798     
24799     
24800     
24801     
24802 });
24803
24804
24805
24806
24807
24808 /*
24809  * Based on:
24810  * Ext JS Library 1.1.1
24811  * Copyright(c) 2006-2007, Ext JS, LLC.
24812  *
24813  * Originally Released Under LGPL - original licence link has changed is not relivant.
24814  *
24815  * Fork - LGPL
24816  * <script type="text/javascript">
24817  */
24818  
24819 /**
24820  * @class Roo.form.BasicForm
24821  * @extends Roo.util.Observable
24822  * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
24823  * @constructor
24824  * @param {String/HTMLElement/Roo.Element} el The form element or its id
24825  * @param {Object} config Configuration options
24826  */
24827 Roo.form.BasicForm = function(el, config){
24828     this.allItems = [];
24829     this.childForms = [];
24830     Roo.apply(this, config);
24831     /*
24832      * The Roo.form.Field items in this form.
24833      * @type MixedCollection
24834      */
24835      
24836      
24837     this.items = new Roo.util.MixedCollection(false, function(o){
24838         return o.id || (o.id = Roo.id());
24839     });
24840     this.addEvents({
24841         /**
24842          * @event beforeaction
24843          * Fires before any action is performed. Return false to cancel the action.
24844          * @param {Form} this
24845          * @param {Action} action The action to be performed
24846          */
24847         beforeaction: true,
24848         /**
24849          * @event actionfailed
24850          * Fires when an action fails.
24851          * @param {Form} this
24852          * @param {Action} action The action that failed
24853          */
24854         actionfailed : true,
24855         /**
24856          * @event actioncomplete
24857          * Fires when an action is completed.
24858          * @param {Form} this
24859          * @param {Action} action The action that completed
24860          */
24861         actioncomplete : true
24862     });
24863     if(el){
24864         this.initEl(el);
24865     }
24866     Roo.form.BasicForm.superclass.constructor.call(this);
24867     
24868     Roo.form.BasicForm.popover.apply();
24869 };
24870
24871 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
24872     /**
24873      * @cfg {String} method
24874      * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
24875      */
24876     /**
24877      * @cfg {DataReader} reader
24878      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
24879      * This is optional as there is built-in support for processing JSON.
24880      */
24881     /**
24882      * @cfg {DataReader} errorReader
24883      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
24884      * This is completely optional as there is built-in support for processing JSON.
24885      */
24886     /**
24887      * @cfg {String} url
24888      * The URL to use for form actions if one isn't supplied in the action options.
24889      */
24890     /**
24891      * @cfg {Boolean} fileUpload
24892      * Set to true if this form is a file upload.
24893      */
24894      
24895     /**
24896      * @cfg {Object} baseParams
24897      * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
24898      */
24899      /**
24900      
24901     /**
24902      * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
24903      */
24904     timeout: 30,
24905
24906     // private
24907     activeAction : null,
24908
24909     /**
24910      * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
24911      * or setValues() data instead of when the form was first created.
24912      */
24913     trackResetOnLoad : false,
24914     
24915     
24916     /**
24917      * childForms - used for multi-tab forms
24918      * @type {Array}
24919      */
24920     childForms : false,
24921     
24922     /**
24923      * allItems - full list of fields.
24924      * @type {Array}
24925      */
24926     allItems : false,
24927     
24928     /**
24929      * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
24930      * element by passing it or its id or mask the form itself by passing in true.
24931      * @type Mixed
24932      */
24933     waitMsgTarget : false,
24934     
24935     /**
24936      * @type Boolean
24937      */
24938     disableMask : false,
24939     
24940     /**
24941      * @cfg {Boolean} errorMask (true|false) default false
24942      */
24943     errorMask : false,
24944     
24945     /**
24946      * @cfg {Number} maskOffset Default 100
24947      */
24948     maskOffset : 100,
24949
24950     // private
24951     initEl : function(el){
24952         this.el = Roo.get(el);
24953         this.id = this.el.id || Roo.id();
24954         this.el.on('submit', this.onSubmit, this);
24955         this.el.addClass('x-form');
24956     },
24957
24958     // private
24959     onSubmit : function(e){
24960         e.stopEvent();
24961     },
24962
24963     /**
24964      * Returns true if client-side validation on the form is successful.
24965      * @return Boolean
24966      */
24967     isValid : function(){
24968         var valid = true;
24969         var target = false;
24970         this.items.each(function(f){
24971             if(f.validate()){
24972                 return;
24973             }
24974             
24975             valid = false;
24976                 
24977             if(!target && f.el.isVisible(true)){
24978                 target = f;
24979             }
24980         });
24981         
24982         if(this.errorMask && !valid){
24983             Roo.form.BasicForm.popover.mask(this, target);
24984         }
24985         
24986         return valid;
24987     },
24988     /**
24989      * Returns array of invalid form fields.
24990      * @return Array
24991      */
24992     
24993     invalidFields : function()
24994     {
24995         var ret = [];
24996         this.items.each(function(f){
24997             if(f.validate()){
24998                 return;
24999             }
25000             ret.push(f);
25001             
25002         });
25003         
25004         return ret;
25005     },
25006     
25007     
25008     /**
25009      * DEPRICATED Returns true if any fields in this form have changed since their original load. 
25010      * @return Boolean
25011      */
25012     isDirty : function(){
25013         var dirty = false;
25014         this.items.each(function(f){
25015            if(f.isDirty()){
25016                dirty = true;
25017                return false;
25018            }
25019         });
25020         return dirty;
25021     },
25022     
25023     /**
25024      * Returns true if any fields in this form have changed since their original load. (New version)
25025      * @return Boolean
25026      */
25027     
25028     hasChanged : function()
25029     {
25030         var dirty = false;
25031         this.items.each(function(f){
25032            if(f.hasChanged()){
25033                dirty = true;
25034                return false;
25035            }
25036         });
25037         return dirty;
25038         
25039     },
25040     /**
25041      * Resets all hasChanged to 'false' -
25042      * The old 'isDirty' used 'original value..' however this breaks reset() and a few other things.
25043      * So hasChanged storage is only to be used for this purpose
25044      * @return Boolean
25045      */
25046     resetHasChanged : function()
25047     {
25048         this.items.each(function(f){
25049            f.resetHasChanged();
25050         });
25051         
25052     },
25053     
25054     
25055     /**
25056      * Performs a predefined action (submit or load) or custom actions you define on this form.
25057      * @param {String} actionName The name of the action type
25058      * @param {Object} options (optional) The options to pass to the action.  All of the config options listed
25059      * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
25060      * accept other config options):
25061      * <pre>
25062 Property          Type             Description
25063 ----------------  ---------------  ----------------------------------------------------------------------------------
25064 url               String           The url for the action (defaults to the form's url)
25065 method            String           The form method to use (defaults to the form's method, or POST if not defined)
25066 params            String/Object    The params to pass (defaults to the form's baseParams, or none if not defined)
25067 clientValidation  Boolean          Applies to submit only.  Pass true to call form.isValid() prior to posting to
25068                                    validate the form on the client (defaults to false)
25069      * </pre>
25070      * @return {BasicForm} this
25071      */
25072     doAction : function(action, options){
25073         if(typeof action == 'string'){
25074             action = new Roo.form.Action.ACTION_TYPES[action](this, options);
25075         }
25076         if(this.fireEvent('beforeaction', this, action) !== false){
25077             this.beforeAction(action);
25078             action.run.defer(100, action);
25079         }
25080         return this;
25081     },
25082
25083     /**
25084      * Shortcut to do a submit action.
25085      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
25086      * @return {BasicForm} this
25087      */
25088     submit : function(options){
25089         this.doAction('submit', options);
25090         return this;
25091     },
25092
25093     /**
25094      * Shortcut to do a load action.
25095      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
25096      * @return {BasicForm} this
25097      */
25098     load : function(options){
25099         this.doAction('load', options);
25100         return this;
25101     },
25102
25103     /**
25104      * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
25105      * @param {Record} record The record to edit
25106      * @return {BasicForm} this
25107      */
25108     updateRecord : function(record){
25109         record.beginEdit();
25110         var fs = record.fields;
25111         fs.each(function(f){
25112             var field = this.findField(f.name);
25113             if(field){
25114                 record.set(f.name, field.getValue());
25115             }
25116         }, this);
25117         record.endEdit();
25118         return this;
25119     },
25120
25121     /**
25122      * Loads an Roo.data.Record into this form.
25123      * @param {Record} record The record to load
25124      * @return {BasicForm} this
25125      */
25126     loadRecord : function(record){
25127         this.setValues(record.data);
25128         return this;
25129     },
25130
25131     // private
25132     beforeAction : function(action){
25133         var o = action.options;
25134         
25135         if(!this.disableMask) {
25136             if(this.waitMsgTarget === true){
25137                 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
25138             }else if(this.waitMsgTarget){
25139                 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
25140                 this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
25141             }else {
25142                 Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
25143             }
25144         }
25145         
25146          
25147     },
25148
25149     // private
25150     afterAction : function(action, success){
25151         this.activeAction = null;
25152         var o = action.options;
25153         
25154         if(!this.disableMask) {
25155             if(this.waitMsgTarget === true){
25156                 this.el.unmask();
25157             }else if(this.waitMsgTarget){
25158                 this.waitMsgTarget.unmask();
25159             }else{
25160                 Roo.MessageBox.updateProgress(1);
25161                 Roo.MessageBox.hide();
25162             }
25163         }
25164         
25165         if(success){
25166             if(o.reset){
25167                 this.reset();
25168             }
25169             Roo.callback(o.success, o.scope, [this, action]);
25170             this.fireEvent('actioncomplete', this, action);
25171             
25172         }else{
25173             
25174             // failure condition..
25175             // we have a scenario where updates need confirming.
25176             // eg. if a locking scenario exists..
25177             // we look for { errors : { needs_confirm : true }} in the response.
25178             if (
25179                 (typeof(action.result) != 'undefined')  &&
25180                 (typeof(action.result.errors) != 'undefined')  &&
25181                 (typeof(action.result.errors.needs_confirm) != 'undefined')
25182            ){
25183                 var _t = this;
25184                 Roo.MessageBox.confirm(
25185                     "Change requires confirmation",
25186                     action.result.errorMsg,
25187                     function(r) {
25188                         if (r != 'yes') {
25189                             return;
25190                         }
25191                         _t.doAction('submit', { params :  { _submit_confirmed : 1 } }  );
25192                     }
25193                     
25194                 );
25195                 
25196                 
25197                 
25198                 return;
25199             }
25200             
25201             Roo.callback(o.failure, o.scope, [this, action]);
25202             // show an error message if no failed handler is set..
25203             if (!this.hasListener('actionfailed')) {
25204                 Roo.MessageBox.alert("Error",
25205                     (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
25206                         action.result.errorMsg :
25207                         "Saving Failed, please check your entries or try again"
25208                 );
25209             }
25210             
25211             this.fireEvent('actionfailed', this, action);
25212         }
25213         
25214     },
25215
25216     /**
25217      * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
25218      * @param {String} id The value to search for
25219      * @return Field
25220      */
25221     findField : function(id){
25222         var field = this.items.get(id);
25223         if(!field){
25224             this.items.each(function(f){
25225                 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
25226                     field = f;
25227                     return false;
25228                 }
25229             });
25230         }
25231         return field || null;
25232     },
25233
25234     /**
25235      * Add a secondary form to this one, 
25236      * Used to provide tabbed forms. One form is primary, with hidden values 
25237      * which mirror the elements from the other forms.
25238      * 
25239      * @param {Roo.form.Form} form to add.
25240      * 
25241      */
25242     addForm : function(form)
25243     {
25244        
25245         if (this.childForms.indexOf(form) > -1) {
25246             // already added..
25247             return;
25248         }
25249         this.childForms.push(form);
25250         var n = '';
25251         Roo.each(form.allItems, function (fe) {
25252             
25253             n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
25254             if (this.findField(n)) { // already added..
25255                 return;
25256             }
25257             var add = new Roo.form.Hidden({
25258                 name : n
25259             });
25260             add.render(this.el);
25261             
25262             this.add( add );
25263         }, this);
25264         
25265     },
25266     /**
25267      * Mark fields in this form invalid in bulk.
25268      * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
25269      * @return {BasicForm} this
25270      */
25271     markInvalid : function(errors){
25272         if(errors instanceof Array){
25273             for(var i = 0, len = errors.length; i < len; i++){
25274                 var fieldError = errors[i];
25275                 var f = this.findField(fieldError.id);
25276                 if(f){
25277                     f.markInvalid(fieldError.msg);
25278                 }
25279             }
25280         }else{
25281             var field, id;
25282             for(id in errors){
25283                 if(typeof errors[id] != 'function' && (field = this.findField(id))){
25284                     field.markInvalid(errors[id]);
25285                 }
25286             }
25287         }
25288         Roo.each(this.childForms || [], function (f) {
25289             f.markInvalid(errors);
25290         });
25291         
25292         return this;
25293     },
25294
25295     /**
25296      * Set values for fields in this form in bulk.
25297      * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
25298      * @return {BasicForm} this
25299      */
25300     setValues : function(values){
25301         if(values instanceof Array){ // array of objects
25302             for(var i = 0, len = values.length; i < len; i++){
25303                 var v = values[i];
25304                 var f = this.findField(v.id);
25305                 if(f){
25306                     f.setValue(v.value);
25307                     if(this.trackResetOnLoad){
25308                         f.originalValue = f.getValue();
25309                     }
25310                 }
25311             }
25312         }else{ // object hash
25313             var field, id;
25314             for(id in values){
25315                 if(typeof values[id] != 'function' && (field = this.findField(id))){
25316                     
25317                     if (field.setFromData && 
25318                         field.valueField && 
25319                         field.displayField &&
25320                         // combos' with local stores can 
25321                         // be queried via setValue()
25322                         // to set their value..
25323                         (field.store && !field.store.isLocal)
25324                         ) {
25325                         // it's a combo
25326                         var sd = { };
25327                         sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
25328                         sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
25329                         field.setFromData(sd);
25330                         
25331                     } else {
25332                         field.setValue(values[id]);
25333                     }
25334                     
25335                     
25336                     if(this.trackResetOnLoad){
25337                         field.originalValue = field.getValue();
25338                     }
25339                 }
25340             }
25341         }
25342         this.resetHasChanged();
25343         
25344         
25345         Roo.each(this.childForms || [], function (f) {
25346             f.setValues(values);
25347             f.resetHasChanged();
25348         });
25349                 
25350         return this;
25351     },
25352  
25353     /**
25354      * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
25355      * they are returned as an array.
25356      * @param {Boolean} asString
25357      * @return {Object}
25358      */
25359     getValues : function(asString){
25360         if (this.childForms) {
25361             // copy values from the child forms
25362             Roo.each(this.childForms, function (f) {
25363                 this.setValues(f.getValues());
25364             }, this);
25365         }
25366         
25367         // use formdata
25368         if (typeof(FormData) != 'undefined' && asString !== true) {
25369             // this relies on a 'recent' version of chrome apparently...
25370             try {
25371                 var fd = (new FormData(this.el.dom)).entries();
25372                 var ret = {};
25373                 var ent = fd.next();
25374                 while (!ent.done) {
25375                     ret[ent.value[0]] = ent.value[1]; // not sure how this will handle duplicates..
25376                     ent = fd.next();
25377                 };
25378                 return ret;
25379             } catch(e) {
25380                 
25381             }
25382             
25383         }
25384         
25385         
25386         var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
25387         if(asString === true){
25388             return fs;
25389         }
25390         return Roo.urlDecode(fs);
25391     },
25392     
25393     /**
25394      * Returns the fields in this form as an object with key/value pairs. 
25395      * This differs from getValues as it calls getValue on each child item, rather than using dom data.
25396      * @return {Object}
25397      */
25398     getFieldValues : function(with_hidden)
25399     {
25400         if (this.childForms) {
25401             // copy values from the child forms
25402             // should this call getFieldValues - probably not as we do not currently copy
25403             // hidden fields when we generate..
25404             Roo.each(this.childForms, function (f) {
25405                 this.setValues(f.getValues());
25406             }, this);
25407         }
25408         
25409         var ret = {};
25410         this.items.each(function(f){
25411             if (!f.getName()) {
25412                 return;
25413             }
25414             var v = f.getValue();
25415             if (f.inputType =='radio') {
25416                 if (typeof(ret[f.getName()]) == 'undefined') {
25417                     ret[f.getName()] = ''; // empty..
25418                 }
25419                 
25420                 if (!f.el.dom.checked) {
25421                     return;
25422                     
25423                 }
25424                 v = f.el.dom.value;
25425                 
25426             }
25427             
25428             // not sure if this supported any more..
25429             if ((typeof(v) == 'object') && f.getRawValue) {
25430                 v = f.getRawValue() ; // dates..
25431             }
25432             // combo boxes where name != hiddenName...
25433             if (f.name != f.getName()) {
25434                 ret[f.name] = f.getRawValue();
25435             }
25436             ret[f.getName()] = v;
25437         });
25438         
25439         return ret;
25440     },
25441
25442     /**
25443      * Clears all invalid messages in this form.
25444      * @return {BasicForm} this
25445      */
25446     clearInvalid : function(){
25447         this.items.each(function(f){
25448            f.clearInvalid();
25449         });
25450         
25451         Roo.each(this.childForms || [], function (f) {
25452             f.clearInvalid();
25453         });
25454         
25455         
25456         return this;
25457     },
25458
25459     /**
25460      * Resets this form.
25461      * @return {BasicForm} this
25462      */
25463     reset : function(){
25464         this.items.each(function(f){
25465             f.reset();
25466         });
25467         
25468         Roo.each(this.childForms || [], function (f) {
25469             f.reset();
25470         });
25471         this.resetHasChanged();
25472         
25473         return this;
25474     },
25475
25476     /**
25477      * Add Roo.form components to this form.
25478      * @param {Field} field1
25479      * @param {Field} field2 (optional)
25480      * @param {Field} etc (optional)
25481      * @return {BasicForm} this
25482      */
25483     add : function(){
25484         this.items.addAll(Array.prototype.slice.call(arguments, 0));
25485         return this;
25486     },
25487
25488
25489     /**
25490      * Removes a field from the items collection (does NOT remove its markup).
25491      * @param {Field} field
25492      * @return {BasicForm} this
25493      */
25494     remove : function(field){
25495         this.items.remove(field);
25496         return this;
25497     },
25498
25499     /**
25500      * Looks at the fields in this form, checks them for an id attribute,
25501      * and calls applyTo on the existing dom element with that id.
25502      * @return {BasicForm} this
25503      */
25504     render : function(){
25505         this.items.each(function(f){
25506             if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
25507                 f.applyTo(f.id);
25508             }
25509         });
25510         return this;
25511     },
25512
25513     /**
25514      * Calls {@link Ext#apply} for all fields in this form with the passed object.
25515      * @param {Object} values
25516      * @return {BasicForm} this
25517      */
25518     applyToFields : function(o){
25519         this.items.each(function(f){
25520            Roo.apply(f, o);
25521         });
25522         return this;
25523     },
25524
25525     /**
25526      * Calls {@link Ext#applyIf} for all field in this form with the passed object.
25527      * @param {Object} values
25528      * @return {BasicForm} this
25529      */
25530     applyIfToFields : function(o){
25531         this.items.each(function(f){
25532            Roo.applyIf(f, o);
25533         });
25534         return this;
25535     }
25536 });
25537
25538 // back compat
25539 Roo.BasicForm = Roo.form.BasicForm;
25540
25541 Roo.apply(Roo.form.BasicForm, {
25542     
25543     popover : {
25544         
25545         padding : 5,
25546         
25547         isApplied : false,
25548         
25549         isMasked : false,
25550         
25551         form : false,
25552         
25553         target : false,
25554         
25555         intervalID : false,
25556         
25557         maskEl : false,
25558         
25559         apply : function()
25560         {
25561             if(this.isApplied){
25562                 return;
25563             }
25564             
25565             this.maskEl = {
25566                 top : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-top-mask" }, true),
25567                 left : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-left-mask" }, true),
25568                 bottom : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-bottom-mask" }, true),
25569                 right : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-right-mask" }, true)
25570             };
25571             
25572             this.maskEl.top.enableDisplayMode("block");
25573             this.maskEl.left.enableDisplayMode("block");
25574             this.maskEl.bottom.enableDisplayMode("block");
25575             this.maskEl.right.enableDisplayMode("block");
25576             
25577             Roo.get(document.body).on('click', function(){
25578                 this.unmask();
25579             }, this);
25580             
25581             Roo.get(document.body).on('touchstart', function(){
25582                 this.unmask();
25583             }, this);
25584             
25585             this.isApplied = true
25586         },
25587         
25588         mask : function(form, target)
25589         {
25590             this.form = form;
25591             
25592             this.target = target;
25593             
25594             if(!this.form.errorMask || !target.el){
25595                 return;
25596             }
25597             
25598             var scrollable = this.target.el.findScrollableParent() || this.target.el.findParent('div.x-layout-active-content', 100, true) || Roo.get(document.body);
25599             
25600             var ot = this.target.el.calcOffsetsTo(scrollable);
25601             
25602             var scrollTo = ot[1] - this.form.maskOffset;
25603             
25604             scrollTo = Math.min(scrollTo, scrollable.dom.scrollHeight);
25605             
25606             scrollable.scrollTo('top', scrollTo);
25607             
25608             var el = this.target.wrap || this.target.el;
25609             
25610             var box = el.getBox();
25611             
25612             this.maskEl.top.setStyle('position', 'absolute');
25613             this.maskEl.top.setStyle('z-index', 10000);
25614             this.maskEl.top.setSize(Roo.lib.Dom.getDocumentWidth(), box.y - this.padding);
25615             this.maskEl.top.setLeft(0);
25616             this.maskEl.top.setTop(0);
25617             this.maskEl.top.show();
25618             
25619             this.maskEl.left.setStyle('position', 'absolute');
25620             this.maskEl.left.setStyle('z-index', 10000);
25621             this.maskEl.left.setSize(box.x - this.padding, box.height + this.padding * 2);
25622             this.maskEl.left.setLeft(0);
25623             this.maskEl.left.setTop(box.y - this.padding);
25624             this.maskEl.left.show();
25625
25626             this.maskEl.bottom.setStyle('position', 'absolute');
25627             this.maskEl.bottom.setStyle('z-index', 10000);
25628             this.maskEl.bottom.setSize(Roo.lib.Dom.getDocumentWidth(), Roo.lib.Dom.getDocumentHeight() - box.bottom - this.padding);
25629             this.maskEl.bottom.setLeft(0);
25630             this.maskEl.bottom.setTop(box.bottom + this.padding);
25631             this.maskEl.bottom.show();
25632
25633             this.maskEl.right.setStyle('position', 'absolute');
25634             this.maskEl.right.setStyle('z-index', 10000);
25635             this.maskEl.right.setSize(Roo.lib.Dom.getDocumentWidth() - box.right - this.padding, box.height + this.padding * 2);
25636             this.maskEl.right.setLeft(box.right + this.padding);
25637             this.maskEl.right.setTop(box.y - this.padding);
25638             this.maskEl.right.show();
25639
25640             this.intervalID = window.setInterval(function() {
25641                 Roo.form.BasicForm.popover.unmask();
25642             }, 10000);
25643
25644             window.onwheel = function(){ return false;};
25645             
25646             (function(){ this.isMasked = true; }).defer(500, this);
25647             
25648         },
25649         
25650         unmask : function()
25651         {
25652             if(!this.isApplied || !this.isMasked || !this.form || !this.target || !this.form.errorMask){
25653                 return;
25654             }
25655             
25656             this.maskEl.top.setStyle('position', 'absolute');
25657             this.maskEl.top.setSize(0, 0).setXY([0, 0]);
25658             this.maskEl.top.hide();
25659
25660             this.maskEl.left.setStyle('position', 'absolute');
25661             this.maskEl.left.setSize(0, 0).setXY([0, 0]);
25662             this.maskEl.left.hide();
25663
25664             this.maskEl.bottom.setStyle('position', 'absolute');
25665             this.maskEl.bottom.setSize(0, 0).setXY([0, 0]);
25666             this.maskEl.bottom.hide();
25667
25668             this.maskEl.right.setStyle('position', 'absolute');
25669             this.maskEl.right.setSize(0, 0).setXY([0, 0]);
25670             this.maskEl.right.hide();
25671             
25672             window.onwheel = function(){ return true;};
25673             
25674             if(this.intervalID){
25675                 window.clearInterval(this.intervalID);
25676                 this.intervalID = false;
25677             }
25678             
25679             this.isMasked = false;
25680             
25681         }
25682         
25683     }
25684     
25685 });/*
25686  * Based on:
25687  * Ext JS Library 1.1.1
25688  * Copyright(c) 2006-2007, Ext JS, LLC.
25689  *
25690  * Originally Released Under LGPL - original licence link has changed is not relivant.
25691  *
25692  * Fork - LGPL
25693  * <script type="text/javascript">
25694  */
25695
25696 /**
25697  * @class Roo.form.Form
25698  * @extends Roo.form.BasicForm
25699  * @children Roo.form.Column Roo.form.FieldSet Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
25700  * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
25701  * @constructor
25702  * @param {Object} config Configuration options
25703  */
25704 Roo.form.Form = function(config){
25705     var xitems =  [];
25706     if (config.items) {
25707         xitems = config.items;
25708         delete config.items;
25709     }
25710    
25711     
25712     Roo.form.Form.superclass.constructor.call(this, null, config);
25713     this.url = this.url || this.action;
25714     if(!this.root){
25715         this.root = new Roo.form.Layout(Roo.applyIf({
25716             id: Roo.id()
25717         }, config));
25718     }
25719     this.active = this.root;
25720     /**
25721      * Array of all the buttons that have been added to this form via {@link addButton}
25722      * @type Array
25723      */
25724     this.buttons = [];
25725     this.allItems = [];
25726     this.addEvents({
25727         /**
25728          * @event clientvalidation
25729          * If the monitorValid config option is true, this event fires repetitively to notify of valid state
25730          * @param {Form} this
25731          * @param {Boolean} valid true if the form has passed client-side validation
25732          */
25733         clientvalidation: true,
25734         /**
25735          * @event rendered
25736          * Fires when the form is rendered
25737          * @param {Roo.form.Form} form
25738          */
25739         rendered : true
25740     });
25741     
25742     if (this.progressUrl) {
25743             // push a hidden field onto the list of fields..
25744             this.addxtype( {
25745                     xns: Roo.form, 
25746                     xtype : 'Hidden', 
25747                     name : 'UPLOAD_IDENTIFIER' 
25748             });
25749         }
25750         
25751     
25752     Roo.each(xitems, this.addxtype, this);
25753     
25754 };
25755
25756 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
25757      /**
25758      * @cfg {Roo.Button} buttons[] buttons at bottom of form
25759      */
25760     
25761     /**
25762      * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
25763      */
25764     /**
25765      * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
25766      */
25767     /**
25768      * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
25769      */
25770     buttonAlign:'center',
25771
25772     /**
25773      * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
25774      */
25775     minButtonWidth:75,
25776
25777     /**
25778      * @cfg {String} labelAlign Valid values are "left," "top" and "right" (defaults to "left").
25779      * This property cascades to child containers if not set.
25780      */
25781     labelAlign:'left',
25782
25783     /**
25784      * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
25785      * fires a looping event with that state. This is required to bind buttons to the valid
25786      * state using the config value formBind:true on the button.
25787      */
25788     monitorValid : false,
25789
25790     /**
25791      * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
25792      */
25793     monitorPoll : 200,
25794     
25795     /**
25796      * @cfg {String} progressUrl - Url to return progress data 
25797      */
25798     
25799     progressUrl : false,
25800     /**
25801      * @cfg {boolean|FormData} formData - true to use new 'FormData' post, or set to a new FormData({dom form}) Object, if
25802      * sending a formdata with extra parameters - eg uploaded elements.
25803      */
25804     
25805     formData : false,
25806     
25807     /**
25808      * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
25809      * fields are added and the column is closed. If no fields are passed the column remains open
25810      * until end() is called.
25811      * @param {Object} config The config to pass to the column
25812      * @param {Field} field1 (optional)
25813      * @param {Field} field2 (optional)
25814      * @param {Field} etc (optional)
25815      * @return Column The column container object
25816      */
25817     column : function(c){
25818         var col = new Roo.form.Column(c);
25819         this.start(col);
25820         if(arguments.length > 1){ // duplicate code required because of Opera
25821             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
25822             this.end();
25823         }
25824         return col;
25825     },
25826
25827     /**
25828      * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
25829      * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
25830      * until end() is called.
25831      * @param {Object} config The config to pass to the fieldset
25832      * @param {Field} field1 (optional)
25833      * @param {Field} field2 (optional)
25834      * @param {Field} etc (optional)
25835      * @return FieldSet The fieldset container object
25836      */
25837     fieldset : function(c){
25838         var fs = new Roo.form.FieldSet(c);
25839         this.start(fs);
25840         if(arguments.length > 1){ // duplicate code required because of Opera
25841             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
25842             this.end();
25843         }
25844         return fs;
25845     },
25846
25847     /**
25848      * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
25849      * fields are added and the container is closed. If no fields are passed the container remains open
25850      * until end() is called.
25851      * @param {Object} config The config to pass to the Layout
25852      * @param {Field} field1 (optional)
25853      * @param {Field} field2 (optional)
25854      * @param {Field} etc (optional)
25855      * @return Layout The container object
25856      */
25857     container : function(c){
25858         var l = new Roo.form.Layout(c);
25859         this.start(l);
25860         if(arguments.length > 1){ // duplicate code required because of Opera
25861             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
25862             this.end();
25863         }
25864         return l;
25865     },
25866
25867     /**
25868      * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
25869      * @param {Object} container A Roo.form.Layout or subclass of Layout
25870      * @return {Form} this
25871      */
25872     start : function(c){
25873         // cascade label info
25874         Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
25875         this.active.stack.push(c);
25876         c.ownerCt = this.active;
25877         this.active = c;
25878         return this;
25879     },
25880
25881     /**
25882      * Closes the current open container
25883      * @return {Form} this
25884      */
25885     end : function(){
25886         if(this.active == this.root){
25887             return this;
25888         }
25889         this.active = this.active.ownerCt;
25890         return this;
25891     },
25892
25893     /**
25894      * Add Roo.form components to the current open container (e.g. column, fieldset, etc.).  Fields added via this method
25895      * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
25896      * as the label of the field.
25897      * @param {Field} field1
25898      * @param {Field} field2 (optional)
25899      * @param {Field} etc. (optional)
25900      * @return {Form} this
25901      */
25902     add : function(){
25903         this.active.stack.push.apply(this.active.stack, arguments);
25904         this.allItems.push.apply(this.allItems,arguments);
25905         var r = [];
25906         for(var i = 0, a = arguments, len = a.length; i < len; i++) {
25907             if(a[i].isFormField){
25908                 r.push(a[i]);
25909             }
25910         }
25911         if(r.length > 0){
25912             Roo.form.Form.superclass.add.apply(this, r);
25913         }
25914         return this;
25915     },
25916     
25917
25918     
25919     
25920     
25921      /**
25922      * Find any element that has been added to a form, using it's ID or name
25923      * This can include framesets, columns etc. along with regular fields..
25924      * @param {String} id - id or name to find.
25925      
25926      * @return {Element} e - or false if nothing found.
25927      */
25928     findbyId : function(id)
25929     {
25930         var ret = false;
25931         if (!id) {
25932             return ret;
25933         }
25934         Roo.each(this.allItems, function(f){
25935             if (f.id == id || f.name == id ){
25936                 ret = f;
25937                 return false;
25938             }
25939         });
25940         return ret;
25941     },
25942
25943     
25944     
25945     /**
25946      * Render this form into the passed container. This should only be called once!
25947      * @param {String/HTMLElement/Element} container The element this component should be rendered into
25948      * @return {Form} this
25949      */
25950     render : function(ct)
25951     {
25952         
25953         
25954         
25955         ct = Roo.get(ct);
25956         var o = this.autoCreate || {
25957             tag: 'form',
25958             method : this.method || 'POST',
25959             id : this.id || Roo.id()
25960         };
25961         this.initEl(ct.createChild(o));
25962
25963         this.root.render(this.el);
25964         
25965        
25966              
25967         this.items.each(function(f){
25968             f.render('x-form-el-'+f.id);
25969         });
25970
25971         if(this.buttons.length > 0){
25972             // tables are required to maintain order and for correct IE layout
25973             var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
25974                 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
25975                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
25976             }}, null, true);
25977             var tr = tb.getElementsByTagName('tr')[0];
25978             for(var i = 0, len = this.buttons.length; i < len; i++) {
25979                 var b = this.buttons[i];
25980                 var td = document.createElement('td');
25981                 td.className = 'x-form-btn-td';
25982                 b.render(tr.appendChild(td));
25983             }
25984         }
25985         if(this.monitorValid){ // initialize after render
25986             this.startMonitoring();
25987         }
25988         this.fireEvent('rendered', this);
25989         return this;
25990     },
25991
25992     /**
25993      * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
25994      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
25995      * object or a valid Roo.DomHelper element config
25996      * @param {Function} handler The function called when the button is clicked
25997      * @param {Object} scope (optional) The scope of the handler function
25998      * @return {Roo.Button}
25999      */
26000     addButton : function(config, handler, scope){
26001         var bc = {
26002             handler: handler,
26003             scope: scope,
26004             minWidth: this.minButtonWidth,
26005             hideParent:true
26006         };
26007         if(typeof config == "string"){
26008             bc.text = config;
26009         }else{
26010             Roo.apply(bc, config);
26011         }
26012         var btn = new Roo.Button(null, bc);
26013         this.buttons.push(btn);
26014         return btn;
26015     },
26016
26017      /**
26018      * Adds a series of form elements (using the xtype property as the factory method.
26019      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
26020      * @param {Object} config 
26021      */
26022     
26023     addxtype : function()
26024     {
26025         var ar = Array.prototype.slice.call(arguments, 0);
26026         var ret = false;
26027         for(var i = 0; i < ar.length; i++) {
26028             if (!ar[i]) {
26029                 continue; // skip -- if this happends something invalid got sent, we 
26030                 // should ignore it, as basically that interface element will not show up
26031                 // and that should be pretty obvious!!
26032             }
26033             
26034             if (Roo.form[ar[i].xtype]) {
26035                 ar[i].form = this;
26036                 var fe = Roo.factory(ar[i], Roo.form);
26037                 if (!ret) {
26038                     ret = fe;
26039                 }
26040                 fe.form = this;
26041                 if (fe.store) {
26042                     fe.store.form = this;
26043                 }
26044                 if (fe.isLayout) {  
26045                          
26046                     this.start(fe);
26047                     this.allItems.push(fe);
26048                     if (fe.items && fe.addxtype) {
26049                         fe.addxtype.apply(fe, fe.items);
26050                         delete fe.items;
26051                     }
26052                      this.end();
26053                     continue;
26054                 }
26055                 
26056                 
26057                  
26058                 this.add(fe);
26059               //  console.log('adding ' + ar[i].xtype);
26060             }
26061             if (ar[i].xtype == 'Button') {  
26062                 //console.log('adding button');
26063                 //console.log(ar[i]);
26064                 this.addButton(ar[i]);
26065                 this.allItems.push(fe);
26066                 continue;
26067             }
26068             
26069             if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
26070                 alert('end is not supported on xtype any more, use items');
26071             //    this.end();
26072             //    //console.log('adding end');
26073             }
26074             
26075         }
26076         return ret;
26077     },
26078     
26079     /**
26080      * Starts monitoring of the valid state of this form. Usually this is done by passing the config
26081      * option "monitorValid"
26082      */
26083     startMonitoring : function(){
26084         if(!this.bound){
26085             this.bound = true;
26086             Roo.TaskMgr.start({
26087                 run : this.bindHandler,
26088                 interval : this.monitorPoll || 200,
26089                 scope: this
26090             });
26091         }
26092     },
26093
26094     /**
26095      * Stops monitoring of the valid state of this form
26096      */
26097     stopMonitoring : function(){
26098         this.bound = false;
26099     },
26100
26101     // private
26102     bindHandler : function(){
26103         if(!this.bound){
26104             return false; // stops binding
26105         }
26106         var valid = true;
26107         this.items.each(function(f){
26108             if(!f.isValid(true)){
26109                 valid = false;
26110                 return false;
26111             }
26112         });
26113         for(var i = 0, len = this.buttons.length; i < len; i++){
26114             var btn = this.buttons[i];
26115             if(btn.formBind === true && btn.disabled === valid){
26116                 btn.setDisabled(!valid);
26117             }
26118         }
26119         this.fireEvent('clientvalidation', this, valid);
26120     }
26121     
26122     
26123     
26124     
26125     
26126     
26127     
26128     
26129 });
26130
26131
26132 // back compat
26133 Roo.Form = Roo.form.Form;
26134 /*
26135  * Based on:
26136  * Ext JS Library 1.1.1
26137  * Copyright(c) 2006-2007, Ext JS, LLC.
26138  *
26139  * Originally Released Under LGPL - original licence link has changed is not relivant.
26140  *
26141  * Fork - LGPL
26142  * <script type="text/javascript">
26143  */
26144
26145 // as we use this in bootstrap.
26146 Roo.namespace('Roo.form');
26147  /**
26148  * @class Roo.form.Action
26149  * Internal Class used to handle form actions
26150  * @constructor
26151  * @param {Roo.form.BasicForm} el The form element or its id
26152  * @param {Object} config Configuration options
26153  */
26154
26155  
26156  
26157 // define the action interface
26158 Roo.form.Action = function(form, options){
26159     this.form = form;
26160     this.options = options || {};
26161 };
26162 /**
26163  * Client Validation Failed
26164  * @const 
26165  */
26166 Roo.form.Action.CLIENT_INVALID = 'client';
26167 /**
26168  * Server Validation Failed
26169  * @const 
26170  */
26171 Roo.form.Action.SERVER_INVALID = 'server';
26172  /**
26173  * Connect to Server Failed
26174  * @const 
26175  */
26176 Roo.form.Action.CONNECT_FAILURE = 'connect';
26177 /**
26178  * Reading Data from Server Failed
26179  * @const 
26180  */
26181 Roo.form.Action.LOAD_FAILURE = 'load';
26182
26183 Roo.form.Action.prototype = {
26184     type : 'default',
26185     failureType : undefined,
26186     response : undefined,
26187     result : undefined,
26188
26189     // interface method
26190     run : function(options){
26191
26192     },
26193
26194     // interface method
26195     success : function(response){
26196
26197     },
26198
26199     // interface method
26200     handleResponse : function(response){
26201
26202     },
26203
26204     // default connection failure
26205     failure : function(response){
26206         
26207         this.response = response;
26208         this.failureType = Roo.form.Action.CONNECT_FAILURE;
26209         this.form.afterAction(this, false);
26210     },
26211
26212     processResponse : function(response){
26213         this.response = response;
26214         if(!response.responseText){
26215             return true;
26216         }
26217         this.result = this.handleResponse(response);
26218         return this.result;
26219     },
26220
26221     // utility functions used internally
26222     getUrl : function(appendParams){
26223         var url = this.options.url || this.form.url || this.form.el.dom.action;
26224         if(appendParams){
26225             var p = this.getParams();
26226             if(p){
26227                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
26228             }
26229         }
26230         return url;
26231     },
26232
26233     getMethod : function(){
26234         return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
26235     },
26236
26237     getParams : function(){
26238         var bp = this.form.baseParams;
26239         var p = this.options.params;
26240         if(p){
26241             if(typeof p == "object"){
26242                 p = Roo.urlEncode(Roo.applyIf(p, bp));
26243             }else if(typeof p == 'string' && bp){
26244                 p += '&' + Roo.urlEncode(bp);
26245             }
26246         }else if(bp){
26247             p = Roo.urlEncode(bp);
26248         }
26249         return p;
26250     },
26251
26252     createCallback : function(){
26253         return {
26254             success: this.success,
26255             failure: this.failure,
26256             scope: this,
26257             timeout: (this.form.timeout*1000),
26258             upload: this.form.fileUpload ? this.success : undefined
26259         };
26260     }
26261 };
26262
26263 Roo.form.Action.Submit = function(form, options){
26264     Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
26265 };
26266
26267 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
26268     type : 'submit',
26269
26270     haveProgress : false,
26271     uploadComplete : false,
26272     
26273     // uploadProgress indicator.
26274     uploadProgress : function()
26275     {
26276         if (!this.form.progressUrl) {
26277             return;
26278         }
26279         
26280         if (!this.haveProgress) {
26281             Roo.MessageBox.progress("Uploading", "Uploading");
26282         }
26283         if (this.uploadComplete) {
26284            Roo.MessageBox.hide();
26285            return;
26286         }
26287         
26288         this.haveProgress = true;
26289    
26290         var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
26291         
26292         var c = new Roo.data.Connection();
26293         c.request({
26294             url : this.form.progressUrl,
26295             params: {
26296                 id : uid
26297             },
26298             method: 'GET',
26299             success : function(req){
26300                //console.log(data);
26301                 var rdata = false;
26302                 var edata;
26303                 try  {
26304                    rdata = Roo.decode(req.responseText)
26305                 } catch (e) {
26306                     Roo.log("Invalid data from server..");
26307                     Roo.log(edata);
26308                     return;
26309                 }
26310                 if (!rdata || !rdata.success) {
26311                     Roo.log(rdata);
26312                     Roo.MessageBox.alert(Roo.encode(rdata));
26313                     return;
26314                 }
26315                 var data = rdata.data;
26316                 
26317                 if (this.uploadComplete) {
26318                    Roo.MessageBox.hide();
26319                    return;
26320                 }
26321                    
26322                 if (data){
26323                     Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
26324                        Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
26325                     );
26326                 }
26327                 this.uploadProgress.defer(2000,this);
26328             },
26329        
26330             failure: function(data) {
26331                 Roo.log('progress url failed ');
26332                 Roo.log(data);
26333             },
26334             scope : this
26335         });
26336            
26337     },
26338     
26339     
26340     run : function()
26341     {
26342         // run get Values on the form, so it syncs any secondary forms.
26343         this.form.getValues();
26344         
26345         var o = this.options;
26346         var method = this.getMethod();
26347         var isPost = method == 'POST';
26348         if(o.clientValidation === false || this.form.isValid()){
26349             
26350             if (this.form.progressUrl) {
26351                 this.form.findField('UPLOAD_IDENTIFIER').setValue(
26352                     (new Date() * 1) + '' + Math.random());
26353                     
26354             } 
26355             
26356             
26357             Roo.Ajax.request(Roo.apply(this.createCallback(), {
26358                 form:this.form.el.dom,
26359                 url:this.getUrl(!isPost),
26360                 method: method,
26361                 params:isPost ? this.getParams() : null,
26362                 isUpload: this.form.fileUpload,
26363                 formData : this.form.formData
26364             }));
26365             
26366             this.uploadProgress();
26367
26368         }else if (o.clientValidation !== false){ // client validation failed
26369             this.failureType = Roo.form.Action.CLIENT_INVALID;
26370             this.form.afterAction(this, false);
26371         }
26372     },
26373
26374     success : function(response)
26375     {
26376         this.uploadComplete= true;
26377         if (this.haveProgress) {
26378             Roo.MessageBox.hide();
26379         }
26380         
26381         
26382         var result = this.processResponse(response);
26383         if(result === true || result.success){
26384             this.form.afterAction(this, true);
26385             return;
26386         }
26387         if(result.errors){
26388             this.form.markInvalid(result.errors);
26389             this.failureType = Roo.form.Action.SERVER_INVALID;
26390         }
26391         this.form.afterAction(this, false);
26392     },
26393     failure : function(response)
26394     {
26395         this.uploadComplete= true;
26396         if (this.haveProgress) {
26397             Roo.MessageBox.hide();
26398         }
26399         
26400         this.response = response;
26401         this.failureType = Roo.form.Action.CONNECT_FAILURE;
26402         this.form.afterAction(this, false);
26403     },
26404     
26405     handleResponse : function(response){
26406         if(this.form.errorReader){
26407             var rs = this.form.errorReader.read(response);
26408             var errors = [];
26409             if(rs.records){
26410                 for(var i = 0, len = rs.records.length; i < len; i++) {
26411                     var r = rs.records[i];
26412                     errors[i] = r.data;
26413                 }
26414             }
26415             if(errors.length < 1){
26416                 errors = null;
26417             }
26418             return {
26419                 success : rs.success,
26420                 errors : errors
26421             };
26422         }
26423         var ret = false;
26424         try {
26425             ret = Roo.decode(response.responseText);
26426         } catch (e) {
26427             ret = {
26428                 success: false,
26429                 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
26430                 errors : []
26431             };
26432         }
26433         return ret;
26434         
26435     }
26436 });
26437
26438
26439 Roo.form.Action.Load = function(form, options){
26440     Roo.form.Action.Load.superclass.constructor.call(this, form, options);
26441     this.reader = this.form.reader;
26442 };
26443
26444 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
26445     type : 'load',
26446
26447     run : function(){
26448         
26449         Roo.Ajax.request(Roo.apply(
26450                 this.createCallback(), {
26451                     method:this.getMethod(),
26452                     url:this.getUrl(false),
26453                     params:this.getParams()
26454         }));
26455     },
26456
26457     success : function(response){
26458         
26459         var result = this.processResponse(response);
26460         if(result === true || !result.success || !result.data){
26461             this.failureType = Roo.form.Action.LOAD_FAILURE;
26462             this.form.afterAction(this, false);
26463             return;
26464         }
26465         this.form.clearInvalid();
26466         this.form.setValues(result.data);
26467         this.form.afterAction(this, true);
26468     },
26469
26470     handleResponse : function(response){
26471         if(this.form.reader){
26472             var rs = this.form.reader.read(response);
26473             var data = rs.records && rs.records[0] ? rs.records[0].data : null;
26474             return {
26475                 success : rs.success,
26476                 data : data
26477             };
26478         }
26479         return Roo.decode(response.responseText);
26480     }
26481 });
26482
26483 Roo.form.Action.ACTION_TYPES = {
26484     'load' : Roo.form.Action.Load,
26485     'submit' : Roo.form.Action.Submit
26486 };/*
26487  * Based on:
26488  * Ext JS Library 1.1.1
26489  * Copyright(c) 2006-2007, Ext JS, LLC.
26490  *
26491  * Originally Released Under LGPL - original licence link has changed is not relivant.
26492  *
26493  * Fork - LGPL
26494  * <script type="text/javascript">
26495  */
26496  
26497 /**
26498  * @class Roo.form.Layout
26499  * @extends Roo.Component
26500  * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
26501  * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
26502  * @constructor
26503  * @param {Object} config Configuration options
26504  */
26505 Roo.form.Layout = function(config){
26506     var xitems = [];
26507     if (config.items) {
26508         xitems = config.items;
26509         delete config.items;
26510     }
26511     Roo.form.Layout.superclass.constructor.call(this, config);
26512     this.stack = [];
26513     Roo.each(xitems, this.addxtype, this);
26514      
26515 };
26516
26517 Roo.extend(Roo.form.Layout, Roo.Component, {
26518     /**
26519      * @cfg {String/Object} autoCreate
26520      * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
26521      */
26522     /**
26523      * @cfg {String/Object/Function} style
26524      * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
26525      * a function which returns such a specification.
26526      */
26527     /**
26528      * @cfg {String} labelAlign
26529      * Valid values are "left," "top" and "right" (defaults to "left")
26530      */
26531     /**
26532      * @cfg {Number} labelWidth
26533      * Fixed width in pixels of all field labels (defaults to undefined)
26534      */
26535     /**
26536      * @cfg {Boolean} clear
26537      * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
26538      */
26539     clear : true,
26540     /**
26541      * @cfg {String} labelSeparator
26542      * The separator to use after field labels (defaults to ':')
26543      */
26544     labelSeparator : ':',
26545     /**
26546      * @cfg {Boolean} hideLabels
26547      * True to suppress the display of field labels in this layout (defaults to false)
26548      */
26549     hideLabels : false,
26550
26551     // private
26552     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
26553     
26554     isLayout : true,
26555     
26556     // private
26557     onRender : function(ct, position){
26558         if(this.el){ // from markup
26559             this.el = Roo.get(this.el);
26560         }else {  // generate
26561             var cfg = this.getAutoCreate();
26562             this.el = ct.createChild(cfg, position);
26563         }
26564         if(this.style){
26565             this.el.applyStyles(this.style);
26566         }
26567         if(this.labelAlign){
26568             this.el.addClass('x-form-label-'+this.labelAlign);
26569         }
26570         if(this.hideLabels){
26571             this.labelStyle = "display:none";
26572             this.elementStyle = "padding-left:0;";
26573         }else{
26574             if(typeof this.labelWidth == 'number'){
26575                 this.labelStyle = "width:"+this.labelWidth+"px;";
26576                 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
26577             }
26578             if(this.labelAlign == 'top'){
26579                 this.labelStyle = "width:auto;";
26580                 this.elementStyle = "padding-left:0;";
26581             }
26582         }
26583         var stack = this.stack;
26584         var slen = stack.length;
26585         if(slen > 0){
26586             if(!this.fieldTpl){
26587                 var t = new Roo.Template(
26588                     '<div class="x-form-item {5}">',
26589                         '<label for="{0}" style="{2}">{1}{4}</label>',
26590                         '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
26591                         '</div>',
26592                     '</div><div class="x-form-clear-left"></div>'
26593                 );
26594                 t.disableFormats = true;
26595                 t.compile();
26596                 Roo.form.Layout.prototype.fieldTpl = t;
26597             }
26598             for(var i = 0; i < slen; i++) {
26599                 if(stack[i].isFormField){
26600                     this.renderField(stack[i]);
26601                 }else{
26602                     this.renderComponent(stack[i]);
26603                 }
26604             }
26605         }
26606         if(this.clear){
26607             this.el.createChild({cls:'x-form-clear'});
26608         }
26609     },
26610
26611     // private
26612     renderField : function(f){
26613         f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
26614                f.id, //0
26615                f.fieldLabel, //1
26616                f.labelStyle||this.labelStyle||'', //2
26617                this.elementStyle||'', //3
26618                typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
26619                f.itemCls||this.itemCls||''  //5
26620        ], true).getPrevSibling());
26621     },
26622
26623     // private
26624     renderComponent : function(c){
26625         c.render(c.isLayout ? this.el : this.el.createChild());    
26626     },
26627     /**
26628      * Adds a object form elements (using the xtype property as the factory method.)
26629      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column
26630      * @param {Object} config 
26631      */
26632     addxtype : function(o)
26633     {
26634         // create the lement.
26635         o.form = this.form;
26636         var fe = Roo.factory(o, Roo.form);
26637         this.form.allItems.push(fe);
26638         this.stack.push(fe);
26639         
26640         if (fe.isFormField) {
26641             this.form.items.add(fe);
26642         }
26643          
26644         return fe;
26645     }
26646 });
26647
26648 /**
26649  * @class Roo.form.Column
26650  * @extends Roo.form.Layout
26651  * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
26652  * @constructor
26653  * @param {Object} config Configuration options
26654  */
26655 Roo.form.Column = function(config){
26656     Roo.form.Column.superclass.constructor.call(this, config);
26657 };
26658
26659 Roo.extend(Roo.form.Column, Roo.form.Layout, {
26660     /**
26661      * @cfg {Number/String} width
26662      * The fixed width of the column in pixels or CSS value (defaults to "auto")
26663      */
26664     /**
26665      * @cfg {String/Object} autoCreate
26666      * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
26667      */
26668
26669     // private
26670     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
26671
26672     // private
26673     onRender : function(ct, position){
26674         Roo.form.Column.superclass.onRender.call(this, ct, position);
26675         if(this.width){
26676             this.el.setWidth(this.width);
26677         }
26678     }
26679 });
26680
26681
26682 /**
26683  * @class Roo.form.Row
26684  * @extends Roo.form.Layout
26685  * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
26686  * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
26687  * @constructor
26688  * @param {Object} config Configuration options
26689  */
26690
26691  
26692 Roo.form.Row = function(config){
26693     Roo.form.Row.superclass.constructor.call(this, config);
26694 };
26695  
26696 Roo.extend(Roo.form.Row, Roo.form.Layout, {
26697       /**
26698      * @cfg {Number/String} width
26699      * The fixed width of the column in pixels or CSS value (defaults to "auto")
26700      */
26701     /**
26702      * @cfg {Number/String} height
26703      * The fixed height of the column in pixels or CSS value (defaults to "auto")
26704      */
26705     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
26706     
26707     padWidth : 20,
26708     // private
26709     onRender : function(ct, position){
26710         //console.log('row render');
26711         if(!this.rowTpl){
26712             var t = new Roo.Template(
26713                 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
26714                     '<label for="{0}" style="{2}">{1}{4}</label>',
26715                     '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
26716                     '</div>',
26717                 '</div>'
26718             );
26719             t.disableFormats = true;
26720             t.compile();
26721             Roo.form.Layout.prototype.rowTpl = t;
26722         }
26723         this.fieldTpl = this.rowTpl;
26724         
26725         //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
26726         var labelWidth = 100;
26727         
26728         if ((this.labelAlign != 'top')) {
26729             if (typeof this.labelWidth == 'number') {
26730                 labelWidth = this.labelWidth
26731             }
26732             this.padWidth =  20 + labelWidth;
26733             
26734         }
26735         
26736         Roo.form.Column.superclass.onRender.call(this, ct, position);
26737         if(this.width){
26738             this.el.setWidth(this.width);
26739         }
26740         if(this.height){
26741             this.el.setHeight(this.height);
26742         }
26743     },
26744     
26745     // private
26746     renderField : function(f){
26747         f.fieldEl = this.fieldTpl.append(this.el, [
26748                f.id, f.fieldLabel,
26749                f.labelStyle||this.labelStyle||'',
26750                this.elementStyle||'',
26751                typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
26752                f.itemCls||this.itemCls||'',
26753                f.width ? f.width + this.padWidth : 160 + this.padWidth
26754        ],true);
26755     }
26756 });
26757  
26758
26759 /**
26760  * @class Roo.form.FieldSet
26761  * @extends Roo.form.Layout
26762  * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
26763  * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
26764  * @constructor
26765  * @param {Object} config Configuration options
26766  */
26767 Roo.form.FieldSet = function(config){
26768     Roo.form.FieldSet.superclass.constructor.call(this, config);
26769 };
26770
26771 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
26772     /**
26773      * @cfg {String} legend
26774      * The text to display as the legend for the FieldSet (defaults to '')
26775      */
26776     /**
26777      * @cfg {String/Object} autoCreate
26778      * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
26779      */
26780
26781     // private
26782     defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
26783
26784     // private
26785     onRender : function(ct, position){
26786         Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
26787         if(this.legend){
26788             this.setLegend(this.legend);
26789         }
26790     },
26791
26792     // private
26793     setLegend : function(text){
26794         if(this.rendered){
26795             this.el.child('legend').update(text);
26796         }
26797     }
26798 });/*
26799  * Based on:
26800  * Ext JS Library 1.1.1
26801  * Copyright(c) 2006-2007, Ext JS, LLC.
26802  *
26803  * Originally Released Under LGPL - original licence link has changed is not relivant.
26804  *
26805  * Fork - LGPL
26806  * <script type="text/javascript">
26807  */
26808 /**
26809  * @class Roo.form.VTypes
26810  * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
26811  * @static
26812  */
26813 Roo.form.VTypes = function(){
26814     // closure these in so they are only created once.
26815     var alpha = /^[a-zA-Z_]+$/;
26816     var alphanum = /^[a-zA-Z0-9_]+$/;
26817     var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
26818     var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
26819
26820     // All these messages and functions are configurable
26821     return {
26822         /**
26823          * The function used to validate email addresses
26824          * @param {String} value The email address
26825          */
26826         'email' : function(v){
26827             return email.test(v);
26828         },
26829         /**
26830          * The error text to display when the email validation function returns false
26831          * @type String
26832          */
26833         'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
26834         /**
26835          * The keystroke filter mask to be applied on email input
26836          * @type RegExp
26837          */
26838         'emailMask' : /[a-z0-9_\.\-@]/i,
26839
26840         /**
26841          * The function used to validate URLs
26842          * @param {String} value The URL
26843          */
26844         'url' : function(v){
26845             return url.test(v);
26846         },
26847         /**
26848          * The error text to display when the url validation function returns false
26849          * @type String
26850          */
26851         'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
26852         
26853         /**
26854          * The function used to validate alpha values
26855          * @param {String} value The value
26856          */
26857         'alpha' : function(v){
26858             return alpha.test(v);
26859         },
26860         /**
26861          * The error text to display when the alpha validation function returns false
26862          * @type String
26863          */
26864         'alphaText' : 'This field should only contain letters and _',
26865         /**
26866          * The keystroke filter mask to be applied on alpha input
26867          * @type RegExp
26868          */
26869         'alphaMask' : /[a-z_]/i,
26870
26871         /**
26872          * The function used to validate alphanumeric values
26873          * @param {String} value The value
26874          */
26875         'alphanum' : function(v){
26876             return alphanum.test(v);
26877         },
26878         /**
26879          * The error text to display when the alphanumeric validation function returns false
26880          * @type String
26881          */
26882         'alphanumText' : 'This field should only contain letters, numbers and _',
26883         /**
26884          * The keystroke filter mask to be applied on alphanumeric input
26885          * @type RegExp
26886          */
26887         'alphanumMask' : /[a-z0-9_]/i
26888     };
26889 }();//<script type="text/javascript">
26890
26891 /**
26892  * @class Roo.form.FCKeditor
26893  * @extends Roo.form.TextArea
26894  * Wrapper around the FCKEditor http://www.fckeditor.net
26895  * @constructor
26896  * Creates a new FCKeditor
26897  * @param {Object} config Configuration options
26898  */
26899 Roo.form.FCKeditor = function(config){
26900     Roo.form.FCKeditor.superclass.constructor.call(this, config);
26901     this.addEvents({
26902          /**
26903          * @event editorinit
26904          * Fired when the editor is initialized - you can add extra handlers here..
26905          * @param {FCKeditor} this
26906          * @param {Object} the FCK object.
26907          */
26908         editorinit : true
26909     });
26910     
26911     
26912 };
26913 Roo.form.FCKeditor.editors = { };
26914 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
26915 {
26916     //defaultAutoCreate : {
26917     //    tag : "textarea",style   : "width:100px;height:60px;" ,autocomplete    : "off"
26918     //},
26919     // private
26920     /**
26921      * @cfg {Object} fck options - see fck manual for details.
26922      */
26923     fckconfig : false,
26924     
26925     /**
26926      * @cfg {Object} fck toolbar set (Basic or Default)
26927      */
26928     toolbarSet : 'Basic',
26929     /**
26930      * @cfg {Object} fck BasePath
26931      */ 
26932     basePath : '/fckeditor/',
26933     
26934     
26935     frame : false,
26936     
26937     value : '',
26938     
26939    
26940     onRender : function(ct, position)
26941     {
26942         if(!this.el){
26943             this.defaultAutoCreate = {
26944                 tag: "textarea",
26945                 style:"width:300px;height:60px;",
26946                 autocomplete: "new-password"
26947             };
26948         }
26949         Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
26950         /*
26951         if(this.grow){
26952             this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
26953             if(this.preventScrollbars){
26954                 this.el.setStyle("overflow", "hidden");
26955             }
26956             this.el.setHeight(this.growMin);
26957         }
26958         */
26959         //console.log('onrender' + this.getId() );
26960         Roo.form.FCKeditor.editors[this.getId()] = this;
26961          
26962
26963         this.replaceTextarea() ;
26964         
26965     },
26966     
26967     getEditor : function() {
26968         return this.fckEditor;
26969     },
26970     /**
26971      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
26972      * @param {Mixed} value The value to set
26973      */
26974     
26975     
26976     setValue : function(value)
26977     {
26978         //console.log('setValue: ' + value);
26979         
26980         if(typeof(value) == 'undefined') { // not sure why this is happending...
26981             return;
26982         }
26983         Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
26984         
26985         //if(!this.el || !this.getEditor()) {
26986         //    this.value = value;
26987             //this.setValue.defer(100,this,[value]);    
26988         //    return;
26989         //} 
26990         
26991         if(!this.getEditor()) {
26992             return;
26993         }
26994         
26995         this.getEditor().SetData(value);
26996         
26997         //
26998
26999     },
27000
27001     /**
27002      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
27003      * @return {Mixed} value The field value
27004      */
27005     getValue : function()
27006     {
27007         
27008         if (this.frame && this.frame.dom.style.display == 'none') {
27009             return Roo.form.FCKeditor.superclass.getValue.call(this);
27010         }
27011         
27012         if(!this.el || !this.getEditor()) {
27013            
27014            // this.getValue.defer(100,this); 
27015             return this.value;
27016         }
27017        
27018         
27019         var value=this.getEditor().GetData();
27020         Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
27021         return Roo.form.FCKeditor.superclass.getValue.call(this);
27022         
27023
27024     },
27025
27026     /**
27027      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
27028      * @return {Mixed} value The field value
27029      */
27030     getRawValue : function()
27031     {
27032         if (this.frame && this.frame.dom.style.display == 'none') {
27033             return Roo.form.FCKeditor.superclass.getRawValue.call(this);
27034         }
27035         
27036         if(!this.el || !this.getEditor()) {
27037             //this.getRawValue.defer(100,this); 
27038             return this.value;
27039             return;
27040         }
27041         
27042         
27043         
27044         var value=this.getEditor().GetData();
27045         Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
27046         return Roo.form.FCKeditor.superclass.getRawValue.call(this);
27047          
27048     },
27049     
27050     setSize : function(w,h) {
27051         
27052         
27053         
27054         //if (this.frame && this.frame.dom.style.display == 'none') {
27055         //    Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
27056         //    return;
27057         //}
27058         //if(!this.el || !this.getEditor()) {
27059         //    this.setSize.defer(100,this, [w,h]); 
27060         //    return;
27061         //}
27062         
27063         
27064         
27065         Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
27066         
27067         this.frame.dom.setAttribute('width', w);
27068         this.frame.dom.setAttribute('height', h);
27069         this.frame.setSize(w,h);
27070         
27071     },
27072     
27073     toggleSourceEdit : function(value) {
27074         
27075       
27076          
27077         this.el.dom.style.display = value ? '' : 'none';
27078         this.frame.dom.style.display = value ?  'none' : '';
27079         
27080     },
27081     
27082     
27083     focus: function(tag)
27084     {
27085         if (this.frame.dom.style.display == 'none') {
27086             return Roo.form.FCKeditor.superclass.focus.call(this);
27087         }
27088         if(!this.el || !this.getEditor()) {
27089             this.focus.defer(100,this, [tag]); 
27090             return;
27091         }
27092         
27093         
27094         
27095         
27096         var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
27097         this.getEditor().Focus();
27098         if (tgs.length) {
27099             if (!this.getEditor().Selection.GetSelection()) {
27100                 this.focus.defer(100,this, [tag]); 
27101                 return;
27102             }
27103             
27104             
27105             var r = this.getEditor().EditorDocument.createRange();
27106             r.setStart(tgs[0],0);
27107             r.setEnd(tgs[0],0);
27108             this.getEditor().Selection.GetSelection().removeAllRanges();
27109             this.getEditor().Selection.GetSelection().addRange(r);
27110             this.getEditor().Focus();
27111         }
27112         
27113     },
27114     
27115     
27116     
27117     replaceTextarea : function()
27118     {
27119         if ( document.getElementById( this.getId() + '___Frame' ) ) {
27120             return ;
27121         }
27122         //if ( !this.checkBrowser || this._isCompatibleBrowser() )
27123         //{
27124             // We must check the elements firstly using the Id and then the name.
27125         var oTextarea = document.getElementById( this.getId() );
27126         
27127         var colElementsByName = document.getElementsByName( this.getId() ) ;
27128          
27129         oTextarea.style.display = 'none' ;
27130
27131         if ( oTextarea.tabIndex ) {            
27132             this.TabIndex = oTextarea.tabIndex ;
27133         }
27134         
27135         this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
27136         this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
27137         this.frame = Roo.get(this.getId() + '___Frame')
27138     },
27139     
27140     _getConfigHtml : function()
27141     {
27142         var sConfig = '' ;
27143
27144         for ( var o in this.fckconfig ) {
27145             sConfig += sConfig.length > 0  ? '&amp;' : '';
27146             sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
27147         }
27148
27149         return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
27150     },
27151     
27152     
27153     _getIFrameHtml : function()
27154     {
27155         var sFile = 'fckeditor.html' ;
27156         /* no idea what this is about..
27157         try
27158         {
27159             if ( (/fcksource=true/i).test( window.top.location.search ) )
27160                 sFile = 'fckeditor.original.html' ;
27161         }
27162         catch (e) { 
27163         */
27164
27165         var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
27166         sLink += this.toolbarSet ? ( '&amp;Toolbar=' + this.toolbarSet)  : '';
27167         
27168         
27169         var html = '<iframe id="' + this.getId() +
27170             '___Frame" src="' + sLink +
27171             '" width="' + this.width +
27172             '" height="' + this.height + '"' +
27173             (this.tabIndex ?  ' tabindex="' + this.tabIndex + '"' :'' ) +
27174             ' frameborder="0" scrolling="no"></iframe>' ;
27175
27176         return html ;
27177     },
27178     
27179     _insertHtmlBefore : function( html, element )
27180     {
27181         if ( element.insertAdjacentHTML )       {
27182             // IE
27183             element.insertAdjacentHTML( 'beforeBegin', html ) ;
27184         } else { // Gecko
27185             var oRange = document.createRange() ;
27186             oRange.setStartBefore( element ) ;
27187             var oFragment = oRange.createContextualFragment( html );
27188             element.parentNode.insertBefore( oFragment, element ) ;
27189         }
27190     }
27191     
27192     
27193   
27194     
27195     
27196     
27197     
27198
27199 });
27200
27201 //Roo.reg('fckeditor', Roo.form.FCKeditor);
27202
27203 function FCKeditor_OnComplete(editorInstance){
27204     var f = Roo.form.FCKeditor.editors[editorInstance.Name];
27205     f.fckEditor = editorInstance;
27206     //console.log("loaded");
27207     f.fireEvent('editorinit', f, editorInstance);
27208
27209   
27210
27211  
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227 //<script type="text/javascript">
27228 /**
27229  * @class Roo.form.GridField
27230  * @extends Roo.form.Field
27231  * Embed a grid (or editable grid into a form)
27232  * STATUS ALPHA
27233  * 
27234  * This embeds a grid in a form, the value of the field should be the json encoded array of rows
27235  * it needs 
27236  * xgrid.store = Roo.data.Store
27237  * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
27238  * xgrid.store.reader = Roo.data.JsonReader 
27239  * 
27240  * 
27241  * @constructor
27242  * Creates a new GridField
27243  * @param {Object} config Configuration options
27244  */
27245 Roo.form.GridField = function(config){
27246     Roo.form.GridField.superclass.constructor.call(this, config);
27247      
27248 };
27249
27250 Roo.extend(Roo.form.GridField, Roo.form.Field,  {
27251     /**
27252      * @cfg {Number} width  - used to restrict width of grid..
27253      */
27254     width : 100,
27255     /**
27256      * @cfg {Number} height - used to restrict height of grid..
27257      */
27258     height : 50,
27259      /**
27260      * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
27261          * 
27262          *}
27263      */
27264     xgrid : false, 
27265     /**
27266      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
27267      * {tag: "input", type: "checkbox", autocomplete: "off"})
27268      */
27269    // defaultAutoCreate : { tag: 'div' },
27270     defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'new-password'},
27271     /**
27272      * @cfg {String} addTitle Text to include for adding a title.
27273      */
27274     addTitle : false,
27275     //
27276     onResize : function(){
27277         Roo.form.Field.superclass.onResize.apply(this, arguments);
27278     },
27279
27280     initEvents : function(){
27281         // Roo.form.Checkbox.superclass.initEvents.call(this);
27282         // has no events...
27283        
27284     },
27285
27286
27287     getResizeEl : function(){
27288         return this.wrap;
27289     },
27290
27291     getPositionEl : function(){
27292         return this.wrap;
27293     },
27294
27295     // private
27296     onRender : function(ct, position){
27297         
27298         this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
27299         var style = this.style;
27300         delete this.style;
27301         
27302         Roo.form.GridField.superclass.onRender.call(this, ct, position);
27303         this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
27304         this.viewEl = this.wrap.createChild({ tag: 'div' });
27305         if (style) {
27306             this.viewEl.applyStyles(style);
27307         }
27308         if (this.width) {
27309             this.viewEl.setWidth(this.width);
27310         }
27311         if (this.height) {
27312             this.viewEl.setHeight(this.height);
27313         }
27314         //if(this.inputValue !== undefined){
27315         //this.setValue(this.value);
27316         
27317         
27318         this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
27319         
27320         
27321         this.grid.render();
27322         this.grid.getDataSource().on('remove', this.refreshValue, this);
27323         this.grid.getDataSource().on('update', this.refreshValue, this);
27324         this.grid.on('afteredit', this.refreshValue, this);
27325  
27326     },
27327      
27328     
27329     /**
27330      * Sets the value of the item. 
27331      * @param {String} either an object  or a string..
27332      */
27333     setValue : function(v){
27334         //this.value = v;
27335         v = v || []; // empty set..
27336         // this does not seem smart - it really only affects memoryproxy grids..
27337         if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
27338             var ds = this.grid.getDataSource();
27339             // assumes a json reader..
27340             var data = {}
27341             data[ds.reader.meta.root ] =  typeof(v) == 'string' ? Roo.decode(v) : v;
27342             ds.loadData( data);
27343         }
27344         // clear selection so it does not get stale.
27345         if (this.grid.sm) { 
27346             this.grid.sm.clearSelections();
27347         }
27348         
27349         Roo.form.GridField.superclass.setValue.call(this, v);
27350         this.refreshValue();
27351         // should load data in the grid really....
27352     },
27353     
27354     // private
27355     refreshValue: function() {
27356          var val = [];
27357         this.grid.getDataSource().each(function(r) {
27358             val.push(r.data);
27359         });
27360         this.el.dom.value = Roo.encode(val);
27361     }
27362     
27363      
27364     
27365     
27366 });/*
27367  * Based on:
27368  * Ext JS Library 1.1.1
27369  * Copyright(c) 2006-2007, Ext JS, LLC.
27370  *
27371  * Originally Released Under LGPL - original licence link has changed is not relivant.
27372  *
27373  * Fork - LGPL
27374  * <script type="text/javascript">
27375  */
27376 /**
27377  * @class Roo.form.DisplayField
27378  * @extends Roo.form.Field
27379  * A generic Field to display non-editable data.
27380  * @cfg {Boolean} closable (true|false) default false
27381  * @constructor
27382  * Creates a new Display Field item.
27383  * @param {Object} config Configuration options
27384  */
27385 Roo.form.DisplayField = function(config){
27386     Roo.form.DisplayField.superclass.constructor.call(this, config);
27387     
27388     this.addEvents({
27389         /**
27390          * @event close
27391          * Fires after the click the close btn
27392              * @param {Roo.form.DisplayField} this
27393              */
27394         close : true
27395     });
27396 };
27397
27398 Roo.extend(Roo.form.DisplayField, Roo.form.TextField,  {
27399     inputType:      'hidden',
27400     allowBlank:     true,
27401     readOnly:         true,
27402     
27403  
27404     /**
27405      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
27406      */
27407     focusClass : undefined,
27408     /**
27409      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
27410      */
27411     fieldClass: 'x-form-field',
27412     
27413      /**
27414      * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
27415      */
27416     valueRenderer: undefined,
27417     
27418     width: 100,
27419     /**
27420      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
27421      * {tag: "input", type: "checkbox", autocomplete: "off"})
27422      */
27423      
27424  //   defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
27425  
27426     closable : false,
27427     
27428     onResize : function(){
27429         Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
27430         
27431     },
27432
27433     initEvents : function(){
27434         // Roo.form.Checkbox.superclass.initEvents.call(this);
27435         // has no events...
27436         
27437         if(this.closable){
27438             this.closeEl.on('click', this.onClose, this);
27439         }
27440        
27441     },
27442
27443
27444     getResizeEl : function(){
27445         return this.wrap;
27446     },
27447
27448     getPositionEl : function(){
27449         return this.wrap;
27450     },
27451
27452     // private
27453     onRender : function(ct, position){
27454         
27455         Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
27456         //if(this.inputValue !== undefined){
27457         this.wrap = this.el.wrap();
27458         
27459         this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
27460         
27461         if(this.closable){
27462             this.closeEl = this.wrap.createChild({ tag: 'div', cls: 'x-dlg-close'});
27463         }
27464         
27465         if (this.bodyStyle) {
27466             this.viewEl.applyStyles(this.bodyStyle);
27467         }
27468         //this.viewEl.setStyle('padding', '2px');
27469         
27470         this.setValue(this.value);
27471         
27472     },
27473 /*
27474     // private
27475     initValue : Roo.emptyFn,
27476
27477   */
27478
27479         // private
27480     onClick : function(){
27481         
27482     },
27483
27484     /**
27485      * Sets the checked state of the checkbox.
27486      * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
27487      */
27488     setValue : function(v){
27489         this.value = v;
27490         var html = this.valueRenderer ?  this.valueRenderer(v) : String.format('{0}', v);
27491         // this might be called before we have a dom element..
27492         if (!this.viewEl) {
27493             return;
27494         }
27495         this.viewEl.dom.innerHTML = html;
27496         Roo.form.DisplayField.superclass.setValue.call(this, v);
27497
27498     },
27499     
27500     onClose : function(e)
27501     {
27502         e.preventDefault();
27503         
27504         this.fireEvent('close', this);
27505     }
27506 });/*
27507  * 
27508  * Licence- LGPL
27509  * 
27510  */
27511
27512 /**
27513  * @class Roo.form.DayPicker
27514  * @extends Roo.form.Field
27515  * A Day picker show [M] [T] [W] ....
27516  * @constructor
27517  * Creates a new Day Picker
27518  * @param {Object} config Configuration options
27519  */
27520 Roo.form.DayPicker= function(config){
27521     Roo.form.DayPicker.superclass.constructor.call(this, config);
27522      
27523 };
27524
27525 Roo.extend(Roo.form.DayPicker, Roo.form.Field,  {
27526     /**
27527      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
27528      */
27529     focusClass : undefined,
27530     /**
27531      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
27532      */
27533     fieldClass: "x-form-field",
27534    
27535     /**
27536      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
27537      * {tag: "input", type: "checkbox", autocomplete: "off"})
27538      */
27539     defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "new-password"},
27540     
27541    
27542     actionMode : 'viewEl', 
27543     //
27544     // private
27545  
27546     inputType : 'hidden',
27547     
27548      
27549     inputElement: false, // real input element?
27550     basedOn: false, // ????
27551     
27552     isFormField: true, // not sure where this is needed!!!!
27553
27554     onResize : function(){
27555         Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
27556         if(!this.boxLabel){
27557             this.el.alignTo(this.wrap, 'c-c');
27558         }
27559     },
27560
27561     initEvents : function(){
27562         Roo.form.Checkbox.superclass.initEvents.call(this);
27563         this.el.on("click", this.onClick,  this);
27564         this.el.on("change", this.onClick,  this);
27565     },
27566
27567
27568     getResizeEl : function(){
27569         return this.wrap;
27570     },
27571
27572     getPositionEl : function(){
27573         return this.wrap;
27574     },
27575
27576     
27577     // private
27578     onRender : function(ct, position){
27579         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
27580        
27581         this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
27582         
27583         var r1 = '<table><tr>';
27584         var r2 = '<tr class="x-form-daypick-icons">';
27585         for (var i=0; i < 7; i++) {
27586             r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
27587             r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL  +'"></td>';
27588         }
27589         
27590         var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
27591         viewEl.select('img').on('click', this.onClick, this);
27592         this.viewEl = viewEl;   
27593         
27594         
27595         // this will not work on Chrome!!!
27596         this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
27597         this.el.on('propertychange', this.setFromHidden,  this);  //ie
27598         
27599         
27600           
27601
27602     },
27603
27604     // private
27605     initValue : Roo.emptyFn,
27606
27607     /**
27608      * Returns the checked state of the checkbox.
27609      * @return {Boolean} True if checked, else false
27610      */
27611     getValue : function(){
27612         return this.el.dom.value;
27613         
27614     },
27615
27616         // private
27617     onClick : function(e){ 
27618         //this.setChecked(!this.checked);
27619         Roo.get(e.target).toggleClass('x-menu-item-checked');
27620         this.refreshValue();
27621         //if(this.el.dom.checked != this.checked){
27622         //    this.setValue(this.el.dom.checked);
27623        // }
27624     },
27625     
27626     // private
27627     refreshValue : function()
27628     {
27629         var val = '';
27630         this.viewEl.select('img',true).each(function(e,i,n)  {
27631             val += e.is(".x-menu-item-checked") ? String(n) : '';
27632         });
27633         this.setValue(val, true);
27634     },
27635
27636     /**
27637      * Sets the checked state of the checkbox.
27638      * On is always based on a string comparison between inputValue and the param.
27639      * @param {Boolean/String} value - the value to set 
27640      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
27641      */
27642     setValue : function(v,suppressEvent){
27643         if (!this.el.dom) {
27644             return;
27645         }
27646         var old = this.el.dom.value ;
27647         this.el.dom.value = v;
27648         if (suppressEvent) {
27649             return ;
27650         }
27651          
27652         // update display..
27653         this.viewEl.select('img',true).each(function(e,i,n)  {
27654             
27655             var on = e.is(".x-menu-item-checked");
27656             var newv = v.indexOf(String(n)) > -1;
27657             if (on != newv) {
27658                 e.toggleClass('x-menu-item-checked');
27659             }
27660             
27661         });
27662         
27663         
27664         this.fireEvent('change', this, v, old);
27665         
27666         
27667     },
27668    
27669     // handle setting of hidden value by some other method!!?!?
27670     setFromHidden: function()
27671     {
27672         if(!this.el){
27673             return;
27674         }
27675         //console.log("SET FROM HIDDEN");
27676         //alert('setFrom hidden');
27677         this.setValue(this.el.dom.value);
27678     },
27679     
27680     onDestroy : function()
27681     {
27682         if(this.viewEl){
27683             Roo.get(this.viewEl).remove();
27684         }
27685          
27686         Roo.form.DayPicker.superclass.onDestroy.call(this);
27687     }
27688
27689 });/*
27690  * RooJS Library 1.1.1
27691  * Copyright(c) 2008-2011  Alan Knowles
27692  *
27693  * License - LGPL
27694  */
27695  
27696
27697 /**
27698  * @class Roo.form.ComboCheck
27699  * @extends Roo.form.ComboBox
27700  * A combobox for multiple select items.
27701  *
27702  * FIXME - could do with a reset button..
27703  * 
27704  * @constructor
27705  * Create a new ComboCheck
27706  * @param {Object} config Configuration options
27707  */
27708 Roo.form.ComboCheck = function(config){
27709     Roo.form.ComboCheck.superclass.constructor.call(this, config);
27710     // should verify some data...
27711     // like
27712     // hiddenName = required..
27713     // displayField = required
27714     // valudField == required
27715     var req= [ 'hiddenName', 'displayField', 'valueField' ];
27716     var _t = this;
27717     Roo.each(req, function(e) {
27718         if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
27719             throw "Roo.form.ComboCheck : missing value for: " + e;
27720         }
27721     });
27722     
27723     
27724 };
27725
27726 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
27727      
27728      
27729     editable : false,
27730      
27731     selectedClass: 'x-menu-item-checked', 
27732     
27733     // private
27734     onRender : function(ct, position){
27735         var _t = this;
27736         
27737         
27738         
27739         if(!this.tpl){
27740             var cls = 'x-combo-list';
27741
27742             
27743             this.tpl =  new Roo.Template({
27744                 html :  '<div class="'+cls+'-item x-menu-check-item">' +
27745                    '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' + 
27746                    '<span>{' + this.displayField + '}</span>' +
27747                     '</div>' 
27748                 
27749             });
27750         }
27751  
27752         
27753         Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
27754         this.view.singleSelect = false;
27755         this.view.multiSelect = true;
27756         this.view.toggleSelect = true;
27757         this.pageTb.add(new Roo.Toolbar.Fill(), {
27758             
27759             text: 'Done',
27760             handler: function()
27761             {
27762                 _t.collapse();
27763             }
27764         });
27765     },
27766     
27767     onViewOver : function(e, t){
27768         // do nothing...
27769         return;
27770         
27771     },
27772     
27773     onViewClick : function(doFocus,index){
27774         return;
27775         
27776     },
27777     select: function () {
27778         //Roo.log("SELECT CALLED");
27779     },
27780      
27781     selectByValue : function(xv, scrollIntoView){
27782         var ar = this.getValueArray();
27783         var sels = [];
27784         
27785         Roo.each(ar, function(v) {
27786             if(v === undefined || v === null){
27787                 return;
27788             }
27789             var r = this.findRecord(this.valueField, v);
27790             if(r){
27791                 sels.push(this.store.indexOf(r))
27792                 
27793             }
27794         },this);
27795         this.view.select(sels);
27796         return false;
27797     },
27798     
27799     
27800     
27801     onSelect : function(record, index){
27802        // Roo.log("onselect Called");
27803        // this is only called by the clear button now..
27804         this.view.clearSelections();
27805         this.setValue('[]');
27806         if (this.value != this.valueBefore) {
27807             this.fireEvent('change', this, this.value, this.valueBefore);
27808             this.valueBefore = this.value;
27809         }
27810     },
27811     getValueArray : function()
27812     {
27813         var ar = [] ;
27814         
27815         try {
27816             //Roo.log(this.value);
27817             if (typeof(this.value) == 'undefined') {
27818                 return [];
27819             }
27820             var ar = Roo.decode(this.value);
27821             return  ar instanceof Array ? ar : []; //?? valid?
27822             
27823         } catch(e) {
27824             Roo.log(e + "\nRoo.form.ComboCheck:getValueArray  invalid data:" + this.getValue());
27825             return [];
27826         }
27827          
27828     },
27829     expand : function ()
27830     {
27831         
27832         Roo.form.ComboCheck.superclass.expand.call(this);
27833         this.valueBefore = typeof(this.value) == 'undefined' ? '' : this.value;
27834         //this.valueBefore = typeof(this.valueBefore) == 'undefined' ? '' : this.valueBefore;
27835         
27836
27837     },
27838     
27839     collapse : function(){
27840         Roo.form.ComboCheck.superclass.collapse.call(this);
27841         var sl = this.view.getSelectedIndexes();
27842         var st = this.store;
27843         var nv = [];
27844         var tv = [];
27845         var r;
27846         Roo.each(sl, function(i) {
27847             r = st.getAt(i);
27848             nv.push(r.get(this.valueField));
27849         },this);
27850         this.setValue(Roo.encode(nv));
27851         if (this.value != this.valueBefore) {
27852
27853             this.fireEvent('change', this, this.value, this.valueBefore);
27854             this.valueBefore = this.value;
27855         }
27856         
27857     },
27858     
27859     setValue : function(v){
27860         // Roo.log(v);
27861         this.value = v;
27862         
27863         var vals = this.getValueArray();
27864         var tv = [];
27865         Roo.each(vals, function(k) {
27866             var r = this.findRecord(this.valueField, k);
27867             if(r){
27868                 tv.push(r.data[this.displayField]);
27869             }else if(this.valueNotFoundText !== undefined){
27870                 tv.push( this.valueNotFoundText );
27871             }
27872         },this);
27873        // Roo.log(tv);
27874         
27875         Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
27876         this.hiddenField.value = v;
27877         this.value = v;
27878     }
27879     
27880 });/*
27881  * Based on:
27882  * Ext JS Library 1.1.1
27883  * Copyright(c) 2006-2007, Ext JS, LLC.
27884  *
27885  * Originally Released Under LGPL - original licence link has changed is not relivant.
27886  *
27887  * Fork - LGPL
27888  * <script type="text/javascript">
27889  */
27890  
27891 /**
27892  * @class Roo.form.Signature
27893  * @extends Roo.form.Field
27894  * Signature field.  
27895  * @constructor
27896  * 
27897  * @param {Object} config Configuration options
27898  */
27899
27900 Roo.form.Signature = function(config){
27901     Roo.form.Signature.superclass.constructor.call(this, config);
27902     
27903     this.addEvents({// not in used??
27904          /**
27905          * @event confirm
27906          * Fires when the 'confirm' icon is pressed (add a listener to enable add button)
27907              * @param {Roo.form.Signature} combo This combo box
27908              */
27909         'confirm' : true,
27910         /**
27911          * @event reset
27912          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
27913              * @param {Roo.form.ComboBox} combo This combo box
27914              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
27915              */
27916         'reset' : true
27917     });
27918 };
27919
27920 Roo.extend(Roo.form.Signature, Roo.form.Field,  {
27921     /**
27922      * @cfg {Object} labels Label to use when rendering a form.
27923      * defaults to 
27924      * labels : { 
27925      *      clear : "Clear",
27926      *      confirm : "Confirm"
27927      *  }
27928      */
27929     labels : { 
27930         clear : "Clear",
27931         confirm : "Confirm"
27932     },
27933     /**
27934      * @cfg {Number} width The signature panel width (defaults to 300)
27935      */
27936     width: 300,
27937     /**
27938      * @cfg {Number} height The signature panel height (defaults to 100)
27939      */
27940     height : 100,
27941     /**
27942      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to false)
27943      */
27944     allowBlank : false,
27945     
27946     //private
27947     // {Object} signPanel The signature SVG panel element (defaults to {})
27948     signPanel : {},
27949     // {Boolean} isMouseDown False to validate that the mouse down event (defaults to false)
27950     isMouseDown : false,
27951     // {Boolean} isConfirmed validate the signature is confirmed or not for submitting form (defaults to false)
27952     isConfirmed : false,
27953     // {String} signatureTmp SVG mapping string (defaults to empty string)
27954     signatureTmp : '',
27955     
27956     
27957     defaultAutoCreate : { // modified by initCompnoent..
27958         tag: "input",
27959         type:"hidden"
27960     },
27961
27962     // private
27963     onRender : function(ct, position){
27964         
27965         Roo.form.Signature.superclass.onRender.call(this, ct, position);
27966         
27967         this.wrap = this.el.wrap({
27968             cls:'x-form-signature-wrap', style : 'width: ' + this.width + 'px', cn:{cls:'x-form-signature'}
27969         });
27970         
27971         this.createToolbar(this);
27972         this.signPanel = this.wrap.createChild({
27973                 tag: 'div',
27974                 style: 'width: ' + this.width + 'px; height: ' + this.height + 'px; border: 0;'
27975             }, this.el
27976         );
27977             
27978         this.svgID = Roo.id();
27979         this.svgEl = this.signPanel.createChild({
27980               xmlns : 'http://www.w3.org/2000/svg',
27981               tag : 'svg',
27982               id : this.svgID + "-svg",
27983               width: this.width,
27984               height: this.height,
27985               viewBox: '0 0 '+this.width+' '+this.height,
27986               cn : [
27987                 {
27988                     tag: "rect",
27989                     id: this.svgID + "-svg-r",
27990                     width: this.width,
27991                     height: this.height,
27992                     fill: "#ffa"
27993                 },
27994                 {
27995                     tag: "line",
27996                     id: this.svgID + "-svg-l",
27997                     x1: "0", // start
27998                     y1: (this.height*0.8), // start set the line in 80% of height
27999                     x2: this.width, // end
28000                     y2: (this.height*0.8), // end set the line in 80% of height
28001                     'stroke': "#666",
28002                     'stroke-width': "1",
28003                     'stroke-dasharray': "3",
28004                     'shape-rendering': "crispEdges",
28005                     'pointer-events': "none"
28006                 },
28007                 {
28008                     tag: "path",
28009                     id: this.svgID + "-svg-p",
28010                     'stroke': "navy",
28011                     'stroke-width': "3",
28012                     'fill': "none",
28013                     'pointer-events': 'none'
28014                 }
28015               ]
28016         });
28017         this.createSVG();
28018         this.svgBox = this.svgEl.dom.getScreenCTM();
28019     },
28020     createSVG : function(){ 
28021         var svg = this.signPanel;
28022         var r = svg.select('#'+ this.svgID + '-svg-r', true).first().dom;
28023         var t = this;
28024
28025         r.addEventListener('mousedown', function(e) { return t.down(e); }, false);
28026         r.addEventListener('mousemove', function(e) { return t.move(e); }, false);
28027         r.addEventListener('mouseup', function(e) { return t.up(e); }, false);
28028         r.addEventListener('mouseout', function(e) { return t.up(e); }, false);
28029         r.addEventListener('touchstart', function(e) { return t.down(e); }, false);
28030         r.addEventListener('touchmove', function(e) { return t.move(e); }, false);
28031         r.addEventListener('touchend', function(e) { return t.up(e); }, false);
28032         
28033     },
28034     isTouchEvent : function(e){
28035         return e.type.match(/^touch/);
28036     },
28037     getCoords : function (e) {
28038         var pt    = this.svgEl.dom.createSVGPoint();
28039         pt.x = e.clientX; 
28040         pt.y = e.clientY;
28041         if (this.isTouchEvent(e)) {
28042             pt.x =  e.targetTouches[0].clientX;
28043             pt.y = e.targetTouches[0].clientY;
28044         }
28045         var a = this.svgEl.dom.getScreenCTM();
28046         var b = a.inverse();
28047         var mx = pt.matrixTransform(b);
28048         return mx.x + ',' + mx.y;
28049     },
28050     //mouse event headler 
28051     down : function (e) {
28052         this.signatureTmp += 'M' + this.getCoords(e) + ' ';
28053         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr('d', this.signatureTmp);
28054         
28055         this.isMouseDown = true;
28056         
28057         e.preventDefault();
28058     },
28059     move : function (e) {
28060         if (this.isMouseDown) {
28061             this.signatureTmp += 'L' + this.getCoords(e) + ' ';
28062             this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', this.signatureTmp);
28063         }
28064         
28065         e.preventDefault();
28066     },
28067     up : function (e) {
28068         this.isMouseDown = false;
28069         var sp = this.signatureTmp.split(' ');
28070         
28071         if(sp.length > 1){
28072             if(!sp[sp.length-2].match(/^L/)){
28073                 sp.pop();
28074                 sp.pop();
28075                 sp.push("");
28076                 this.signatureTmp = sp.join(" ");
28077             }
28078         }
28079         if(this.getValue() != this.signatureTmp){
28080             this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
28081             this.isConfirmed = false;
28082         }
28083         e.preventDefault();
28084     },
28085     
28086     /**
28087      * Protected method that will not generally be called directly. It
28088      * is called when the editor creates its toolbar. Override this method if you need to
28089      * add custom toolbar buttons.
28090      * @param {HtmlEditor} editor
28091      */
28092     createToolbar : function(editor){
28093          function btn(id, toggle, handler){
28094             var xid = fid + '-'+ id ;
28095             return {
28096                 id : xid,
28097                 cmd : id,
28098                 cls : 'x-btn-icon x-edit-'+id,
28099                 enableToggle:toggle !== false,
28100                 scope: editor, // was editor...
28101                 handler:handler||editor.relayBtnCmd,
28102                 clickEvent:'mousedown',
28103                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
28104                 tabIndex:-1
28105             };
28106         }
28107         
28108         
28109         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
28110         this.tb = tb;
28111         this.tb.add(
28112            {
28113                 cls : ' x-signature-btn x-signature-'+id,
28114                 scope: editor, // was editor...
28115                 handler: this.reset,
28116                 clickEvent:'mousedown',
28117                 text: this.labels.clear
28118             },
28119             {
28120                  xtype : 'Fill',
28121                  xns: Roo.Toolbar
28122             }, 
28123             {
28124                 cls : '  x-signature-btn x-signature-'+id,
28125                 scope: editor, // was editor...
28126                 handler: this.confirmHandler,
28127                 clickEvent:'mousedown',
28128                 text: this.labels.confirm
28129             }
28130         );
28131     
28132     },
28133     //public
28134     /**
28135      * when user is clicked confirm then show this image.....
28136      * 
28137      * @return {String} Image Data URI
28138      */
28139     getImageDataURI : function(){
28140         var svg = this.svgEl.dom.parentNode.innerHTML;
28141         var src = 'data:image/svg+xml;base64,'+window.btoa(svg);
28142         return src; 
28143     },
28144     /**
28145      * 
28146      * @return {Boolean} this.isConfirmed
28147      */
28148     getConfirmed : function(){
28149         return this.isConfirmed;
28150     },
28151     /**
28152      * 
28153      * @return {Number} this.width
28154      */
28155     getWidth : function(){
28156         return this.width;
28157     },
28158     /**
28159      * 
28160      * @return {Number} this.height
28161      */
28162     getHeight : function(){
28163         return this.height;
28164     },
28165     // private
28166     getSignature : function(){
28167         return this.signatureTmp;
28168     },
28169     // private
28170     reset : function(){
28171         this.signatureTmp = '';
28172         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
28173         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', '');
28174         this.isConfirmed = false;
28175         Roo.form.Signature.superclass.reset.call(this);
28176     },
28177     setSignature : function(s){
28178         this.signatureTmp = s;
28179         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
28180         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', s);
28181         this.setValue(s);
28182         this.isConfirmed = false;
28183         Roo.form.Signature.superclass.reset.call(this);
28184     }, 
28185     test : function(){
28186 //        Roo.log(this.signPanel.dom.contentWindow.up())
28187     },
28188     //private
28189     setConfirmed : function(){
28190         
28191         
28192         
28193 //        Roo.log(Roo.get(this.signPanel.dom.contentWindow.r).attr('fill', '#cfc'));
28194     },
28195     // private
28196     confirmHandler : function(){
28197         if(!this.getSignature()){
28198             return;
28199         }
28200         
28201         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#cfc');
28202         this.setValue(this.getSignature());
28203         this.isConfirmed = true;
28204         
28205         this.fireEvent('confirm', this);
28206     },
28207     // private
28208     // Subclasses should provide the validation implementation by overriding this
28209     validateValue : function(value){
28210         if(this.allowBlank){
28211             return true;
28212         }
28213         
28214         if(this.isConfirmed){
28215             return true;
28216         }
28217         return false;
28218     }
28219 });/*
28220  * Based on:
28221  * Ext JS Library 1.1.1
28222  * Copyright(c) 2006-2007, Ext JS, LLC.
28223  *
28224  * Originally Released Under LGPL - original licence link has changed is not relivant.
28225  *
28226  * Fork - LGPL
28227  * <script type="text/javascript">
28228  */
28229  
28230
28231 /**
28232  * @class Roo.form.ComboBox
28233  * @extends Roo.form.TriggerField
28234  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
28235  * @constructor
28236  * Create a new ComboBox.
28237  * @param {Object} config Configuration options
28238  */
28239 Roo.form.Select = function(config){
28240     Roo.form.Select.superclass.constructor.call(this, config);
28241      
28242 };
28243
28244 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
28245     /**
28246      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
28247      */
28248     /**
28249      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
28250      * rendering into an Roo.Editor, defaults to false)
28251      */
28252     /**
28253      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
28254      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
28255      */
28256     /**
28257      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
28258      */
28259     /**
28260      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
28261      * the dropdown list (defaults to undefined, with no header element)
28262      */
28263
28264      /**
28265      * @cfg {String/Roo.Template} tpl The template to use to render the output
28266      */
28267      
28268     // private
28269     defaultAutoCreate : {tag: "select"  },
28270     /**
28271      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
28272      */
28273     listWidth: undefined,
28274     /**
28275      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
28276      * mode = 'remote' or 'text' if mode = 'local')
28277      */
28278     displayField: undefined,
28279     /**
28280      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
28281      * mode = 'remote' or 'value' if mode = 'local'). 
28282      * Note: use of a valueField requires the user make a selection
28283      * in order for a value to be mapped.
28284      */
28285     valueField: undefined,
28286     
28287     
28288     /**
28289      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
28290      * field's data value (defaults to the underlying DOM element's name)
28291      */
28292     hiddenName: undefined,
28293     /**
28294      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
28295      */
28296     listClass: '',
28297     /**
28298      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
28299      */
28300     selectedClass: 'x-combo-selected',
28301     /**
28302      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
28303      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
28304      * which displays a downward arrow icon).
28305      */
28306     triggerClass : 'x-form-arrow-trigger',
28307     /**
28308      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
28309      */
28310     shadow:'sides',
28311     /**
28312      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
28313      * anchor positions (defaults to 'tl-bl')
28314      */
28315     listAlign: 'tl-bl?',
28316     /**
28317      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
28318      */
28319     maxHeight: 300,
28320     /**
28321      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
28322      * query specified by the allQuery config option (defaults to 'query')
28323      */
28324     triggerAction: 'query',
28325     /**
28326      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
28327      * (defaults to 4, does not apply if editable = false)
28328      */
28329     minChars : 4,
28330     /**
28331      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
28332      * delay (typeAheadDelay) if it matches a known value (defaults to false)
28333      */
28334     typeAhead: false,
28335     /**
28336      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
28337      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
28338      */
28339     queryDelay: 500,
28340     /**
28341      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
28342      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
28343      */
28344     pageSize: 0,
28345     /**
28346      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
28347      * when editable = true (defaults to false)
28348      */
28349     selectOnFocus:false,
28350     /**
28351      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
28352      */
28353     queryParam: 'query',
28354     /**
28355      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
28356      * when mode = 'remote' (defaults to 'Loading...')
28357      */
28358     loadingText: 'Loading...',
28359     /**
28360      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
28361      */
28362     resizable: false,
28363     /**
28364      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
28365      */
28366     handleHeight : 8,
28367     /**
28368      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
28369      * traditional select (defaults to true)
28370      */
28371     editable: true,
28372     /**
28373      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
28374      */
28375     allQuery: '',
28376     /**
28377      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
28378      */
28379     mode: 'remote',
28380     /**
28381      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
28382      * listWidth has a higher value)
28383      */
28384     minListWidth : 70,
28385     /**
28386      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
28387      * allow the user to set arbitrary text into the field (defaults to false)
28388      */
28389     forceSelection:false,
28390     /**
28391      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
28392      * if typeAhead = true (defaults to 250)
28393      */
28394     typeAheadDelay : 250,
28395     /**
28396      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
28397      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
28398      */
28399     valueNotFoundText : undefined,
28400     
28401     /**
28402      * @cfg {String} defaultValue The value displayed after loading the store.
28403      */
28404     defaultValue: '',
28405     
28406     /**
28407      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
28408      */
28409     blockFocus : false,
28410     
28411     /**
28412      * @cfg {Boolean} disableClear Disable showing of clear button.
28413      */
28414     disableClear : false,
28415     /**
28416      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
28417      */
28418     alwaysQuery : false,
28419     
28420     //private
28421     addicon : false,
28422     editicon: false,
28423     
28424     // element that contains real text value.. (when hidden is used..)
28425      
28426     // private
28427     onRender : function(ct, position){
28428         Roo.form.Field.prototype.onRender.call(this, ct, position);
28429         
28430         if(this.store){
28431             this.store.on('beforeload', this.onBeforeLoad, this);
28432             this.store.on('load', this.onLoad, this);
28433             this.store.on('loadexception', this.onLoadException, this);
28434             this.store.load({});
28435         }
28436         
28437         
28438         
28439     },
28440
28441     // private
28442     initEvents : function(){
28443         //Roo.form.ComboBox.superclass.initEvents.call(this);
28444  
28445     },
28446
28447     onDestroy : function(){
28448        
28449         if(this.store){
28450             this.store.un('beforeload', this.onBeforeLoad, this);
28451             this.store.un('load', this.onLoad, this);
28452             this.store.un('loadexception', this.onLoadException, this);
28453         }
28454         //Roo.form.ComboBox.superclass.onDestroy.call(this);
28455     },
28456
28457     // private
28458     fireKey : function(e){
28459         if(e.isNavKeyPress() && !this.list.isVisible()){
28460             this.fireEvent("specialkey", this, e);
28461         }
28462     },
28463
28464     // private
28465     onResize: function(w, h){
28466         
28467         return; 
28468     
28469         
28470     },
28471
28472     /**
28473      * Allow or prevent the user from directly editing the field text.  If false is passed,
28474      * the user will only be able to select from the items defined in the dropdown list.  This method
28475      * is the runtime equivalent of setting the 'editable' config option at config time.
28476      * @param {Boolean} value True to allow the user to directly edit the field text
28477      */
28478     setEditable : function(value){
28479          
28480     },
28481
28482     // private
28483     onBeforeLoad : function(){
28484         
28485         Roo.log("Select before load");
28486         return;
28487     
28488         this.innerList.update(this.loadingText ?
28489                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
28490         //this.restrictHeight();
28491         this.selectedIndex = -1;
28492     },
28493
28494     // private
28495     onLoad : function(){
28496
28497     
28498         var dom = this.el.dom;
28499         dom.innerHTML = '';
28500          var od = dom.ownerDocument;
28501          
28502         if (this.emptyText) {
28503             var op = od.createElement('option');
28504             op.setAttribute('value', '');
28505             op.innerHTML = String.format('{0}', this.emptyText);
28506             dom.appendChild(op);
28507         }
28508         if(this.store.getCount() > 0){
28509            
28510             var vf = this.valueField;
28511             var df = this.displayField;
28512             this.store.data.each(function(r) {
28513                 // which colmsn to use... testing - cdoe / title..
28514                 var op = od.createElement('option');
28515                 op.setAttribute('value', r.data[vf]);
28516                 op.innerHTML = String.format('{0}', r.data[df]);
28517                 dom.appendChild(op);
28518             });
28519             if (typeof(this.defaultValue != 'undefined')) {
28520                 this.setValue(this.defaultValue);
28521             }
28522             
28523              
28524         }else{
28525             //this.onEmptyResults();
28526         }
28527         //this.el.focus();
28528     },
28529     // private
28530     onLoadException : function()
28531     {
28532         dom.innerHTML = '';
28533             
28534         Roo.log("Select on load exception");
28535         return;
28536     
28537         this.collapse();
28538         Roo.log(this.store.reader.jsonData);
28539         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
28540             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
28541         }
28542         
28543         
28544     },
28545     // private
28546     onTypeAhead : function(){
28547          
28548     },
28549
28550     // private
28551     onSelect : function(record, index){
28552         Roo.log('on select?');
28553         return;
28554         if(this.fireEvent('beforeselect', this, record, index) !== false){
28555             this.setFromData(index > -1 ? record.data : false);
28556             this.collapse();
28557             this.fireEvent('select', this, record, index);
28558         }
28559     },
28560
28561     /**
28562      * Returns the currently selected field value or empty string if no value is set.
28563      * @return {String} value The selected value
28564      */
28565     getValue : function(){
28566         var dom = this.el.dom;
28567         this.value = dom.options[dom.selectedIndex].value;
28568         return this.value;
28569         
28570     },
28571
28572     /**
28573      * Clears any text/value currently set in the field
28574      */
28575     clearValue : function(){
28576         this.value = '';
28577         this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
28578         
28579     },
28580
28581     /**
28582      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
28583      * will be displayed in the field.  If the value does not match the data value of an existing item,
28584      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
28585      * Otherwise the field will be blank (although the value will still be set).
28586      * @param {String} value The value to match
28587      */
28588     setValue : function(v){
28589         var d = this.el.dom;
28590         for (var i =0; i < d.options.length;i++) {
28591             if (v == d.options[i].value) {
28592                 d.selectedIndex = i;
28593                 this.value = v;
28594                 return;
28595             }
28596         }
28597         this.clearValue();
28598     },
28599     /**
28600      * @property {Object} the last set data for the element
28601      */
28602     
28603     lastData : false,
28604     /**
28605      * Sets the value of the field based on a object which is related to the record format for the store.
28606      * @param {Object} value the value to set as. or false on reset?
28607      */
28608     setFromData : function(o){
28609         Roo.log('setfrom data?');
28610          
28611         
28612         
28613     },
28614     // private
28615     reset : function(){
28616         this.clearValue();
28617     },
28618     // private
28619     findRecord : function(prop, value){
28620         
28621         return false;
28622     
28623         var record;
28624         if(this.store.getCount() > 0){
28625             this.store.each(function(r){
28626                 if(r.data[prop] == value){
28627                     record = r;
28628                     return false;
28629                 }
28630                 return true;
28631             });
28632         }
28633         return record;
28634     },
28635     
28636     getName: function()
28637     {
28638         // returns hidden if it's set..
28639         if (!this.rendered) {return ''};
28640         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
28641         
28642     },
28643      
28644
28645     
28646
28647     // private
28648     onEmptyResults : function(){
28649         Roo.log('empty results');
28650         //this.collapse();
28651     },
28652
28653     /**
28654      * Returns true if the dropdown list is expanded, else false.
28655      */
28656     isExpanded : function(){
28657         return false;
28658     },
28659
28660     /**
28661      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
28662      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
28663      * @param {String} value The data value of the item to select
28664      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
28665      * selected item if it is not currently in view (defaults to true)
28666      * @return {Boolean} True if the value matched an item in the list, else false
28667      */
28668     selectByValue : function(v, scrollIntoView){
28669         Roo.log('select By Value');
28670         return false;
28671     
28672         if(v !== undefined && v !== null){
28673             var r = this.findRecord(this.valueField || this.displayField, v);
28674             if(r){
28675                 this.select(this.store.indexOf(r), scrollIntoView);
28676                 return true;
28677             }
28678         }
28679         return false;
28680     },
28681
28682     /**
28683      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
28684      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
28685      * @param {Number} index The zero-based index of the list item to select
28686      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
28687      * selected item if it is not currently in view (defaults to true)
28688      */
28689     select : function(index, scrollIntoView){
28690         Roo.log('select ');
28691         return  ;
28692         
28693         this.selectedIndex = index;
28694         this.view.select(index);
28695         if(scrollIntoView !== false){
28696             var el = this.view.getNode(index);
28697             if(el){
28698                 this.innerList.scrollChildIntoView(el, false);
28699             }
28700         }
28701     },
28702
28703       
28704
28705     // private
28706     validateBlur : function(){
28707         
28708         return;
28709         
28710     },
28711
28712     // private
28713     initQuery : function(){
28714         this.doQuery(this.getRawValue());
28715     },
28716
28717     // private
28718     doForce : function(){
28719         if(this.el.dom.value.length > 0){
28720             this.el.dom.value =
28721                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
28722              
28723         }
28724     },
28725
28726     /**
28727      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
28728      * query allowing the query action to be canceled if needed.
28729      * @param {String} query The SQL query to execute
28730      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
28731      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
28732      * saved in the current store (defaults to false)
28733      */
28734     doQuery : function(q, forceAll){
28735         
28736         Roo.log('doQuery?');
28737         if(q === undefined || q === null){
28738             q = '';
28739         }
28740         var qe = {
28741             query: q,
28742             forceAll: forceAll,
28743             combo: this,
28744             cancel:false
28745         };
28746         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
28747             return false;
28748         }
28749         q = qe.query;
28750         forceAll = qe.forceAll;
28751         if(forceAll === true || (q.length >= this.minChars)){
28752             if(this.lastQuery != q || this.alwaysQuery){
28753                 this.lastQuery = q;
28754                 if(this.mode == 'local'){
28755                     this.selectedIndex = -1;
28756                     if(forceAll){
28757                         this.store.clearFilter();
28758                     }else{
28759                         this.store.filter(this.displayField, q);
28760                     }
28761                     this.onLoad();
28762                 }else{
28763                     this.store.baseParams[this.queryParam] = q;
28764                     this.store.load({
28765                         params: this.getParams(q)
28766                     });
28767                     this.expand();
28768                 }
28769             }else{
28770                 this.selectedIndex = -1;
28771                 this.onLoad();   
28772             }
28773         }
28774     },
28775
28776     // private
28777     getParams : function(q){
28778         var p = {};
28779         //p[this.queryParam] = q;
28780         if(this.pageSize){
28781             p.start = 0;
28782             p.limit = this.pageSize;
28783         }
28784         return p;
28785     },
28786
28787     /**
28788      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
28789      */
28790     collapse : function(){
28791         
28792     },
28793
28794     // private
28795     collapseIf : function(e){
28796         
28797     },
28798
28799     /**
28800      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
28801      */
28802     expand : function(){
28803         
28804     } ,
28805
28806     // private
28807      
28808
28809     /** 
28810     * @cfg {Boolean} grow 
28811     * @hide 
28812     */
28813     /** 
28814     * @cfg {Number} growMin 
28815     * @hide 
28816     */
28817     /** 
28818     * @cfg {Number} growMax 
28819     * @hide 
28820     */
28821     /**
28822      * @hide
28823      * @method autoSize
28824      */
28825     
28826     setWidth : function()
28827     {
28828         
28829     },
28830     getResizeEl : function(){
28831         return this.el;
28832     }
28833 });//<script type="text/javasscript">
28834  
28835
28836 /**
28837  * @class Roo.DDView
28838  * A DnD enabled version of Roo.View.
28839  * @param {Element/String} container The Element in which to create the View.
28840  * @param {String} tpl The template string used to create the markup for each element of the View
28841  * @param {Object} config The configuration properties. These include all the config options of
28842  * {@link Roo.View} plus some specific to this class.<br>
28843  * <p>
28844  * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
28845  * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
28846  * <p>
28847  * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
28848 .x-view-drag-insert-above {
28849         border-top:1px dotted #3366cc;
28850 }
28851 .x-view-drag-insert-below {
28852         border-bottom:1px dotted #3366cc;
28853 }
28854 </code></pre>
28855  * 
28856  */
28857  
28858 Roo.DDView = function(container, tpl, config) {
28859     Roo.DDView.superclass.constructor.apply(this, arguments);
28860     this.getEl().setStyle("outline", "0px none");
28861     this.getEl().unselectable();
28862     if (this.dragGroup) {
28863         this.setDraggable(this.dragGroup.split(","));
28864     }
28865     if (this.dropGroup) {
28866         this.setDroppable(this.dropGroup.split(","));
28867     }
28868     if (this.deletable) {
28869         this.setDeletable();
28870     }
28871     this.isDirtyFlag = false;
28872         this.addEvents({
28873                 "drop" : true
28874         });
28875 };
28876
28877 Roo.extend(Roo.DDView, Roo.View, {
28878 /**     @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
28879 /**     @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
28880 /**     @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
28881 /**     @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
28882
28883         isFormField: true,
28884
28885         reset: Roo.emptyFn,
28886         
28887         clearInvalid: Roo.form.Field.prototype.clearInvalid,
28888
28889         validate: function() {
28890                 return true;
28891         },
28892         
28893         destroy: function() {
28894                 this.purgeListeners();
28895                 this.getEl.removeAllListeners();
28896                 this.getEl().remove();
28897                 if (this.dragZone) {
28898                         if (this.dragZone.destroy) {
28899                                 this.dragZone.destroy();
28900                         }
28901                 }
28902                 if (this.dropZone) {
28903                         if (this.dropZone.destroy) {
28904                                 this.dropZone.destroy();
28905                         }
28906                 }
28907         },
28908
28909 /**     Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
28910         getName: function() {
28911                 return this.name;
28912         },
28913
28914 /**     Loads the View from a JSON string representing the Records to put into the Store. */
28915         setValue: function(v) {
28916                 if (!this.store) {
28917                         throw "DDView.setValue(). DDView must be constructed with a valid Store";
28918                 }
28919                 var data = {};
28920                 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
28921                 this.store.proxy = new Roo.data.MemoryProxy(data);
28922                 this.store.load();
28923         },
28924
28925 /**     @return {String} a parenthesised list of the ids of the Records in the View. */
28926         getValue: function() {
28927                 var result = '(';
28928                 this.store.each(function(rec) {
28929                         result += rec.id + ',';
28930                 });
28931                 return result.substr(0, result.length - 1) + ')';
28932         },
28933         
28934         getIds: function() {
28935                 var i = 0, result = new Array(this.store.getCount());
28936                 this.store.each(function(rec) {
28937                         result[i++] = rec.id;
28938                 });
28939                 return result;
28940         },
28941         
28942         isDirty: function() {
28943                 return this.isDirtyFlag;
28944         },
28945
28946 /**
28947  *      Part of the Roo.dd.DropZone interface. If no target node is found, the
28948  *      whole Element becomes the target, and this causes the drop gesture to append.
28949  */
28950     getTargetFromEvent : function(e) {
28951                 var target = e.getTarget();
28952                 while ((target !== null) && (target.parentNode != this.el.dom)) {
28953                 target = target.parentNode;
28954                 }
28955                 if (!target) {
28956                         target = this.el.dom.lastChild || this.el.dom;
28957                 }
28958                 return target;
28959     },
28960
28961 /**
28962  *      Create the drag data which consists of an object which has the property "ddel" as
28963  *      the drag proxy element. 
28964  */
28965     getDragData : function(e) {
28966         var target = this.findItemFromChild(e.getTarget());
28967                 if(target) {
28968                         this.handleSelection(e);
28969                         var selNodes = this.getSelectedNodes();
28970             var dragData = {
28971                 source: this,
28972                 copy: this.copy || (this.allowCopy && e.ctrlKey),
28973                 nodes: selNodes,
28974                 records: []
28975                         };
28976                         var selectedIndices = this.getSelectedIndexes();
28977                         for (var i = 0; i < selectedIndices.length; i++) {
28978                                 dragData.records.push(this.store.getAt(selectedIndices[i]));
28979                         }
28980                         if (selNodes.length == 1) {
28981                                 dragData.ddel = target.cloneNode(true); // the div element
28982                         } else {
28983                                 var div = document.createElement('div'); // create the multi element drag "ghost"
28984                                 div.className = 'multi-proxy';
28985                                 for (var i = 0, len = selNodes.length; i < len; i++) {
28986                                         div.appendChild(selNodes[i].cloneNode(true));
28987                                 }
28988                                 dragData.ddel = div;
28989                         }
28990             //console.log(dragData)
28991             //console.log(dragData.ddel.innerHTML)
28992                         return dragData;
28993                 }
28994         //console.log('nodragData')
28995                 return false;
28996     },
28997     
28998 /**     Specify to which ddGroup items in this DDView may be dragged. */
28999     setDraggable: function(ddGroup) {
29000         if (ddGroup instanceof Array) {
29001                 Roo.each(ddGroup, this.setDraggable, this);
29002                 return;
29003         }
29004         if (this.dragZone) {
29005                 this.dragZone.addToGroup(ddGroup);
29006         } else {
29007                         this.dragZone = new Roo.dd.DragZone(this.getEl(), {
29008                                 containerScroll: true,
29009                                 ddGroup: ddGroup 
29010
29011                         });
29012 //                      Draggability implies selection. DragZone's mousedown selects the element.
29013                         if (!this.multiSelect) { this.singleSelect = true; }
29014
29015 //                      Wire the DragZone's handlers up to methods in *this*
29016                         this.dragZone.getDragData = this.getDragData.createDelegate(this);
29017                 }
29018     },
29019
29020 /**     Specify from which ddGroup this DDView accepts drops. */
29021     setDroppable: function(ddGroup) {
29022         if (ddGroup instanceof Array) {
29023                 Roo.each(ddGroup, this.setDroppable, this);
29024                 return;
29025         }
29026         if (this.dropZone) {
29027                 this.dropZone.addToGroup(ddGroup);
29028         } else {
29029                         this.dropZone = new Roo.dd.DropZone(this.getEl(), {
29030                                 containerScroll: true,
29031                                 ddGroup: ddGroup
29032                         });
29033
29034 //                      Wire the DropZone's handlers up to methods in *this*
29035                         this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
29036                         this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
29037                         this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
29038                         this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
29039                         this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
29040                 }
29041     },
29042
29043 /**     Decide whether to drop above or below a View node. */
29044     getDropPoint : function(e, n, dd){
29045         if (n == this.el.dom) { return "above"; }
29046                 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
29047                 var c = t + (b - t) / 2;
29048                 var y = Roo.lib.Event.getPageY(e);
29049                 if(y <= c) {
29050                         return "above";
29051                 }else{
29052                         return "below";
29053                 }
29054     },
29055
29056     onNodeEnter : function(n, dd, e, data){
29057                 return false;
29058     },
29059     
29060     onNodeOver : function(n, dd, e, data){
29061                 var pt = this.getDropPoint(e, n, dd);
29062                 // set the insert point style on the target node
29063                 var dragElClass = this.dropNotAllowed;
29064                 if (pt) {
29065                         var targetElClass;
29066                         if (pt == "above"){
29067                                 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
29068                                 targetElClass = "x-view-drag-insert-above";
29069                         } else {
29070                                 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
29071                                 targetElClass = "x-view-drag-insert-below";
29072                         }
29073                         if (this.lastInsertClass != targetElClass){
29074                                 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
29075                                 this.lastInsertClass = targetElClass;
29076                         }
29077                 }
29078                 return dragElClass;
29079         },
29080
29081     onNodeOut : function(n, dd, e, data){
29082                 this.removeDropIndicators(n);
29083     },
29084
29085     onNodeDrop : function(n, dd, e, data){
29086         if (this.fireEvent("drop", this, n, dd, e, data) === false) {
29087                 return false;
29088         }
29089         var pt = this.getDropPoint(e, n, dd);
29090                 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
29091                 if (pt == "below") { insertAt++; }
29092                 for (var i = 0; i < data.records.length; i++) {
29093                         var r = data.records[i];
29094                         var dup = this.store.getById(r.id);
29095                         if (dup && (dd != this.dragZone)) {
29096                                 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
29097                         } else {
29098                                 if (data.copy) {
29099                                         this.store.insert(insertAt++, r.copy());
29100                                 } else {
29101                                         data.source.isDirtyFlag = true;
29102                                         r.store.remove(r);
29103                                         this.store.insert(insertAt++, r);
29104                                 }
29105                                 this.isDirtyFlag = true;
29106                         }
29107                 }
29108                 this.dragZone.cachedTarget = null;
29109                 return true;
29110     },
29111
29112     removeDropIndicators : function(n){
29113                 if(n){
29114                         Roo.fly(n).removeClass([
29115                                 "x-view-drag-insert-above",
29116                                 "x-view-drag-insert-below"]);
29117                         this.lastInsertClass = "_noclass";
29118                 }
29119     },
29120
29121 /**
29122  *      Utility method. Add a delete option to the DDView's context menu.
29123  *      @param {String} imageUrl The URL of the "delete" icon image.
29124  */
29125         setDeletable: function(imageUrl) {
29126                 if (!this.singleSelect && !this.multiSelect) {
29127                         this.singleSelect = true;
29128                 }
29129                 var c = this.getContextMenu();
29130                 this.contextMenu.on("itemclick", function(item) {
29131                         switch (item.id) {
29132                                 case "delete":
29133                                         this.remove(this.getSelectedIndexes());
29134                                         break;
29135                         }
29136                 }, this);
29137                 this.contextMenu.add({
29138                         icon: imageUrl,
29139                         id: "delete",
29140                         text: 'Delete'
29141                 });
29142         },
29143         
29144 /**     Return the context menu for this DDView. */
29145         getContextMenu: function() {
29146                 if (!this.contextMenu) {
29147 //                      Create the View's context menu
29148                         this.contextMenu = new Roo.menu.Menu({
29149                                 id: this.id + "-contextmenu"
29150                         });
29151                         this.el.on("contextmenu", this.showContextMenu, this);
29152                 }
29153                 return this.contextMenu;
29154         },
29155         
29156         disableContextMenu: function() {
29157                 if (this.contextMenu) {
29158                         this.el.un("contextmenu", this.showContextMenu, this);
29159                 }
29160         },
29161
29162         showContextMenu: function(e, item) {
29163         item = this.findItemFromChild(e.getTarget());
29164                 if (item) {
29165                         e.stopEvent();
29166                         this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
29167                         this.contextMenu.showAt(e.getXY());
29168             }
29169     },
29170
29171 /**
29172  *      Remove {@link Roo.data.Record}s at the specified indices.
29173  *      @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
29174  */
29175     remove: function(selectedIndices) {
29176                 selectedIndices = [].concat(selectedIndices);
29177                 for (var i = 0; i < selectedIndices.length; i++) {
29178                         var rec = this.store.getAt(selectedIndices[i]);
29179                         this.store.remove(rec);
29180                 }
29181     },
29182
29183 /**
29184  *      Double click fires the event, but also, if this is draggable, and there is only one other
29185  *      related DropZone, it transfers the selected node.
29186  */
29187     onDblClick : function(e){
29188         var item = this.findItemFromChild(e.getTarget());
29189         if(item){
29190             if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
29191                 return false;
29192             }
29193             if (this.dragGroup) {
29194                     var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
29195                     while (targets.indexOf(this.dropZone) > -1) {
29196                             targets.remove(this.dropZone);
29197                                 }
29198                     if (targets.length == 1) {
29199                                         this.dragZone.cachedTarget = null;
29200                         var el = Roo.get(targets[0].getEl());
29201                         var box = el.getBox(true);
29202                         targets[0].onNodeDrop(el.dom, {
29203                                 target: el.dom,
29204                                 xy: [box.x, box.y + box.height - 1]
29205                         }, null, this.getDragData(e));
29206                     }
29207                 }
29208         }
29209     },
29210     
29211     handleSelection: function(e) {
29212                 this.dragZone.cachedTarget = null;
29213         var item = this.findItemFromChild(e.getTarget());
29214         if (!item) {
29215                 this.clearSelections(true);
29216                 return;
29217         }
29218                 if (item && (this.multiSelect || this.singleSelect)){
29219                         if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
29220                                 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
29221                         }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
29222                                 this.unselect(item);
29223                         } else {
29224                                 this.select(item, this.multiSelect && e.ctrlKey);
29225                                 this.lastSelection = item;
29226                         }
29227                 }
29228     },
29229
29230     onItemClick : function(item, index, e){
29231                 if(this.fireEvent("beforeclick", this, index, item, e) === false){
29232                         return false;
29233                 }
29234                 return true;
29235     },
29236
29237     unselect : function(nodeInfo, suppressEvent){
29238                 var node = this.getNode(nodeInfo);
29239                 if(node && this.isSelected(node)){
29240                         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
29241                                 Roo.fly(node).removeClass(this.selectedClass);
29242                                 this.selections.remove(node);
29243                                 if(!suppressEvent){
29244                                         this.fireEvent("selectionchange", this, this.selections);
29245                                 }
29246                         }
29247                 }
29248     }
29249 });
29250 /*
29251  * Based on:
29252  * Ext JS Library 1.1.1
29253  * Copyright(c) 2006-2007, Ext JS, LLC.
29254  *
29255  * Originally Released Under LGPL - original licence link has changed is not relivant.
29256  *
29257  * Fork - LGPL
29258  * <script type="text/javascript">
29259  */
29260  
29261 /**
29262  * @class Roo.LayoutManager
29263  * @extends Roo.util.Observable
29264  * Base class for layout managers.
29265  */
29266 Roo.LayoutManager = function(container, config){
29267     Roo.LayoutManager.superclass.constructor.call(this);
29268     this.el = Roo.get(container);
29269     // ie scrollbar fix
29270     if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
29271         document.body.scroll = "no";
29272     }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
29273         this.el.position('relative');
29274     }
29275     this.id = this.el.id;
29276     this.el.addClass("x-layout-container");
29277     /** false to disable window resize monitoring @type Boolean */
29278     this.monitorWindowResize = true;
29279     this.regions = {};
29280     this.addEvents({
29281         /**
29282          * @event layout
29283          * Fires when a layout is performed. 
29284          * @param {Roo.LayoutManager} this
29285          */
29286         "layout" : true,
29287         /**
29288          * @event regionresized
29289          * Fires when the user resizes a region. 
29290          * @param {Roo.LayoutRegion} region The resized region
29291          * @param {Number} newSize The new size (width for east/west, height for north/south)
29292          */
29293         "regionresized" : true,
29294         /**
29295          * @event regioncollapsed
29296          * Fires when a region is collapsed. 
29297          * @param {Roo.LayoutRegion} region The collapsed region
29298          */
29299         "regioncollapsed" : true,
29300         /**
29301          * @event regionexpanded
29302          * Fires when a region is expanded.  
29303          * @param {Roo.LayoutRegion} region The expanded region
29304          */
29305         "regionexpanded" : true
29306     });
29307     this.updating = false;
29308     Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
29309 };
29310
29311 Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
29312     /**
29313      * Returns true if this layout is currently being updated
29314      * @return {Boolean}
29315      */
29316     isUpdating : function(){
29317         return this.updating; 
29318     },
29319     
29320     /**
29321      * Suspend the LayoutManager from doing auto-layouts while
29322      * making multiple add or remove calls
29323      */
29324     beginUpdate : function(){
29325         this.updating = true;    
29326     },
29327     
29328     /**
29329      * Restore auto-layouts and optionally disable the manager from performing a layout
29330      * @param {Boolean} noLayout true to disable a layout update 
29331      */
29332     endUpdate : function(noLayout){
29333         this.updating = false;
29334         if(!noLayout){
29335             this.layout();
29336         }    
29337     },
29338     
29339     layout: function(){
29340         
29341     },
29342     
29343     onRegionResized : function(region, newSize){
29344         this.fireEvent("regionresized", region, newSize);
29345         this.layout();
29346     },
29347     
29348     onRegionCollapsed : function(region){
29349         this.fireEvent("regioncollapsed", region);
29350     },
29351     
29352     onRegionExpanded : function(region){
29353         this.fireEvent("regionexpanded", region);
29354     },
29355         
29356     /**
29357      * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
29358      * performs box-model adjustments.
29359      * @return {Object} The size as an object {width: (the width), height: (the height)}
29360      */
29361     getViewSize : function(){
29362         var size;
29363         if(this.el.dom != document.body){
29364             size = this.el.getSize();
29365         }else{
29366             size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
29367         }
29368         size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
29369         size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
29370         return size;
29371     },
29372     
29373     /**
29374      * Returns the Element this layout is bound to.
29375      * @return {Roo.Element}
29376      */
29377     getEl : function(){
29378         return this.el;
29379     },
29380     
29381     /**
29382      * Returns the specified region.
29383      * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
29384      * @return {Roo.LayoutRegion}
29385      */
29386     getRegion : function(target){
29387         return this.regions[target.toLowerCase()];
29388     },
29389     
29390     onWindowResize : function(){
29391         if(this.monitorWindowResize){
29392             this.layout();
29393         }
29394     }
29395 });/*
29396  * Based on:
29397  * Ext JS Library 1.1.1
29398  * Copyright(c) 2006-2007, Ext JS, LLC.
29399  *
29400  * Originally Released Under LGPL - original licence link has changed is not relivant.
29401  *
29402  * Fork - LGPL
29403  * <script type="text/javascript">
29404  */
29405 /**
29406  * @class Roo.BorderLayout
29407  * @extends Roo.LayoutManager
29408  * @children Roo.ContentPanel
29409  * This class represents a common layout manager used in desktop applications. For screenshots and more details,
29410  * please see: <br><br>
29411  * <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>
29412  * <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>
29413  * Example:
29414  <pre><code>
29415  var layout = new Roo.BorderLayout(document.body, {
29416     north: {
29417         initialSize: 25,
29418         titlebar: false
29419     },
29420     west: {
29421         split:true,
29422         initialSize: 200,
29423         minSize: 175,
29424         maxSize: 400,
29425         titlebar: true,
29426         collapsible: true
29427     },
29428     east: {
29429         split:true,
29430         initialSize: 202,
29431         minSize: 175,
29432         maxSize: 400,
29433         titlebar: true,
29434         collapsible: true
29435     },
29436     south: {
29437         split:true,
29438         initialSize: 100,
29439         minSize: 100,
29440         maxSize: 200,
29441         titlebar: true,
29442         collapsible: true
29443     },
29444     center: {
29445         titlebar: true,
29446         autoScroll:true,
29447         resizeTabs: true,
29448         minTabWidth: 50,
29449         preferredTabWidth: 150
29450     }
29451 });
29452
29453 // shorthand
29454 var CP = Roo.ContentPanel;
29455
29456 layout.beginUpdate();
29457 layout.add("north", new CP("north", "North"));
29458 layout.add("south", new CP("south", {title: "South", closable: true}));
29459 layout.add("west", new CP("west", {title: "West"}));
29460 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
29461 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
29462 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
29463 layout.getRegion("center").showPanel("center1");
29464 layout.endUpdate();
29465 </code></pre>
29466
29467 <b>The container the layout is rendered into can be either the body element or any other element.
29468 If it is not the body element, the container needs to either be an absolute positioned element,
29469 or you will need to add "position:relative" to the css of the container.  You will also need to specify
29470 the container size if it is not the body element.</b>
29471
29472 * @constructor
29473 * Create a new BorderLayout
29474 * @param {String/HTMLElement/Element} container The container this layout is bound to
29475 * @param {Object} config Configuration options
29476  */
29477 Roo.BorderLayout = function(container, config){
29478     config = config || {};
29479     Roo.BorderLayout.superclass.constructor.call(this, container, config);
29480     this.factory = config.factory || Roo.BorderLayout.RegionFactory;
29481     for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
29482         var target = this.factory.validRegions[i];
29483         if(config[target]){
29484             this.addRegion(target, config[target]);
29485         }
29486     }
29487 };
29488
29489 Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
29490         
29491         /**
29492          * @cfg {Roo.LayoutRegion} east
29493          */
29494         /**
29495          * @cfg {Roo.LayoutRegion} west
29496          */
29497         /**
29498          * @cfg {Roo.LayoutRegion} north
29499          */
29500         /**
29501          * @cfg {Roo.LayoutRegion} south
29502          */
29503         /**
29504          * @cfg {Roo.LayoutRegion} center
29505          */
29506     /**
29507      * Creates and adds a new region if it doesn't already exist.
29508      * @param {String} target The target region key (north, south, east, west or center).
29509      * @param {Object} config The regions config object
29510      * @return {BorderLayoutRegion} The new region
29511      */
29512     addRegion : function(target, config){
29513         if(!this.regions[target]){
29514             var r = this.factory.create(target, this, config);
29515             this.bindRegion(target, r);
29516         }
29517         return this.regions[target];
29518     },
29519
29520     // private (kinda)
29521     bindRegion : function(name, r){
29522         this.regions[name] = r;
29523         r.on("visibilitychange", this.layout, this);
29524         r.on("paneladded", this.layout, this);
29525         r.on("panelremoved", this.layout, this);
29526         r.on("invalidated", this.layout, this);
29527         r.on("resized", this.onRegionResized, this);
29528         r.on("collapsed", this.onRegionCollapsed, this);
29529         r.on("expanded", this.onRegionExpanded, this);
29530     },
29531
29532     /**
29533      * Performs a layout update.
29534      */
29535     layout : function(){
29536         if(this.updating) {
29537             return;
29538         }
29539         var size = this.getViewSize();
29540         var w = size.width;
29541         var h = size.height;
29542         var centerW = w;
29543         var centerH = h;
29544         var centerY = 0;
29545         var centerX = 0;
29546         //var x = 0, y = 0;
29547
29548         var rs = this.regions;
29549         var north = rs["north"];
29550         var south = rs["south"]; 
29551         var west = rs["west"];
29552         var east = rs["east"];
29553         var center = rs["center"];
29554         //if(this.hideOnLayout){ // not supported anymore
29555             //c.el.setStyle("display", "none");
29556         //}
29557         if(north && north.isVisible()){
29558             var b = north.getBox();
29559             var m = north.getMargins();
29560             b.width = w - (m.left+m.right);
29561             b.x = m.left;
29562             b.y = m.top;
29563             centerY = b.height + b.y + m.bottom;
29564             centerH -= centerY;
29565             north.updateBox(this.safeBox(b));
29566         }
29567         if(south && south.isVisible()){
29568             var b = south.getBox();
29569             var m = south.getMargins();
29570             b.width = w - (m.left+m.right);
29571             b.x = m.left;
29572             var totalHeight = (b.height + m.top + m.bottom);
29573             b.y = h - totalHeight + m.top;
29574             centerH -= totalHeight;
29575             south.updateBox(this.safeBox(b));
29576         }
29577         if(west && west.isVisible()){
29578             var b = west.getBox();
29579             var m = west.getMargins();
29580             b.height = centerH - (m.top+m.bottom);
29581             b.x = m.left;
29582             b.y = centerY + m.top;
29583             var totalWidth = (b.width + m.left + m.right);
29584             centerX += totalWidth;
29585             centerW -= totalWidth;
29586             west.updateBox(this.safeBox(b));
29587         }
29588         if(east && east.isVisible()){
29589             var b = east.getBox();
29590             var m = east.getMargins();
29591             b.height = centerH - (m.top+m.bottom);
29592             var totalWidth = (b.width + m.left + m.right);
29593             b.x = w - totalWidth + m.left;
29594             b.y = centerY + m.top;
29595             centerW -= totalWidth;
29596             east.updateBox(this.safeBox(b));
29597         }
29598         if(center){
29599             var m = center.getMargins();
29600             var centerBox = {
29601                 x: centerX + m.left,
29602                 y: centerY + m.top,
29603                 width: centerW - (m.left+m.right),
29604                 height: centerH - (m.top+m.bottom)
29605             };
29606             //if(this.hideOnLayout){
29607                 //center.el.setStyle("display", "block");
29608             //}
29609             center.updateBox(this.safeBox(centerBox));
29610         }
29611         this.el.repaint();
29612         this.fireEvent("layout", this);
29613     },
29614
29615     // private
29616     safeBox : function(box){
29617         box.width = Math.max(0, box.width);
29618         box.height = Math.max(0, box.height);
29619         return box;
29620     },
29621
29622     /**
29623      * Adds a ContentPanel (or subclass) to this layout.
29624      * @param {String} target The target region key (north, south, east, west or center).
29625      * @param {Roo.ContentPanel} panel The panel to add
29626      * @return {Roo.ContentPanel} The added panel
29627      */
29628     add : function(target, panel){
29629          
29630         target = target.toLowerCase();
29631         return this.regions[target].add(panel);
29632     },
29633
29634     /**
29635      * Remove a ContentPanel (or subclass) to this layout.
29636      * @param {String} target The target region key (north, south, east, west or center).
29637      * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
29638      * @return {Roo.ContentPanel} The removed panel
29639      */
29640     remove : function(target, panel){
29641         target = target.toLowerCase();
29642         return this.regions[target].remove(panel);
29643     },
29644
29645     /**
29646      * Searches all regions for a panel with the specified id
29647      * @param {String} panelId
29648      * @return {Roo.ContentPanel} The panel or null if it wasn't found
29649      */
29650     findPanel : function(panelId){
29651         var rs = this.regions;
29652         for(var target in rs){
29653             if(typeof rs[target] != "function"){
29654                 var p = rs[target].getPanel(panelId);
29655                 if(p){
29656                     return p;
29657                 }
29658             }
29659         }
29660         return null;
29661     },
29662
29663     /**
29664      * Searches all regions for a panel with the specified id and activates (shows) it.
29665      * @param {String/ContentPanel} panelId The panels id or the panel itself
29666      * @return {Roo.ContentPanel} The shown panel or null
29667      */
29668     showPanel : function(panelId) {
29669       var rs = this.regions;
29670       for(var target in rs){
29671          var r = rs[target];
29672          if(typeof r != "function"){
29673             if(r.hasPanel(panelId)){
29674                return r.showPanel(panelId);
29675             }
29676          }
29677       }
29678       return null;
29679    },
29680
29681    /**
29682      * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
29683      * @param {Roo.state.Provider} provider (optional) An alternate state provider
29684      */
29685     restoreState : function(provider){
29686         if(!provider){
29687             provider = Roo.state.Manager;
29688         }
29689         var sm = new Roo.LayoutStateManager();
29690         sm.init(this, provider);
29691     },
29692
29693     /**
29694      * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object.  This config
29695      * object should contain properties for each region to add ContentPanels to, and each property's value should be
29696      * a valid ContentPanel config object.  Example:
29697      * <pre><code>
29698 // Create the main layout
29699 var layout = new Roo.BorderLayout('main-ct', {
29700     west: {
29701         split:true,
29702         minSize: 175,
29703         titlebar: true
29704     },
29705     center: {
29706         title:'Components'
29707     }
29708 }, 'main-ct');
29709
29710 // Create and add multiple ContentPanels at once via configs
29711 layout.batchAdd({
29712    west: {
29713        id: 'source-files',
29714        autoCreate:true,
29715        title:'Ext Source Files',
29716        autoScroll:true,
29717        fitToFrame:true
29718    },
29719    center : {
29720        el: cview,
29721        autoScroll:true,
29722        fitToFrame:true,
29723        toolbar: tb,
29724        resizeEl:'cbody'
29725    }
29726 });
29727 </code></pre>
29728      * @param {Object} regions An object containing ContentPanel configs by region name
29729      */
29730     batchAdd : function(regions){
29731         this.beginUpdate();
29732         for(var rname in regions){
29733             var lr = this.regions[rname];
29734             if(lr){
29735                 this.addTypedPanels(lr, regions[rname]);
29736             }
29737         }
29738         this.endUpdate();
29739     },
29740
29741     // private
29742     addTypedPanels : function(lr, ps){
29743         if(typeof ps == 'string'){
29744             lr.add(new Roo.ContentPanel(ps));
29745         }
29746         else if(ps instanceof Array){
29747             for(var i =0, len = ps.length; i < len; i++){
29748                 this.addTypedPanels(lr, ps[i]);
29749             }
29750         }
29751         else if(!ps.events){ // raw config?
29752             var el = ps.el;
29753             delete ps.el; // prevent conflict
29754             lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
29755         }
29756         else {  // panel object assumed!
29757             lr.add(ps);
29758         }
29759     },
29760     /**
29761      * Adds a xtype elements to the layout.
29762      * <pre><code>
29763
29764 layout.addxtype({
29765        xtype : 'ContentPanel',
29766        region: 'west',
29767        items: [ .... ]
29768    }
29769 );
29770
29771 layout.addxtype({
29772         xtype : 'NestedLayoutPanel',
29773         region: 'west',
29774         layout: {
29775            center: { },
29776            west: { }   
29777         },
29778         items : [ ... list of content panels or nested layout panels.. ]
29779    }
29780 );
29781 </code></pre>
29782      * @param {Object} cfg Xtype definition of item to add.
29783      */
29784     addxtype : function(cfg)
29785     {
29786         // basically accepts a pannel...
29787         // can accept a layout region..!?!?
29788         //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
29789         
29790         if (!cfg.xtype.match(/Panel$/)) {
29791             return false;
29792         }
29793         var ret = false;
29794         
29795         if (typeof(cfg.region) == 'undefined') {
29796             Roo.log("Failed to add Panel, region was not set");
29797             Roo.log(cfg);
29798             return false;
29799         }
29800         var region = cfg.region;
29801         delete cfg.region;
29802         
29803           
29804         var xitems = [];
29805         if (cfg.items) {
29806             xitems = cfg.items;
29807             delete cfg.items;
29808         }
29809         var nb = false;
29810         
29811         switch(cfg.xtype) 
29812         {
29813             case 'ContentPanel':  // ContentPanel (el, cfg)
29814             case 'ScrollPanel':  // ContentPanel (el, cfg)
29815             case 'ViewPanel': 
29816                 if(cfg.autoCreate) {
29817                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
29818                 } else {
29819                     var el = this.el.createChild();
29820                     ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
29821                 }
29822                 
29823                 this.add(region, ret);
29824                 break;
29825             
29826             
29827             case 'TreePanel': // our new panel!
29828                 cfg.el = this.el.createChild();
29829                 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
29830                 this.add(region, ret);
29831                 break;
29832             
29833             case 'NestedLayoutPanel': 
29834                 // create a new Layout (which is  a Border Layout...
29835                 var el = this.el.createChild();
29836                 var clayout = cfg.layout;
29837                 delete cfg.layout;
29838                 clayout.items   = clayout.items  || [];
29839                 // replace this exitems with the clayout ones..
29840                 xitems = clayout.items;
29841                  
29842                 
29843                 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
29844                     cfg.background = false;
29845                 }
29846                 var layout = new Roo.BorderLayout(el, clayout);
29847                 
29848                 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
29849                 //console.log('adding nested layout panel '  + cfg.toSource());
29850                 this.add(region, ret);
29851                 nb = {}; /// find first...
29852                 break;
29853                 
29854             case 'GridPanel': 
29855             
29856                 // needs grid and region
29857                 
29858                 //var el = this.getRegion(region).el.createChild();
29859                 var el = this.el.createChild();
29860                 // create the grid first...
29861                 
29862                 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
29863                 delete cfg.grid;
29864                 if (region == 'center' && this.active ) {
29865                     cfg.background = false;
29866                 }
29867                 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
29868                 
29869                 this.add(region, ret);
29870                 if (cfg.background) {
29871                     ret.on('activate', function(gp) {
29872                         if (!gp.grid.rendered) {
29873                             gp.grid.render();
29874                         }
29875                     });
29876                 } else {
29877                     grid.render();
29878                 }
29879                 break;
29880            
29881            
29882            
29883                 
29884                 
29885                 
29886             default:
29887                 if (typeof(Roo[cfg.xtype]) != 'undefined') {
29888                     
29889                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
29890                     this.add(region, ret);
29891                 } else {
29892                 
29893                     alert("Can not add '" + cfg.xtype + "' to BorderLayout");
29894                     return null;
29895                 }
29896                 
29897              // GridPanel (grid, cfg)
29898             
29899         }
29900         this.beginUpdate();
29901         // add children..
29902         var region = '';
29903         var abn = {};
29904         Roo.each(xitems, function(i)  {
29905             region = nb && i.region ? i.region : false;
29906             
29907             var add = ret.addxtype(i);
29908            
29909             if (region) {
29910                 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
29911                 if (!i.background) {
29912                     abn[region] = nb[region] ;
29913                 }
29914             }
29915             
29916         });
29917         this.endUpdate();
29918
29919         // make the last non-background panel active..
29920         //if (nb) { Roo.log(abn); }
29921         if (nb) {
29922             
29923             for(var r in abn) {
29924                 region = this.getRegion(r);
29925                 if (region) {
29926                     // tried using nb[r], but it does not work..
29927                      
29928                     region.showPanel(abn[r]);
29929                    
29930                 }
29931             }
29932         }
29933         return ret;
29934         
29935     }
29936 });
29937
29938 /**
29939  * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
29940  * the beginUpdate and endUpdate calls internally.  The key to this method is the <b>panels</b> property that can be
29941  * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
29942  * during creation.  The following code is equivalent to the constructor-based example at the beginning of this class:
29943  * <pre><code>
29944 // shorthand
29945 var CP = Roo.ContentPanel;
29946
29947 var layout = Roo.BorderLayout.create({
29948     north: {
29949         initialSize: 25,
29950         titlebar: false,
29951         panels: [new CP("north", "North")]
29952     },
29953     west: {
29954         split:true,
29955         initialSize: 200,
29956         minSize: 175,
29957         maxSize: 400,
29958         titlebar: true,
29959         collapsible: true,
29960         panels: [new CP("west", {title: "West"})]
29961     },
29962     east: {
29963         split:true,
29964         initialSize: 202,
29965         minSize: 175,
29966         maxSize: 400,
29967         titlebar: true,
29968         collapsible: true,
29969         panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
29970     },
29971     south: {
29972         split:true,
29973         initialSize: 100,
29974         minSize: 100,
29975         maxSize: 200,
29976         titlebar: true,
29977         collapsible: true,
29978         panels: [new CP("south", {title: "South", closable: true})]
29979     },
29980     center: {
29981         titlebar: true,
29982         autoScroll:true,
29983         resizeTabs: true,
29984         minTabWidth: 50,
29985         preferredTabWidth: 150,
29986         panels: [
29987             new CP("center1", {title: "Close Me", closable: true}),
29988             new CP("center2", {title: "Center Panel", closable: false})
29989         ]
29990     }
29991 }, document.body);
29992
29993 layout.getRegion("center").showPanel("center1");
29994 </code></pre>
29995  * @param config
29996  * @param targetEl
29997  */
29998 Roo.BorderLayout.create = function(config, targetEl){
29999     var layout = new Roo.BorderLayout(targetEl || document.body, config);
30000     layout.beginUpdate();
30001     var regions = Roo.BorderLayout.RegionFactory.validRegions;
30002     for(var j = 0, jlen = regions.length; j < jlen; j++){
30003         var lr = regions[j];
30004         if(layout.regions[lr] && config[lr].panels){
30005             var r = layout.regions[lr];
30006             var ps = config[lr].panels;
30007             layout.addTypedPanels(r, ps);
30008         }
30009     }
30010     layout.endUpdate();
30011     return layout;
30012 };
30013
30014 // private
30015 Roo.BorderLayout.RegionFactory = {
30016     // private
30017     validRegions : ["north","south","east","west","center"],
30018
30019     // private
30020     create : function(target, mgr, config){
30021         target = target.toLowerCase();
30022         if(config.lightweight || config.basic){
30023             return new Roo.BasicLayoutRegion(mgr, config, target);
30024         }
30025         switch(target){
30026             case "north":
30027                 return new Roo.NorthLayoutRegion(mgr, config);
30028             case "south":
30029                 return new Roo.SouthLayoutRegion(mgr, config);
30030             case "east":
30031                 return new Roo.EastLayoutRegion(mgr, config);
30032             case "west":
30033                 return new Roo.WestLayoutRegion(mgr, config);
30034             case "center":
30035                 return new Roo.CenterLayoutRegion(mgr, config);
30036         }
30037         throw 'Layout region "'+target+'" not supported.';
30038     }
30039 };/*
30040  * Based on:
30041  * Ext JS Library 1.1.1
30042  * Copyright(c) 2006-2007, Ext JS, LLC.
30043  *
30044  * Originally Released Under LGPL - original licence link has changed is not relivant.
30045  *
30046  * Fork - LGPL
30047  * <script type="text/javascript">
30048  */
30049  
30050 /**
30051  * @class Roo.BasicLayoutRegion
30052  * @extends Roo.util.Observable
30053  * This class represents a lightweight region in a layout manager. This region does not move dom nodes
30054  * and does not have a titlebar, tabs or any other features. All it does is size and position 
30055  * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
30056  */
30057 Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
30058     this.mgr = mgr;
30059     this.position  = pos;
30060     this.events = {
30061         /**
30062          * @scope Roo.BasicLayoutRegion
30063          */
30064         
30065         /**
30066          * @event beforeremove
30067          * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
30068          * @param {Roo.LayoutRegion} this
30069          * @param {Roo.ContentPanel} panel The panel
30070          * @param {Object} e The cancel event object
30071          */
30072         "beforeremove" : true,
30073         /**
30074          * @event invalidated
30075          * Fires when the layout for this region is changed.
30076          * @param {Roo.LayoutRegion} this
30077          */
30078         "invalidated" : true,
30079         /**
30080          * @event visibilitychange
30081          * Fires when this region is shown or hidden 
30082          * @param {Roo.LayoutRegion} this
30083          * @param {Boolean} visibility true or false
30084          */
30085         "visibilitychange" : true,
30086         /**
30087          * @event paneladded
30088          * Fires when a panel is added. 
30089          * @param {Roo.LayoutRegion} this
30090          * @param {Roo.ContentPanel} panel The panel
30091          */
30092         "paneladded" : true,
30093         /**
30094          * @event panelremoved
30095          * Fires when a panel is removed. 
30096          * @param {Roo.LayoutRegion} this
30097          * @param {Roo.ContentPanel} panel The panel
30098          */
30099         "panelremoved" : true,
30100         /**
30101          * @event beforecollapse
30102          * Fires when this region before collapse.
30103          * @param {Roo.LayoutRegion} this
30104          */
30105         "beforecollapse" : true,
30106         /**
30107          * @event collapsed
30108          * Fires when this region is collapsed.
30109          * @param {Roo.LayoutRegion} this
30110          */
30111         "collapsed" : true,
30112         /**
30113          * @event expanded
30114          * Fires when this region is expanded.
30115          * @param {Roo.LayoutRegion} this
30116          */
30117         "expanded" : true,
30118         /**
30119          * @event slideshow
30120          * Fires when this region is slid into view.
30121          * @param {Roo.LayoutRegion} this
30122          */
30123         "slideshow" : true,
30124         /**
30125          * @event slidehide
30126          * Fires when this region slides out of view. 
30127          * @param {Roo.LayoutRegion} this
30128          */
30129         "slidehide" : true,
30130         /**
30131          * @event panelactivated
30132          * Fires when a panel is activated. 
30133          * @param {Roo.LayoutRegion} this
30134          * @param {Roo.ContentPanel} panel The activated panel
30135          */
30136         "panelactivated" : true,
30137         /**
30138          * @event resized
30139          * Fires when the user resizes this region. 
30140          * @param {Roo.LayoutRegion} this
30141          * @param {Number} newSize The new size (width for east/west, height for north/south)
30142          */
30143         "resized" : true
30144     };
30145     /** A collection of panels in this region. @type Roo.util.MixedCollection */
30146     this.panels = new Roo.util.MixedCollection();
30147     this.panels.getKey = this.getPanelId.createDelegate(this);
30148     this.box = null;
30149     this.activePanel = null;
30150     // ensure listeners are added...
30151     
30152     if (config.listeners || config.events) {
30153         Roo.BasicLayoutRegion.superclass.constructor.call(this, {
30154             listeners : config.listeners || {},
30155             events : config.events || {}
30156         });
30157     }
30158     
30159     if(skipConfig !== true){
30160         this.applyConfig(config);
30161     }
30162 };
30163
30164 Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
30165     getPanelId : function(p){
30166         return p.getId();
30167     },
30168     
30169     applyConfig : function(config){
30170         this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
30171         this.config = config;
30172         
30173     },
30174     
30175     /**
30176      * Resizes the region to the specified size. For vertical regions (west, east) this adjusts 
30177      * the width, for horizontal (north, south) the height.
30178      * @param {Number} newSize The new width or height
30179      */
30180     resizeTo : function(newSize){
30181         var el = this.el ? this.el :
30182                  (this.activePanel ? this.activePanel.getEl() : null);
30183         if(el){
30184             switch(this.position){
30185                 case "east":
30186                 case "west":
30187                     el.setWidth(newSize);
30188                     this.fireEvent("resized", this, newSize);
30189                 break;
30190                 case "north":
30191                 case "south":
30192                     el.setHeight(newSize);
30193                     this.fireEvent("resized", this, newSize);
30194                 break;                
30195             }
30196         }
30197     },
30198     
30199     getBox : function(){
30200         return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
30201     },
30202     
30203     getMargins : function(){
30204         return this.margins;
30205     },
30206     
30207     updateBox : function(box){
30208         this.box = box;
30209         var el = this.activePanel.getEl();
30210         el.dom.style.left = box.x + "px";
30211         el.dom.style.top = box.y + "px";
30212         this.activePanel.setSize(box.width, box.height);
30213     },
30214     
30215     /**
30216      * Returns the container element for this region.
30217      * @return {Roo.Element}
30218      */
30219     getEl : function(){
30220         return this.activePanel;
30221     },
30222     
30223     /**
30224      * Returns true if this region is currently visible.
30225      * @return {Boolean}
30226      */
30227     isVisible : function(){
30228         return this.activePanel ? true : false;
30229     },
30230     
30231     setActivePanel : function(panel){
30232         panel = this.getPanel(panel);
30233         if(this.activePanel && this.activePanel != panel){
30234             this.activePanel.setActiveState(false);
30235             this.activePanel.getEl().setLeftTop(-10000,-10000);
30236         }
30237         this.activePanel = panel;
30238         panel.setActiveState(true);
30239         if(this.box){
30240             panel.setSize(this.box.width, this.box.height);
30241         }
30242         this.fireEvent("panelactivated", this, panel);
30243         this.fireEvent("invalidated");
30244     },
30245     
30246     /**
30247      * Show the specified panel.
30248      * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
30249      * @return {Roo.ContentPanel} The shown panel or null
30250      */
30251     showPanel : function(panel){
30252         if(panel = this.getPanel(panel)){
30253             this.setActivePanel(panel);
30254         }
30255         return panel;
30256     },
30257     
30258     /**
30259      * Get the active panel for this region.
30260      * @return {Roo.ContentPanel} The active panel or null
30261      */
30262     getActivePanel : function(){
30263         return this.activePanel;
30264     },
30265     
30266     /**
30267      * Add the passed ContentPanel(s)
30268      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
30269      * @return {Roo.ContentPanel} The panel added (if only one was added)
30270      */
30271     add : function(panel){
30272         if(arguments.length > 1){
30273             for(var i = 0, len = arguments.length; i < len; i++) {
30274                 this.add(arguments[i]);
30275             }
30276             return null;
30277         }
30278         if(this.hasPanel(panel)){
30279             this.showPanel(panel);
30280             return panel;
30281         }
30282         var el = panel.getEl();
30283         if(el.dom.parentNode != this.mgr.el.dom){
30284             this.mgr.el.dom.appendChild(el.dom);
30285         }
30286         if(panel.setRegion){
30287             panel.setRegion(this);
30288         }
30289         this.panels.add(panel);
30290         el.setStyle("position", "absolute");
30291         if(!panel.background){
30292             this.setActivePanel(panel);
30293             if(this.config.initialSize && this.panels.getCount()==1){
30294                 this.resizeTo(this.config.initialSize);
30295             }
30296         }
30297         this.fireEvent("paneladded", this, panel);
30298         return panel;
30299     },
30300     
30301     /**
30302      * Returns true if the panel is in this region.
30303      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
30304      * @return {Boolean}
30305      */
30306     hasPanel : function(panel){
30307         if(typeof panel == "object"){ // must be panel obj
30308             panel = panel.getId();
30309         }
30310         return this.getPanel(panel) ? true : false;
30311     },
30312     
30313     /**
30314      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
30315      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
30316      * @param {Boolean} preservePanel Overrides the config preservePanel option
30317      * @return {Roo.ContentPanel} The panel that was removed
30318      */
30319     remove : function(panel, preservePanel){
30320         panel = this.getPanel(panel);
30321         if(!panel){
30322             return null;
30323         }
30324         var e = {};
30325         this.fireEvent("beforeremove", this, panel, e);
30326         if(e.cancel === true){
30327             return null;
30328         }
30329         var panelId = panel.getId();
30330         this.panels.removeKey(panelId);
30331         return panel;
30332     },
30333     
30334     /**
30335      * Returns the panel specified or null if it's not in this region.
30336      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
30337      * @return {Roo.ContentPanel}
30338      */
30339     getPanel : function(id){
30340         if(typeof id == "object"){ // must be panel obj
30341             return id;
30342         }
30343         return this.panels.get(id);
30344     },
30345     
30346     /**
30347      * Returns this regions position (north/south/east/west/center).
30348      * @return {String} 
30349      */
30350     getPosition: function(){
30351         return this.position;    
30352     }
30353 });/*
30354  * Based on:
30355  * Ext JS Library 1.1.1
30356  * Copyright(c) 2006-2007, Ext JS, LLC.
30357  *
30358  * Originally Released Under LGPL - original licence link has changed is not relivant.
30359  *
30360  * Fork - LGPL
30361  * <script type="text/javascript">
30362  */
30363  
30364 /**
30365  * @class Roo.LayoutRegion
30366  * @extends Roo.BasicLayoutRegion
30367  * This class represents a region in a layout manager.
30368  * @cfg {Boolean}   collapsible     False to disable collapsing (defaults to true)
30369  * @cfg {Boolean}   collapsed       True to set the initial display to collapsed (defaults to false)
30370  * @cfg {Boolean}   floatable       False to disable floating (defaults to true)
30371  * @cfg {Object}    margins         Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
30372  * @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})
30373  * @cfg {String}    tabPosition     (top|bottom) "top" or "bottom" (defaults to "bottom")
30374  * @cfg {String}    collapsedTitle  Optional string message to display in the collapsed block of a north or south region
30375  * @cfg {Boolean}   alwaysShowTabs  True to always display tabs even when there is only 1 panel (defaults to false)
30376  * @cfg {Boolean}   autoScroll      True to enable overflow scrolling (defaults to false)
30377  * @cfg {Boolean}   titlebar        True to display a title bar (defaults to true)
30378  * @cfg {String}    title           The title for the region (overrides panel titles)
30379  * @cfg {Boolean}   animate         True to animate expand/collapse (defaults to false)
30380  * @cfg {Boolean}   autoHide        False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
30381  * @cfg {Boolean}   preservePanels  True to preserve removed panels so they can be readded later (defaults to false)
30382  * @cfg {Boolean}   closeOnTab      True to place the close icon on the tabs instead of the region titlebar (defaults to false)
30383  * @cfg {Boolean}   hideTabs        True to hide the tab strip (defaults to false)
30384  * @cfg {Boolean}   resizeTabs      True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
30385  *                      the space available, similar to FireFox 1.5 tabs (defaults to false)
30386  * @cfg {Number}    minTabWidth     The minimum tab width (defaults to 40)
30387  * @cfg {Number}    preferredTabWidth The preferred tab width (defaults to 150)
30388  * @cfg {Boolean}   showPin         True to show a pin button
30389  * @cfg {Boolean}   hidden          True to start the region hidden (defaults to false)
30390  * @cfg {Boolean}   hideWhenEmpty   True to hide the region when it has no panels
30391  * @cfg {Boolean}   disableTabTips  True to disable tab tooltips
30392  * @cfg {Number}    width           For East/West panels
30393  * @cfg {Number}    height          For North/South panels
30394  * @cfg {Boolean}   split           To show the splitter
30395  * @cfg {Boolean}   toolbar         xtype configuration for a toolbar - shows on right of tabbar
30396  */
30397 Roo.LayoutRegion = function(mgr, config, pos){
30398     Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
30399     var dh = Roo.DomHelper;
30400     /** This region's container element 
30401     * @type Roo.Element */
30402     this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
30403     /** This region's title element 
30404     * @type Roo.Element */
30405
30406     this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
30407         {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: "&#160;"},
30408         {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
30409     ]}, true);
30410     this.titleEl.enableDisplayMode();
30411     /** This region's title text element 
30412     * @type HTMLElement */
30413     this.titleTextEl = this.titleEl.dom.firstChild;
30414     this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
30415     this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
30416     this.closeBtn.enableDisplayMode();
30417     this.closeBtn.on("click", this.closeClicked, this);
30418     this.closeBtn.hide();
30419
30420     this.createBody(config);
30421     this.visible = true;
30422     this.collapsed = false;
30423
30424     if(config.hideWhenEmpty){
30425         this.hide();
30426         this.on("paneladded", this.validateVisibility, this);
30427         this.on("panelremoved", this.validateVisibility, this);
30428     }
30429     this.applyConfig(config);
30430 };
30431
30432 Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
30433
30434     createBody : function(){
30435         /** This region's body element 
30436         * @type Roo.Element */
30437         this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
30438     },
30439
30440     applyConfig : function(c){
30441         if(c.collapsible && this.position != "center" && !this.collapsedEl){
30442             var dh = Roo.DomHelper;
30443             if(c.titlebar !== false){
30444                 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
30445                 this.collapseBtn.on("click", this.collapse, this);
30446                 this.collapseBtn.enableDisplayMode();
30447
30448                 if(c.showPin === true || this.showPin){
30449                     this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
30450                     this.stickBtn.enableDisplayMode();
30451                     this.stickBtn.on("click", this.expand, this);
30452                     this.stickBtn.hide();
30453                 }
30454             }
30455             /** This region's collapsed element
30456             * @type Roo.Element */
30457             this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
30458                 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
30459             ]}, true);
30460             if(c.floatable !== false){
30461                this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
30462                this.collapsedEl.on("click", this.collapseClick, this);
30463             }
30464
30465             if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
30466                 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
30467                    id: "message", unselectable: "on", style:{"float":"left"}});
30468                this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
30469              }
30470             this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
30471             this.expandBtn.on("click", this.expand, this);
30472         }
30473         if(this.collapseBtn){
30474             this.collapseBtn.setVisible(c.collapsible == true);
30475         }
30476         this.cmargins = c.cmargins || this.cmargins ||
30477                          (this.position == "west" || this.position == "east" ?
30478                              {top: 0, left: 2, right:2, bottom: 0} :
30479                              {top: 2, left: 0, right:0, bottom: 2});
30480         this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
30481         this.bottomTabs = c.tabPosition != "top";
30482         this.autoScroll = c.autoScroll || false;
30483         if(this.autoScroll){
30484             this.bodyEl.setStyle("overflow", "auto");
30485         }else{
30486             this.bodyEl.setStyle("overflow", "hidden");
30487         }
30488         //if(c.titlebar !== false){
30489             if((!c.titlebar && !c.title) || c.titlebar === false){
30490                 this.titleEl.hide();
30491             }else{
30492                 this.titleEl.show();
30493                 if(c.title){
30494                     this.titleTextEl.innerHTML = c.title;
30495                 }
30496             }
30497         //}
30498         this.duration = c.duration || .30;
30499         this.slideDuration = c.slideDuration || .45;
30500         this.config = c;
30501         if(c.collapsed){
30502             this.collapse(true);
30503         }
30504         if(c.hidden){
30505             this.hide();
30506         }
30507     },
30508     /**
30509      * Returns true if this region is currently visible.
30510      * @return {Boolean}
30511      */
30512     isVisible : function(){
30513         return this.visible;
30514     },
30515
30516     /**
30517      * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
30518      * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&amp;#160;")
30519      */
30520     setCollapsedTitle : function(title){
30521         title = title || "&#160;";
30522         if(this.collapsedTitleTextEl){
30523             this.collapsedTitleTextEl.innerHTML = title;
30524         }
30525     },
30526
30527     getBox : function(){
30528         var b;
30529         if(!this.collapsed){
30530             b = this.el.getBox(false, true);
30531         }else{
30532             b = this.collapsedEl.getBox(false, true);
30533         }
30534         return b;
30535     },
30536
30537     getMargins : function(){
30538         return this.collapsed ? this.cmargins : this.margins;
30539     },
30540
30541     highlight : function(){
30542         this.el.addClass("x-layout-panel-dragover");
30543     },
30544
30545     unhighlight : function(){
30546         this.el.removeClass("x-layout-panel-dragover");
30547     },
30548
30549     updateBox : function(box){
30550         this.box = box;
30551         if(!this.collapsed){
30552             this.el.dom.style.left = box.x + "px";
30553             this.el.dom.style.top = box.y + "px";
30554             this.updateBody(box.width, box.height);
30555         }else{
30556             this.collapsedEl.dom.style.left = box.x + "px";
30557             this.collapsedEl.dom.style.top = box.y + "px";
30558             this.collapsedEl.setSize(box.width, box.height);
30559         }
30560         if(this.tabs){
30561             this.tabs.autoSizeTabs();
30562         }
30563     },
30564
30565     updateBody : function(w, h){
30566         if(w !== null){
30567             this.el.setWidth(w);
30568             w -= this.el.getBorderWidth("rl");
30569             if(this.config.adjustments){
30570                 w += this.config.adjustments[0];
30571             }
30572         }
30573         if(h !== null){
30574             this.el.setHeight(h);
30575             h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
30576             h -= this.el.getBorderWidth("tb");
30577             if(this.config.adjustments){
30578                 h += this.config.adjustments[1];
30579             }
30580             this.bodyEl.setHeight(h);
30581             if(this.tabs){
30582                 h = this.tabs.syncHeight(h);
30583             }
30584         }
30585         if(this.panelSize){
30586             w = w !== null ? w : this.panelSize.width;
30587             h = h !== null ? h : this.panelSize.height;
30588         }
30589         if(this.activePanel){
30590             var el = this.activePanel.getEl();
30591             w = w !== null ? w : el.getWidth();
30592             h = h !== null ? h : el.getHeight();
30593             this.panelSize = {width: w, height: h};
30594             this.activePanel.setSize(w, h);
30595         }
30596         if(Roo.isIE && this.tabs){
30597             this.tabs.el.repaint();
30598         }
30599     },
30600
30601     /**
30602      * Returns the container element for this region.
30603      * @return {Roo.Element}
30604      */
30605     getEl : function(){
30606         return this.el;
30607     },
30608
30609     /**
30610      * Hides this region.
30611      */
30612     hide : function(){
30613         if(!this.collapsed){
30614             this.el.dom.style.left = "-2000px";
30615             this.el.hide();
30616         }else{
30617             this.collapsedEl.dom.style.left = "-2000px";
30618             this.collapsedEl.hide();
30619         }
30620         this.visible = false;
30621         this.fireEvent("visibilitychange", this, false);
30622     },
30623
30624     /**
30625      * Shows this region if it was previously hidden.
30626      */
30627     show : function(){
30628         if(!this.collapsed){
30629             this.el.show();
30630         }else{
30631             this.collapsedEl.show();
30632         }
30633         this.visible = true;
30634         this.fireEvent("visibilitychange", this, true);
30635     },
30636
30637     closeClicked : function(){
30638         if(this.activePanel){
30639             this.remove(this.activePanel);
30640         }
30641     },
30642
30643     collapseClick : function(e){
30644         if(this.isSlid){
30645            e.stopPropagation();
30646            this.slideIn();
30647         }else{
30648            e.stopPropagation();
30649            this.slideOut();
30650         }
30651     },
30652
30653     /**
30654      * Collapses this region.
30655      * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
30656      */
30657     collapse : function(skipAnim, skipCheck){
30658         if(this.collapsed) {
30659             return;
30660         }
30661         
30662         if(skipCheck || this.fireEvent("beforecollapse", this) != false){
30663             
30664             this.collapsed = true;
30665             if(this.split){
30666                 this.split.el.hide();
30667             }
30668             if(this.config.animate && skipAnim !== true){
30669                 this.fireEvent("invalidated", this);
30670                 this.animateCollapse();
30671             }else{
30672                 this.el.setLocation(-20000,-20000);
30673                 this.el.hide();
30674                 this.collapsedEl.show();
30675                 this.fireEvent("collapsed", this);
30676                 this.fireEvent("invalidated", this);
30677             }
30678         }
30679         
30680     },
30681
30682     animateCollapse : function(){
30683         // overridden
30684     },
30685
30686     /**
30687      * Expands this region if it was previously collapsed.
30688      * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
30689      * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
30690      */
30691     expand : function(e, skipAnim){
30692         if(e) {
30693             e.stopPropagation();
30694         }
30695         if(!this.collapsed || this.el.hasActiveFx()) {
30696             return;
30697         }
30698         if(this.isSlid){
30699             this.afterSlideIn();
30700             skipAnim = true;
30701         }
30702         this.collapsed = false;
30703         if(this.config.animate && skipAnim !== true){
30704             this.animateExpand();
30705         }else{
30706             this.el.show();
30707             if(this.split){
30708                 this.split.el.show();
30709             }
30710             this.collapsedEl.setLocation(-2000,-2000);
30711             this.collapsedEl.hide();
30712             this.fireEvent("invalidated", this);
30713             this.fireEvent("expanded", this);
30714         }
30715     },
30716
30717     animateExpand : function(){
30718         // overridden
30719     },
30720
30721     initTabs : function()
30722     {
30723         this.bodyEl.setStyle("overflow", "hidden");
30724         var ts = new Roo.TabPanel(
30725                 this.bodyEl.dom,
30726                 {
30727                     tabPosition: this.bottomTabs ? 'bottom' : 'top',
30728                     disableTooltips: this.config.disableTabTips,
30729                     toolbar : this.config.toolbar
30730                 }
30731         );
30732         if(this.config.hideTabs){
30733             ts.stripWrap.setDisplayed(false);
30734         }
30735         this.tabs = ts;
30736         ts.resizeTabs = this.config.resizeTabs === true;
30737         ts.minTabWidth = this.config.minTabWidth || 40;
30738         ts.maxTabWidth = this.config.maxTabWidth || 250;
30739         ts.preferredTabWidth = this.config.preferredTabWidth || 150;
30740         ts.monitorResize = false;
30741         ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
30742         ts.bodyEl.addClass('x-layout-tabs-body');
30743         this.panels.each(this.initPanelAsTab, this);
30744     },
30745
30746     initPanelAsTab : function(panel){
30747         var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
30748                     this.config.closeOnTab && panel.isClosable());
30749         if(panel.tabTip !== undefined){
30750             ti.setTooltip(panel.tabTip);
30751         }
30752         ti.on("activate", function(){
30753               this.setActivePanel(panel);
30754         }, this);
30755         if(this.config.closeOnTab){
30756             ti.on("beforeclose", function(t, e){
30757                 e.cancel = true;
30758                 this.remove(panel);
30759             }, this);
30760         }
30761         return ti;
30762     },
30763
30764     updatePanelTitle : function(panel, title){
30765         if(this.activePanel == panel){
30766             this.updateTitle(title);
30767         }
30768         if(this.tabs){
30769             var ti = this.tabs.getTab(panel.getEl().id);
30770             ti.setText(title);
30771             if(panel.tabTip !== undefined){
30772                 ti.setTooltip(panel.tabTip);
30773             }
30774         }
30775     },
30776
30777     updateTitle : function(title){
30778         if(this.titleTextEl && !this.config.title){
30779             this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : "&#160;");
30780         }
30781     },
30782
30783     setActivePanel : function(panel){
30784         panel = this.getPanel(panel);
30785         if(this.activePanel && this.activePanel != panel){
30786             this.activePanel.setActiveState(false);
30787         }
30788         this.activePanel = panel;
30789         panel.setActiveState(true);
30790         if(this.panelSize){
30791             panel.setSize(this.panelSize.width, this.panelSize.height);
30792         }
30793         if(this.closeBtn){
30794             this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
30795         }
30796         this.updateTitle(panel.getTitle());
30797         if(this.tabs){
30798             this.fireEvent("invalidated", this);
30799         }
30800         this.fireEvent("panelactivated", this, panel);
30801     },
30802
30803     /**
30804      * Shows the specified panel.
30805      * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
30806      * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
30807      */
30808     showPanel : function(panel)
30809     {
30810         panel = this.getPanel(panel);
30811         if(panel){
30812             if(this.tabs){
30813                 var tab = this.tabs.getTab(panel.getEl().id);
30814                 if(tab.isHidden()){
30815                     this.tabs.unhideTab(tab.id);
30816                 }
30817                 tab.activate();
30818             }else{
30819                 this.setActivePanel(panel);
30820             }
30821         }
30822         return panel;
30823     },
30824
30825     /**
30826      * Get the active panel for this region.
30827      * @return {Roo.ContentPanel} The active panel or null
30828      */
30829     getActivePanel : function(){
30830         return this.activePanel;
30831     },
30832
30833     validateVisibility : function(){
30834         if(this.panels.getCount() < 1){
30835             this.updateTitle("&#160;");
30836             this.closeBtn.hide();
30837             this.hide();
30838         }else{
30839             if(!this.isVisible()){
30840                 this.show();
30841             }
30842         }
30843     },
30844
30845     /**
30846      * Adds the passed ContentPanel(s) to this region.
30847      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
30848      * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
30849      */
30850     add : function(panel){
30851         if(arguments.length > 1){
30852             for(var i = 0, len = arguments.length; i < len; i++) {
30853                 this.add(arguments[i]);
30854             }
30855             return null;
30856         }
30857         if(this.hasPanel(panel)){
30858             this.showPanel(panel);
30859             return panel;
30860         }
30861         panel.setRegion(this);
30862         this.panels.add(panel);
30863         if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
30864             this.bodyEl.dom.appendChild(panel.getEl().dom);
30865             if(panel.background !== true){
30866                 this.setActivePanel(panel);
30867             }
30868             this.fireEvent("paneladded", this, panel);
30869             return panel;
30870         }
30871         if(!this.tabs){
30872             this.initTabs();
30873         }else{
30874             this.initPanelAsTab(panel);
30875         }
30876         if(panel.background !== true){
30877             this.tabs.activate(panel.getEl().id);
30878         }
30879         this.fireEvent("paneladded", this, panel);
30880         return panel;
30881     },
30882
30883     /**
30884      * Hides the tab for the specified panel.
30885      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
30886      */
30887     hidePanel : function(panel){
30888         if(this.tabs && (panel = this.getPanel(panel))){
30889             this.tabs.hideTab(panel.getEl().id);
30890         }
30891     },
30892
30893     /**
30894      * Unhides the tab for a previously hidden panel.
30895      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
30896      */
30897     unhidePanel : function(panel){
30898         if(this.tabs && (panel = this.getPanel(panel))){
30899             this.tabs.unhideTab(panel.getEl().id);
30900         }
30901     },
30902
30903     clearPanels : function(){
30904         while(this.panels.getCount() > 0){
30905              this.remove(this.panels.first());
30906         }
30907     },
30908
30909     /**
30910      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
30911      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
30912      * @param {Boolean} preservePanel Overrides the config preservePanel option
30913      * @return {Roo.ContentPanel} The panel that was removed
30914      */
30915     remove : function(panel, preservePanel){
30916         panel = this.getPanel(panel);
30917         if(!panel){
30918             return null;
30919         }
30920         var e = {};
30921         this.fireEvent("beforeremove", this, panel, e);
30922         if(e.cancel === true){
30923             return null;
30924         }
30925         preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
30926         var panelId = panel.getId();
30927         this.panels.removeKey(panelId);
30928         if(preservePanel){
30929             document.body.appendChild(panel.getEl().dom);
30930         }
30931         if(this.tabs){
30932             this.tabs.removeTab(panel.getEl().id);
30933         }else if (!preservePanel){
30934             this.bodyEl.dom.removeChild(panel.getEl().dom);
30935         }
30936         if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
30937             var p = this.panels.first();
30938             var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
30939             tempEl.appendChild(p.getEl().dom);
30940             this.bodyEl.update("");
30941             this.bodyEl.dom.appendChild(p.getEl().dom);
30942             tempEl = null;
30943             this.updateTitle(p.getTitle());
30944             this.tabs = null;
30945             this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
30946             this.setActivePanel(p);
30947         }
30948         panel.setRegion(null);
30949         if(this.activePanel == panel){
30950             this.activePanel = null;
30951         }
30952         if(this.config.autoDestroy !== false && preservePanel !== true){
30953             try{panel.destroy();}catch(e){}
30954         }
30955         this.fireEvent("panelremoved", this, panel);
30956         return panel;
30957     },
30958
30959     /**
30960      * Returns the TabPanel component used by this region
30961      * @return {Roo.TabPanel}
30962      */
30963     getTabs : function(){
30964         return this.tabs;
30965     },
30966
30967     createTool : function(parentEl, className){
30968         var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
30969             children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: "&#160;"}]}, true);
30970         btn.addClassOnOver("x-layout-tools-button-over");
30971         return btn;
30972     }
30973 });/*
30974  * Based on:
30975  * Ext JS Library 1.1.1
30976  * Copyright(c) 2006-2007, Ext JS, LLC.
30977  *
30978  * Originally Released Under LGPL - original licence link has changed is not relivant.
30979  *
30980  * Fork - LGPL
30981  * <script type="text/javascript">
30982  */
30983  
30984
30985
30986 /**
30987  * @class Roo.SplitLayoutRegion
30988  * @extends Roo.LayoutRegion
30989  * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
30990  */
30991 Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
30992     this.cursor = cursor;
30993     Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
30994 };
30995
30996 Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
30997     splitTip : "Drag to resize.",
30998     collapsibleSplitTip : "Drag to resize. Double click to hide.",
30999     useSplitTips : false,
31000
31001     applyConfig : function(config){
31002         Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
31003         if(config.split){
31004             if(!this.split){
31005                 var splitEl = Roo.DomHelper.append(this.mgr.el.dom, 
31006                         {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: "&#160;"});
31007                 /** The SplitBar for this region 
31008                 * @type Roo.SplitBar */
31009                 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
31010                 this.split.on("moved", this.onSplitMove, this);
31011                 this.split.useShim = config.useShim === true;
31012                 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
31013                 if(this.useSplitTips){
31014                     this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
31015                 }
31016                 if(config.collapsible){
31017                     this.split.el.on("dblclick", this.collapse,  this);
31018                 }
31019             }
31020             if(typeof config.minSize != "undefined"){
31021                 this.split.minSize = config.minSize;
31022             }
31023             if(typeof config.maxSize != "undefined"){
31024                 this.split.maxSize = config.maxSize;
31025             }
31026             if(config.hideWhenEmpty || config.hidden || config.collapsed){
31027                 this.hideSplitter();
31028             }
31029         }
31030     },
31031
31032     getHMaxSize : function(){
31033          var cmax = this.config.maxSize || 10000;
31034          var center = this.mgr.getRegion("center");
31035          return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
31036     },
31037
31038     getVMaxSize : function(){
31039          var cmax = this.config.maxSize || 10000;
31040          var center = this.mgr.getRegion("center");
31041          return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
31042     },
31043
31044     onSplitMove : function(split, newSize){
31045         this.fireEvent("resized", this, newSize);
31046     },
31047     
31048     /** 
31049      * Returns the {@link Roo.SplitBar} for this region.
31050      * @return {Roo.SplitBar}
31051      */
31052     getSplitBar : function(){
31053         return this.split;
31054     },
31055     
31056     hide : function(){
31057         this.hideSplitter();
31058         Roo.SplitLayoutRegion.superclass.hide.call(this);
31059     },
31060
31061     hideSplitter : function(){
31062         if(this.split){
31063             this.split.el.setLocation(-2000,-2000);
31064             this.split.el.hide();
31065         }
31066     },
31067
31068     show : function(){
31069         if(this.split){
31070             this.split.el.show();
31071         }
31072         Roo.SplitLayoutRegion.superclass.show.call(this);
31073     },
31074     
31075     beforeSlide: function(){
31076         if(Roo.isGecko){// firefox overflow auto bug workaround
31077             this.bodyEl.clip();
31078             if(this.tabs) {
31079                 this.tabs.bodyEl.clip();
31080             }
31081             if(this.activePanel){
31082                 this.activePanel.getEl().clip();
31083                 
31084                 if(this.activePanel.beforeSlide){
31085                     this.activePanel.beforeSlide();
31086                 }
31087             }
31088         }
31089     },
31090     
31091     afterSlide : function(){
31092         if(Roo.isGecko){// firefox overflow auto bug workaround
31093             this.bodyEl.unclip();
31094             if(this.tabs) {
31095                 this.tabs.bodyEl.unclip();
31096             }
31097             if(this.activePanel){
31098                 this.activePanel.getEl().unclip();
31099                 if(this.activePanel.afterSlide){
31100                     this.activePanel.afterSlide();
31101                 }
31102             }
31103         }
31104     },
31105
31106     initAutoHide : function(){
31107         if(this.autoHide !== false){
31108             if(!this.autoHideHd){
31109                 var st = new Roo.util.DelayedTask(this.slideIn, this);
31110                 this.autoHideHd = {
31111                     "mouseout": function(e){
31112                         if(!e.within(this.el, true)){
31113                             st.delay(500);
31114                         }
31115                     },
31116                     "mouseover" : function(e){
31117                         st.cancel();
31118                     },
31119                     scope : this
31120                 };
31121             }
31122             this.el.on(this.autoHideHd);
31123         }
31124     },
31125
31126     clearAutoHide : function(){
31127         if(this.autoHide !== false){
31128             this.el.un("mouseout", this.autoHideHd.mouseout);
31129             this.el.un("mouseover", this.autoHideHd.mouseover);
31130         }
31131     },
31132
31133     clearMonitor : function(){
31134         Roo.get(document).un("click", this.slideInIf, this);
31135     },
31136
31137     // these names are backwards but not changed for compat
31138     slideOut : function(){
31139         if(this.isSlid || this.el.hasActiveFx()){
31140             return;
31141         }
31142         this.isSlid = true;
31143         if(this.collapseBtn){
31144             this.collapseBtn.hide();
31145         }
31146         this.closeBtnState = this.closeBtn.getStyle('display');
31147         this.closeBtn.hide();
31148         if(this.stickBtn){
31149             this.stickBtn.show();
31150         }
31151         this.el.show();
31152         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
31153         this.beforeSlide();
31154         this.el.setStyle("z-index", 10001);
31155         this.el.slideIn(this.getSlideAnchor(), {
31156             callback: function(){
31157                 this.afterSlide();
31158                 this.initAutoHide();
31159                 Roo.get(document).on("click", this.slideInIf, this);
31160                 this.fireEvent("slideshow", this);
31161             },
31162             scope: this,
31163             block: true
31164         });
31165     },
31166
31167     afterSlideIn : function(){
31168         this.clearAutoHide();
31169         this.isSlid = false;
31170         this.clearMonitor();
31171         this.el.setStyle("z-index", "");
31172         if(this.collapseBtn){
31173             this.collapseBtn.show();
31174         }
31175         this.closeBtn.setStyle('display', this.closeBtnState);
31176         if(this.stickBtn){
31177             this.stickBtn.hide();
31178         }
31179         this.fireEvent("slidehide", this);
31180     },
31181
31182     slideIn : function(cb){
31183         if(!this.isSlid || this.el.hasActiveFx()){
31184             Roo.callback(cb);
31185             return;
31186         }
31187         this.isSlid = false;
31188         this.beforeSlide();
31189         this.el.slideOut(this.getSlideAnchor(), {
31190             callback: function(){
31191                 this.el.setLeftTop(-10000, -10000);
31192                 this.afterSlide();
31193                 this.afterSlideIn();
31194                 Roo.callback(cb);
31195             },
31196             scope: this,
31197             block: true
31198         });
31199     },
31200     
31201     slideInIf : function(e){
31202         if(!e.within(this.el)){
31203             this.slideIn();
31204         }
31205     },
31206
31207     animateCollapse : function(){
31208         this.beforeSlide();
31209         this.el.setStyle("z-index", 20000);
31210         var anchor = this.getSlideAnchor();
31211         this.el.slideOut(anchor, {
31212             callback : function(){
31213                 this.el.setStyle("z-index", "");
31214                 this.collapsedEl.slideIn(anchor, {duration:.3});
31215                 this.afterSlide();
31216                 this.el.setLocation(-10000,-10000);
31217                 this.el.hide();
31218                 this.fireEvent("collapsed", this);
31219             },
31220             scope: this,
31221             block: true
31222         });
31223     },
31224
31225     animateExpand : function(){
31226         this.beforeSlide();
31227         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
31228         this.el.setStyle("z-index", 20000);
31229         this.collapsedEl.hide({
31230             duration:.1
31231         });
31232         this.el.slideIn(this.getSlideAnchor(), {
31233             callback : function(){
31234                 this.el.setStyle("z-index", "");
31235                 this.afterSlide();
31236                 if(this.split){
31237                     this.split.el.show();
31238                 }
31239                 this.fireEvent("invalidated", this);
31240                 this.fireEvent("expanded", this);
31241             },
31242             scope: this,
31243             block: true
31244         });
31245     },
31246
31247     anchors : {
31248         "west" : "left",
31249         "east" : "right",
31250         "north" : "top",
31251         "south" : "bottom"
31252     },
31253
31254     sanchors : {
31255         "west" : "l",
31256         "east" : "r",
31257         "north" : "t",
31258         "south" : "b"
31259     },
31260
31261     canchors : {
31262         "west" : "tl-tr",
31263         "east" : "tr-tl",
31264         "north" : "tl-bl",
31265         "south" : "bl-tl"
31266     },
31267
31268     getAnchor : function(){
31269         return this.anchors[this.position];
31270     },
31271
31272     getCollapseAnchor : function(){
31273         return this.canchors[this.position];
31274     },
31275
31276     getSlideAnchor : function(){
31277         return this.sanchors[this.position];
31278     },
31279
31280     getAlignAdj : function(){
31281         var cm = this.cmargins;
31282         switch(this.position){
31283             case "west":
31284                 return [0, 0];
31285             break;
31286             case "east":
31287                 return [0, 0];
31288             break;
31289             case "north":
31290                 return [0, 0];
31291             break;
31292             case "south":
31293                 return [0, 0];
31294             break;
31295         }
31296     },
31297
31298     getExpandAdj : function(){
31299         var c = this.collapsedEl, cm = this.cmargins;
31300         switch(this.position){
31301             case "west":
31302                 return [-(cm.right+c.getWidth()+cm.left), 0];
31303             break;
31304             case "east":
31305                 return [cm.right+c.getWidth()+cm.left, 0];
31306             break;
31307             case "north":
31308                 return [0, -(cm.top+cm.bottom+c.getHeight())];
31309             break;
31310             case "south":
31311                 return [0, cm.top+cm.bottom+c.getHeight()];
31312             break;
31313         }
31314     }
31315 });/*
31316  * Based on:
31317  * Ext JS Library 1.1.1
31318  * Copyright(c) 2006-2007, Ext JS, LLC.
31319  *
31320  * Originally Released Under LGPL - original licence link has changed is not relivant.
31321  *
31322  * Fork - LGPL
31323  * <script type="text/javascript">
31324  */
31325 /*
31326  * These classes are private internal classes
31327  */
31328 Roo.CenterLayoutRegion = function(mgr, config){
31329     Roo.LayoutRegion.call(this, mgr, config, "center");
31330     this.visible = true;
31331     this.minWidth = config.minWidth || 20;
31332     this.minHeight = config.minHeight || 20;
31333 };
31334
31335 Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
31336     hide : function(){
31337         // center panel can't be hidden
31338     },
31339     
31340     show : function(){
31341         // center panel can't be hidden
31342     },
31343     
31344     getMinWidth: function(){
31345         return this.minWidth;
31346     },
31347     
31348     getMinHeight: function(){
31349         return this.minHeight;
31350     }
31351 });
31352
31353
31354 Roo.NorthLayoutRegion = function(mgr, config){
31355     Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
31356     if(this.split){
31357         this.split.placement = Roo.SplitBar.TOP;
31358         this.split.orientation = Roo.SplitBar.VERTICAL;
31359         this.split.el.addClass("x-layout-split-v");
31360     }
31361     var size = config.initialSize || config.height;
31362     if(typeof size != "undefined"){
31363         this.el.setHeight(size);
31364     }
31365 };
31366 Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
31367     orientation: Roo.SplitBar.VERTICAL,
31368     getBox : function(){
31369         if(this.collapsed){
31370             return this.collapsedEl.getBox();
31371         }
31372         var box = this.el.getBox();
31373         if(this.split){
31374             box.height += this.split.el.getHeight();
31375         }
31376         return box;
31377     },
31378     
31379     updateBox : function(box){
31380         if(this.split && !this.collapsed){
31381             box.height -= this.split.el.getHeight();
31382             this.split.el.setLeft(box.x);
31383             this.split.el.setTop(box.y+box.height);
31384             this.split.el.setWidth(box.width);
31385         }
31386         if(this.collapsed){
31387             this.updateBody(box.width, null);
31388         }
31389         Roo.LayoutRegion.prototype.updateBox.call(this, box);
31390     }
31391 });
31392
31393 Roo.SouthLayoutRegion = function(mgr, config){
31394     Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
31395     if(this.split){
31396         this.split.placement = Roo.SplitBar.BOTTOM;
31397         this.split.orientation = Roo.SplitBar.VERTICAL;
31398         this.split.el.addClass("x-layout-split-v");
31399     }
31400     var size = config.initialSize || config.height;
31401     if(typeof size != "undefined"){
31402         this.el.setHeight(size);
31403     }
31404 };
31405 Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
31406     orientation: Roo.SplitBar.VERTICAL,
31407     getBox : function(){
31408         if(this.collapsed){
31409             return this.collapsedEl.getBox();
31410         }
31411         var box = this.el.getBox();
31412         if(this.split){
31413             var sh = this.split.el.getHeight();
31414             box.height += sh;
31415             box.y -= sh;
31416         }
31417         return box;
31418     },
31419     
31420     updateBox : function(box){
31421         if(this.split && !this.collapsed){
31422             var sh = this.split.el.getHeight();
31423             box.height -= sh;
31424             box.y += sh;
31425             this.split.el.setLeft(box.x);
31426             this.split.el.setTop(box.y-sh);
31427             this.split.el.setWidth(box.width);
31428         }
31429         if(this.collapsed){
31430             this.updateBody(box.width, null);
31431         }
31432         Roo.LayoutRegion.prototype.updateBox.call(this, box);
31433     }
31434 });
31435
31436 Roo.EastLayoutRegion = function(mgr, config){
31437     Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
31438     if(this.split){
31439         this.split.placement = Roo.SplitBar.RIGHT;
31440         this.split.orientation = Roo.SplitBar.HORIZONTAL;
31441         this.split.el.addClass("x-layout-split-h");
31442     }
31443     var size = config.initialSize || config.width;
31444     if(typeof size != "undefined"){
31445         this.el.setWidth(size);
31446     }
31447 };
31448 Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
31449     orientation: Roo.SplitBar.HORIZONTAL,
31450     getBox : function(){
31451         if(this.collapsed){
31452             return this.collapsedEl.getBox();
31453         }
31454         var box = this.el.getBox();
31455         if(this.split){
31456             var sw = this.split.el.getWidth();
31457             box.width += sw;
31458             box.x -= sw;
31459         }
31460         return box;
31461     },
31462
31463     updateBox : function(box){
31464         if(this.split && !this.collapsed){
31465             var sw = this.split.el.getWidth();
31466             box.width -= sw;
31467             this.split.el.setLeft(box.x);
31468             this.split.el.setTop(box.y);
31469             this.split.el.setHeight(box.height);
31470             box.x += sw;
31471         }
31472         if(this.collapsed){
31473             this.updateBody(null, box.height);
31474         }
31475         Roo.LayoutRegion.prototype.updateBox.call(this, box);
31476     }
31477 });
31478
31479 Roo.WestLayoutRegion = function(mgr, config){
31480     Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
31481     if(this.split){
31482         this.split.placement = Roo.SplitBar.LEFT;
31483         this.split.orientation = Roo.SplitBar.HORIZONTAL;
31484         this.split.el.addClass("x-layout-split-h");
31485     }
31486     var size = config.initialSize || config.width;
31487     if(typeof size != "undefined"){
31488         this.el.setWidth(size);
31489     }
31490 };
31491 Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
31492     orientation: Roo.SplitBar.HORIZONTAL,
31493     getBox : function(){
31494         if(this.collapsed){
31495             return this.collapsedEl.getBox();
31496         }
31497         var box = this.el.getBox();
31498         if(this.split){
31499             box.width += this.split.el.getWidth();
31500         }
31501         return box;
31502     },
31503     
31504     updateBox : function(box){
31505         if(this.split && !this.collapsed){
31506             var sw = this.split.el.getWidth();
31507             box.width -= sw;
31508             this.split.el.setLeft(box.x+box.width);
31509             this.split.el.setTop(box.y);
31510             this.split.el.setHeight(box.height);
31511         }
31512         if(this.collapsed){
31513             this.updateBody(null, box.height);
31514         }
31515         Roo.LayoutRegion.prototype.updateBox.call(this, box);
31516     }
31517 });
31518 /*
31519  * Based on:
31520  * Ext JS Library 1.1.1
31521  * Copyright(c) 2006-2007, Ext JS, LLC.
31522  *
31523  * Originally Released Under LGPL - original licence link has changed is not relivant.
31524  *
31525  * Fork - LGPL
31526  * <script type="text/javascript">
31527  */
31528  
31529  
31530 /*
31531  * Private internal class for reading and applying state
31532  */
31533 Roo.LayoutStateManager = function(layout){
31534      // default empty state
31535      this.state = {
31536         north: {},
31537         south: {},
31538         east: {},
31539         west: {}       
31540     };
31541 };
31542
31543 Roo.LayoutStateManager.prototype = {
31544     init : function(layout, provider){
31545         this.provider = provider;
31546         var state = provider.get(layout.id+"-layout-state");
31547         if(state){
31548             var wasUpdating = layout.isUpdating();
31549             if(!wasUpdating){
31550                 layout.beginUpdate();
31551             }
31552             for(var key in state){
31553                 if(typeof state[key] != "function"){
31554                     var rstate = state[key];
31555                     var r = layout.getRegion(key);
31556                     if(r && rstate){
31557                         if(rstate.size){
31558                             r.resizeTo(rstate.size);
31559                         }
31560                         if(rstate.collapsed == true){
31561                             r.collapse(true);
31562                         }else{
31563                             r.expand(null, true);
31564                         }
31565                     }
31566                 }
31567             }
31568             if(!wasUpdating){
31569                 layout.endUpdate();
31570             }
31571             this.state = state; 
31572         }
31573         this.layout = layout;
31574         layout.on("regionresized", this.onRegionResized, this);
31575         layout.on("regioncollapsed", this.onRegionCollapsed, this);
31576         layout.on("regionexpanded", this.onRegionExpanded, this);
31577     },
31578     
31579     storeState : function(){
31580         this.provider.set(this.layout.id+"-layout-state", this.state);
31581     },
31582     
31583     onRegionResized : function(region, newSize){
31584         this.state[region.getPosition()].size = newSize;
31585         this.storeState();
31586     },
31587     
31588     onRegionCollapsed : function(region){
31589         this.state[region.getPosition()].collapsed = true;
31590         this.storeState();
31591     },
31592     
31593     onRegionExpanded : function(region){
31594         this.state[region.getPosition()].collapsed = false;
31595         this.storeState();
31596     }
31597 };/*
31598  * Based on:
31599  * Ext JS Library 1.1.1
31600  * Copyright(c) 2006-2007, Ext JS, LLC.
31601  *
31602  * Originally Released Under LGPL - original licence link has changed is not relivant.
31603  *
31604  * Fork - LGPL
31605  * <script type="text/javascript">
31606  */
31607 /**
31608  * @class Roo.ContentPanel
31609  * @extends Roo.util.Observable
31610  * @children Roo.form.Form Roo.JsonView Roo.View
31611  * @parent Roo.BorderLayout Roo.LayoutDialog builder-top
31612  * A basic ContentPanel element.
31613  * @cfg {Boolean}   fitToFrame    True for this panel to adjust its size to fit when the region resizes  (defaults to false)
31614  * @cfg {Boolean}   fitContainer   When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container  (defaults to false)
31615  * @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
31616  * @cfg {Boolean}   closable      True if the panel can be closed/removed
31617  * @cfg {Boolean}   background    True if the panel should not be activated when it is added (defaults to false)
31618  * @cfg {String|HTMLElement|Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
31619  * @cfg {Roo.Toolbar}   toolbar       A toolbar for this panel
31620  * @cfg {Boolean} autoScroll    True to scroll overflow in this panel (use with {@link #fitToFrame})
31621  * @cfg {String} title          The title for this panel
31622  * @cfg {Array} adjustments     Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
31623  * @cfg {String} url            Calls {@link #setUrl} with this value
31624  * @cfg {String} region [required]   (center|north|south|east|west) which region to put this panel on (when used with xtype constructors)
31625  * @cfg {String|Object} params  When used with {@link #url}, calls {@link #setUrl} with this value
31626  * @cfg {Boolean} loadOnce      When used with {@link #url}, calls {@link #setUrl} with this value
31627  * @cfg {String}    content        Raw content to fill content panel with (uses setContent on construction.)
31628  * @cfg {String}    style  Extra style to add to the content panel
31629  * @cfg {Roo.menu.Menu} menu  popup menu
31630
31631  * @constructor
31632  * Create a new ContentPanel.
31633  * @param {String/HTMLElement/Roo.Element} el The container element for this panel
31634  * @param {String/Object} config A string to set only the title or a config object
31635  * @param {String} content (optional) Set the HTML content for this panel
31636  * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
31637  */
31638 Roo.ContentPanel = function(el, config, content){
31639     
31640      
31641     /*
31642     if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
31643         config = el;
31644         el = Roo.id();
31645     }
31646     if (config && config.parentLayout) { 
31647         el = config.parentLayout.el.createChild(); 
31648     }
31649     */
31650     if(el.autoCreate){ // xtype is available if this is called from factory
31651         config = el;
31652         el = Roo.id();
31653     }
31654     this.el = Roo.get(el);
31655     if(!this.el && config && config.autoCreate){
31656         if(typeof config.autoCreate == "object"){
31657             if(!config.autoCreate.id){
31658                 config.autoCreate.id = config.id||el;
31659             }
31660             this.el = Roo.DomHelper.append(document.body,
31661                         config.autoCreate, true);
31662         }else{
31663             this.el = Roo.DomHelper.append(document.body,
31664                         {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
31665         }
31666     }
31667     
31668     
31669     this.closable = false;
31670     this.loaded = false;
31671     this.active = false;
31672     if(typeof config == "string"){
31673         this.title = config;
31674     }else{
31675         Roo.apply(this, config);
31676     }
31677     
31678     if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
31679         this.wrapEl = this.el.wrap();
31680         this.toolbar.container = this.el.insertSibling(false, 'before');
31681         this.toolbar = new Roo.Toolbar(this.toolbar);
31682     }
31683     
31684     // xtype created footer. - not sure if will work as we normally have to render first..
31685     if (this.footer && !this.footer.el && this.footer.xtype) {
31686         if (!this.wrapEl) {
31687             this.wrapEl = this.el.wrap();
31688         }
31689     
31690         this.footer.container = this.wrapEl.createChild();
31691          
31692         this.footer = Roo.factory(this.footer, Roo);
31693         
31694     }
31695     
31696     if(this.resizeEl){
31697         this.resizeEl = Roo.get(this.resizeEl, true);
31698     }else{
31699         this.resizeEl = this.el;
31700     }
31701     // handle view.xtype
31702     
31703  
31704     
31705     
31706     this.addEvents({
31707         /**
31708          * @event activate
31709          * Fires when this panel is activated. 
31710          * @param {Roo.ContentPanel} this
31711          */
31712         "activate" : true,
31713         /**
31714          * @event deactivate
31715          * Fires when this panel is activated. 
31716          * @param {Roo.ContentPanel} this
31717          */
31718         "deactivate" : true,
31719
31720         /**
31721          * @event resize
31722          * Fires when this panel is resized if fitToFrame is true.
31723          * @param {Roo.ContentPanel} this
31724          * @param {Number} width The width after any component adjustments
31725          * @param {Number} height The height after any component adjustments
31726          */
31727         "resize" : true,
31728         
31729          /**
31730          * @event render
31731          * Fires when this tab is created
31732          * @param {Roo.ContentPanel} this
31733          */
31734         "render" : true
31735          
31736         
31737     });
31738     
31739
31740     
31741     
31742     if(this.autoScroll){
31743         this.resizeEl.setStyle("overflow", "auto");
31744     } else {
31745         // fix randome scrolling
31746         this.el.on('scroll', function() {
31747             Roo.log('fix random scolling');
31748             this.scrollTo('top',0); 
31749         });
31750     }
31751     content = content || this.content;
31752     if(content){
31753         this.setContent(content);
31754     }
31755     if(config && config.url){
31756         this.setUrl(this.url, this.params, this.loadOnce);
31757     }
31758     
31759     
31760     
31761     Roo.ContentPanel.superclass.constructor.call(this);
31762     
31763     if (this.view && typeof(this.view.xtype) != 'undefined') {
31764         this.view.el = this.el.appendChild(document.createElement("div"));
31765         this.view = Roo.factory(this.view); 
31766         this.view.render  &&  this.view.render(false, '');  
31767     }
31768     
31769     
31770     this.fireEvent('render', this);
31771 };
31772
31773 Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
31774     tabTip:'',
31775     setRegion : function(region){
31776         this.region = region;
31777         if(region){
31778            this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
31779         }else{
31780            this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
31781         } 
31782     },
31783     
31784     /**
31785      * Returns the toolbar for this Panel if one was configured. 
31786      * @return {Roo.Toolbar} 
31787      */
31788     getToolbar : function(){
31789         return this.toolbar;
31790     },
31791     
31792     setActiveState : function(active){
31793         this.active = active;
31794         if(!active){
31795             this.fireEvent("deactivate", this);
31796         }else{
31797             this.fireEvent("activate", this);
31798         }
31799     },
31800     /**
31801      * Updates this panel's element
31802      * @param {String} content The new content
31803      * @param {Boolean} loadScripts (optional) true to look for and process scripts
31804     */
31805     setContent : function(content, loadScripts){
31806         this.el.update(content, loadScripts);
31807     },
31808
31809     ignoreResize : function(w, h){
31810         if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
31811             return true;
31812         }else{
31813             this.lastSize = {width: w, height: h};
31814             return false;
31815         }
31816     },
31817     /**
31818      * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
31819      * @return {Roo.UpdateManager} The UpdateManager
31820      */
31821     getUpdateManager : function(){
31822         return this.el.getUpdateManager();
31823     },
31824      /**
31825      * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
31826      * @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:
31827 <pre><code>
31828 panel.load({
31829     url: "your-url.php",
31830     params: {param1: "foo", param2: "bar"}, // or a URL encoded string
31831     callback: yourFunction,
31832     scope: yourObject, //(optional scope)
31833     discardUrl: false,
31834     nocache: false,
31835     text: "Loading...",
31836     timeout: 30,
31837     scripts: false
31838 });
31839 </code></pre>
31840      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
31841      * 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.
31842      * @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}
31843      * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
31844      * @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.
31845      * @return {Roo.ContentPanel} this
31846      */
31847     load : function(){
31848         var um = this.el.getUpdateManager();
31849         um.update.apply(um, arguments);
31850         return this;
31851     },
31852
31853
31854     /**
31855      * 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.
31856      * @param {String/Function} url The URL to load the content from or a function to call to get the URL
31857      * @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)
31858      * @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)
31859      * @return {Roo.UpdateManager} The UpdateManager
31860      */
31861     setUrl : function(url, params, loadOnce){
31862         if(this.refreshDelegate){
31863             this.removeListener("activate", this.refreshDelegate);
31864         }
31865         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
31866         this.on("activate", this.refreshDelegate);
31867         return this.el.getUpdateManager();
31868     },
31869     
31870     _handleRefresh : function(url, params, loadOnce){
31871         if(!loadOnce || !this.loaded){
31872             var updater = this.el.getUpdateManager();
31873             updater.update(url, params, this._setLoaded.createDelegate(this));
31874         }
31875     },
31876     
31877     _setLoaded : function(){
31878         this.loaded = true;
31879     }, 
31880     
31881     /**
31882      * Returns this panel's id
31883      * @return {String} 
31884      */
31885     getId : function(){
31886         return this.el.id;
31887     },
31888     
31889     /** 
31890      * Returns this panel's element - used by regiosn to add.
31891      * @return {Roo.Element} 
31892      */
31893     getEl : function(){
31894         return this.wrapEl || this.el;
31895     },
31896     
31897     adjustForComponents : function(width, height)
31898     {
31899         //Roo.log('adjustForComponents ');
31900         if(this.resizeEl != this.el){
31901             width -= this.el.getFrameWidth('lr');
31902             height -= this.el.getFrameWidth('tb');
31903         }
31904         if(this.toolbar){
31905             var te = this.toolbar.getEl();
31906             height -= te.getHeight();
31907             te.setWidth(width);
31908         }
31909         if(this.footer){
31910             var te = this.footer.getEl();
31911             //Roo.log("footer:" + te.getHeight());
31912             
31913             height -= te.getHeight();
31914             te.setWidth(width);
31915         }
31916         
31917         
31918         if(this.adjustments){
31919             width += this.adjustments[0];
31920             height += this.adjustments[1];
31921         }
31922         return {"width": width, "height": height};
31923     },
31924     
31925     setSize : function(width, height){
31926         if(this.fitToFrame && !this.ignoreResize(width, height)){
31927             if(this.fitContainer && this.resizeEl != this.el){
31928                 this.el.setSize(width, height);
31929             }
31930             var size = this.adjustForComponents(width, height);
31931             this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
31932             this.fireEvent('resize', this, size.width, size.height);
31933         }
31934     },
31935     
31936     /**
31937      * Returns this panel's title
31938      * @return {String} 
31939      */
31940     getTitle : function(){
31941         return this.title;
31942     },
31943     
31944     /**
31945      * Set this panel's title
31946      * @param {String} title
31947      */
31948     setTitle : function(title){
31949         this.title = title;
31950         if(this.region){
31951             this.region.updatePanelTitle(this, title);
31952         }
31953     },
31954     
31955     /**
31956      * Returns true is this panel was configured to be closable
31957      * @return {Boolean} 
31958      */
31959     isClosable : function(){
31960         return this.closable;
31961     },
31962     
31963     beforeSlide : function(){
31964         this.el.clip();
31965         this.resizeEl.clip();
31966     },
31967     
31968     afterSlide : function(){
31969         this.el.unclip();
31970         this.resizeEl.unclip();
31971     },
31972     
31973     /**
31974      *   Force a content refresh from the URL specified in the {@link #setUrl} method.
31975      *   Will fail silently if the {@link #setUrl} method has not been called.
31976      *   This does not activate the panel, just updates its content.
31977      */
31978     refresh : function(){
31979         if(this.refreshDelegate){
31980            this.loaded = false;
31981            this.refreshDelegate();
31982         }
31983     },
31984     
31985     /**
31986      * Destroys this panel
31987      */
31988     destroy : function(){
31989         this.el.removeAllListeners();
31990         var tempEl = document.createElement("span");
31991         tempEl.appendChild(this.el.dom);
31992         tempEl.innerHTML = "";
31993         this.el.remove();
31994         this.el = null;
31995     },
31996     
31997     /**
31998      * form - if the content panel contains a form - this is a reference to it.
31999      * @type {Roo.form.Form}
32000      */
32001     form : false,
32002     /**
32003      * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
32004      *    This contains a reference to it.
32005      * @type {Roo.View}
32006      */
32007     view : false,
32008     
32009       /**
32010      * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
32011      * <pre><code>
32012
32013 layout.addxtype({
32014        xtype : 'Form',
32015        items: [ .... ]
32016    }
32017 );
32018
32019 </code></pre>
32020      * @param {Object} cfg Xtype definition of item to add.
32021      */
32022     
32023     addxtype : function(cfg) {
32024         // add form..
32025         if (cfg.xtype.match(/^Form$/)) {
32026             
32027             var el;
32028             //if (this.footer) {
32029             //    el = this.footer.container.insertSibling(false, 'before');
32030             //} else {
32031                 el = this.el.createChild();
32032             //}
32033
32034             this.form = new  Roo.form.Form(cfg);
32035             
32036             
32037             if ( this.form.allItems.length) {
32038                 this.form.render(el.dom);
32039             }
32040             return this.form;
32041         }
32042         // should only have one of theses..
32043         if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
32044             // views.. should not be just added - used named prop 'view''
32045             
32046             cfg.el = this.el.appendChild(document.createElement("div"));
32047             // factory?
32048             
32049             var ret = new Roo.factory(cfg);
32050              
32051              ret.render && ret.render(false, ''); // render blank..
32052             this.view = ret;
32053             return ret;
32054         }
32055         return false;
32056     }
32057 });
32058
32059 /**
32060  * @class Roo.GridPanel
32061  * @extends Roo.ContentPanel
32062  * @constructor
32063  * Create a new GridPanel.
32064  * @param {Roo.grid.Grid} grid The grid for this panel
32065  * @param {String/Object} config A string to set only the panel's title, or a config object
32066  */
32067 Roo.GridPanel = function(grid, config){
32068     
32069   
32070     this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
32071         {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
32072         
32073     this.wrapper.dom.appendChild(grid.getGridEl().dom);
32074     
32075     Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
32076     
32077     if(this.toolbar){
32078         this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
32079     }
32080     // xtype created footer. - not sure if will work as we normally have to render first..
32081     if (this.footer && !this.footer.el && this.footer.xtype) {
32082         
32083         this.footer.container = this.grid.getView().getFooterPanel(true);
32084         this.footer.dataSource = this.grid.dataSource;
32085         this.footer = Roo.factory(this.footer, Roo);
32086         
32087     }
32088     
32089     grid.monitorWindowResize = false; // turn off autosizing
32090     grid.autoHeight = false;
32091     grid.autoWidth = false;
32092     this.grid = grid;
32093     this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
32094 };
32095
32096 Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
32097     getId : function(){
32098         return this.grid.id;
32099     },
32100     
32101     /**
32102      * Returns the grid for this panel
32103      * @return {Roo.grid.Grid} 
32104      */
32105     getGrid : function(){
32106         return this.grid;    
32107     },
32108     
32109     setSize : function(width, height){
32110         if(!this.ignoreResize(width, height)){
32111             var grid = this.grid;
32112             var size = this.adjustForComponents(width, height);
32113             grid.getGridEl().setSize(size.width, size.height);
32114             grid.autoSize();
32115         }
32116     },
32117     
32118     beforeSlide : function(){
32119         this.grid.getView().scroller.clip();
32120     },
32121     
32122     afterSlide : function(){
32123         this.grid.getView().scroller.unclip();
32124     },
32125     
32126     destroy : function(){
32127         this.grid.destroy();
32128         delete this.grid;
32129         Roo.GridPanel.superclass.destroy.call(this); 
32130     }
32131 });
32132
32133
32134 /**
32135  * @class Roo.NestedLayoutPanel
32136  * @extends Roo.ContentPanel
32137  * @constructor
32138  * Create a new NestedLayoutPanel.
32139  * 
32140  * 
32141  * @param {Roo.BorderLayout} layout [required] The layout for this panel
32142  * @param {String/Object} config A string to set only the title or a config object
32143  */
32144 Roo.NestedLayoutPanel = function(layout, config)
32145 {
32146     // construct with only one argument..
32147     /* FIXME - implement nicer consturctors
32148     if (layout.layout) {
32149         config = layout;
32150         layout = config.layout;
32151         delete config.layout;
32152     }
32153     if (layout.xtype && !layout.getEl) {
32154         // then layout needs constructing..
32155         layout = Roo.factory(layout, Roo);
32156     }
32157     */
32158     
32159     
32160     Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
32161     
32162     layout.monitorWindowResize = false; // turn off autosizing
32163     this.layout = layout;
32164     this.layout.getEl().addClass("x-layout-nested-layout");
32165     
32166     
32167     
32168     
32169 };
32170
32171 Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
32172
32173     setSize : function(width, height){
32174         if(!this.ignoreResize(width, height)){
32175             var size = this.adjustForComponents(width, height);
32176             var el = this.layout.getEl();
32177             el.setSize(size.width, size.height);
32178             var touch = el.dom.offsetWidth;
32179             this.layout.layout();
32180             // ie requires a double layout on the first pass
32181             if(Roo.isIE && !this.initialized){
32182                 this.initialized = true;
32183                 this.layout.layout();
32184             }
32185         }
32186     },
32187     
32188     // activate all subpanels if not currently active..
32189     
32190     setActiveState : function(active){
32191         this.active = active;
32192         if(!active){
32193             this.fireEvent("deactivate", this);
32194             return;
32195         }
32196         
32197         this.fireEvent("activate", this);
32198         // not sure if this should happen before or after..
32199         if (!this.layout) {
32200             return; // should not happen..
32201         }
32202         var reg = false;
32203         for (var r in this.layout.regions) {
32204             reg = this.layout.getRegion(r);
32205             if (reg.getActivePanel()) {
32206                 //reg.showPanel(reg.getActivePanel()); // force it to activate.. 
32207                 reg.setActivePanel(reg.getActivePanel());
32208                 continue;
32209             }
32210             if (!reg.panels.length) {
32211                 continue;
32212             }
32213             reg.showPanel(reg.getPanel(0));
32214         }
32215         
32216         
32217         
32218         
32219     },
32220     
32221     /**
32222      * Returns the nested BorderLayout for this panel
32223      * @return {Roo.BorderLayout} 
32224      */
32225     getLayout : function(){
32226         return this.layout;
32227     },
32228     
32229      /**
32230      * Adds a xtype elements to the layout of the nested panel
32231      * <pre><code>
32232
32233 panel.addxtype({
32234        xtype : 'ContentPanel',
32235        region: 'west',
32236        items: [ .... ]
32237    }
32238 );
32239
32240 panel.addxtype({
32241         xtype : 'NestedLayoutPanel',
32242         region: 'west',
32243         layout: {
32244            center: { },
32245            west: { }   
32246         },
32247         items : [ ... list of content panels or nested layout panels.. ]
32248    }
32249 );
32250 </code></pre>
32251      * @param {Object} cfg Xtype definition of item to add.
32252      */
32253     addxtype : function(cfg) {
32254         return this.layout.addxtype(cfg);
32255     
32256     }
32257 });
32258
32259 Roo.ScrollPanel = function(el, config, content){
32260     config = config || {};
32261     config.fitToFrame = true;
32262     Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
32263     
32264     this.el.dom.style.overflow = "hidden";
32265     var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
32266     this.el.removeClass("x-layout-inactive-content");
32267     this.el.on("mousewheel", this.onWheel, this);
32268
32269     var up = wrap.createChild({cls: "x-scroller-up", html: "&#160;"}, this.el.dom);
32270     var down = wrap.createChild({cls: "x-scroller-down", html: "&#160;"});
32271     up.unselectable(); down.unselectable();
32272     up.on("click", this.scrollUp, this);
32273     down.on("click", this.scrollDown, this);
32274     up.addClassOnOver("x-scroller-btn-over");
32275     down.addClassOnOver("x-scroller-btn-over");
32276     up.addClassOnClick("x-scroller-btn-click");
32277     down.addClassOnClick("x-scroller-btn-click");
32278     this.adjustments = [0, -(up.getHeight() + down.getHeight())];
32279
32280     this.resizeEl = this.el;
32281     this.el = wrap; this.up = up; this.down = down;
32282 };
32283
32284 Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
32285     increment : 100,
32286     wheelIncrement : 5,
32287     scrollUp : function(){
32288         this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
32289     },
32290
32291     scrollDown : function(){
32292         this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
32293     },
32294
32295     afterScroll : function(){
32296         var el = this.resizeEl;
32297         var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
32298         this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
32299         this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
32300     },
32301
32302     setSize : function(){
32303         Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
32304         this.afterScroll();
32305     },
32306
32307     onWheel : function(e){
32308         var d = e.getWheelDelta();
32309         this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
32310         this.afterScroll();
32311         e.stopEvent();
32312     },
32313
32314     setContent : function(content, loadScripts){
32315         this.resizeEl.update(content, loadScripts);
32316     }
32317
32318 });
32319
32320
32321
32322 /**
32323  * @class Roo.TreePanel
32324  * @extends Roo.ContentPanel
32325  * Treepanel component
32326  * 
32327  * @constructor
32328  * Create a new TreePanel. - defaults to fit/scoll contents.
32329  * @param {String/Object} config A string to set only the panel's title, or a config object
32330  */
32331 Roo.TreePanel = function(config){
32332     var el = config.el;
32333     var tree = config.tree;
32334     delete config.tree; 
32335     delete config.el; // hopefull!
32336     
32337     // wrapper for IE7 strict & safari scroll issue
32338     
32339     var treeEl = el.createChild();
32340     config.resizeEl = treeEl;
32341     
32342     
32343     
32344     Roo.TreePanel.superclass.constructor.call(this, el, config);
32345  
32346  
32347     this.tree = new Roo.tree.TreePanel(treeEl , tree);
32348     //console.log(tree);
32349     this.on('activate', function()
32350     {
32351         if (this.tree.rendered) {
32352             return;
32353         }
32354         //console.log('render tree');
32355         this.tree.render();
32356     });
32357     // this should not be needed.. - it's actually the 'el' that resizes?
32358     // actuall it breaks the containerScroll - dragging nodes auto scroll at top
32359     
32360     //this.on('resize',  function (cp, w, h) {
32361     //        this.tree.innerCt.setWidth(w);
32362     //        this.tree.innerCt.setHeight(h);
32363     //        //this.tree.innerCt.setStyle('overflow-y', 'auto');
32364     //});
32365
32366         
32367     
32368 };
32369
32370 Roo.extend(Roo.TreePanel, Roo.ContentPanel, {   
32371     fitToFrame : true,
32372     autoScroll : true,
32373     /*
32374      * @cfg {Roo.tree.TreePanel} tree [required] The tree TreePanel, with config etc.
32375      */
32376     tree : false
32377
32378 });
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390 /*
32391  * Based on:
32392  * Ext JS Library 1.1.1
32393  * Copyright(c) 2006-2007, Ext JS, LLC.
32394  *
32395  * Originally Released Under LGPL - original licence link has changed is not relivant.
32396  *
32397  * Fork - LGPL
32398  * <script type="text/javascript">
32399  */
32400  
32401
32402 /**
32403  * @class Roo.ReaderLayout
32404  * @extends Roo.BorderLayout
32405  * This is a pre-built layout that represents a classic, 5-pane application.  It consists of a header, a primary
32406  * center region containing two nested regions (a top one for a list view and one for item preview below),
32407  * and regions on either side that can be used for navigation, application commands, informational displays, etc.
32408  * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
32409  * expedites the setup of the overall layout and regions for this common application style.
32410  * Example:
32411  <pre><code>
32412 var reader = new Roo.ReaderLayout();
32413 var CP = Roo.ContentPanel;  // shortcut for adding
32414
32415 reader.beginUpdate();
32416 reader.add("north", new CP("north", "North"));
32417 reader.add("west", new CP("west", {title: "West"}));
32418 reader.add("east", new CP("east", {title: "East"}));
32419
32420 reader.regions.listView.add(new CP("listView", "List"));
32421 reader.regions.preview.add(new CP("preview", "Preview"));
32422 reader.endUpdate();
32423 </code></pre>
32424 * @constructor
32425 * Create a new ReaderLayout
32426 * @param {Object} config Configuration options
32427 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
32428 * document.body if omitted)
32429 */
32430 Roo.ReaderLayout = function(config, renderTo){
32431     var c = config || {size:{}};
32432     Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
32433         north: c.north !== false ? Roo.apply({
32434             split:false,
32435             initialSize: 32,
32436             titlebar: false
32437         }, c.north) : false,
32438         west: c.west !== false ? Roo.apply({
32439             split:true,
32440             initialSize: 200,
32441             minSize: 175,
32442             maxSize: 400,
32443             titlebar: true,
32444             collapsible: true,
32445             animate: true,
32446             margins:{left:5,right:0,bottom:5,top:5},
32447             cmargins:{left:5,right:5,bottom:5,top:5}
32448         }, c.west) : false,
32449         east: c.east !== false ? Roo.apply({
32450             split:true,
32451             initialSize: 200,
32452             minSize: 175,
32453             maxSize: 400,
32454             titlebar: true,
32455             collapsible: true,
32456             animate: true,
32457             margins:{left:0,right:5,bottom:5,top:5},
32458             cmargins:{left:5,right:5,bottom:5,top:5}
32459         }, c.east) : false,
32460         center: Roo.apply({
32461             tabPosition: 'top',
32462             autoScroll:false,
32463             closeOnTab: true,
32464             titlebar:false,
32465             margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
32466         }, c.center)
32467     });
32468
32469     this.el.addClass('x-reader');
32470
32471     this.beginUpdate();
32472
32473     var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
32474         south: c.preview !== false ? Roo.apply({
32475             split:true,
32476             initialSize: 200,
32477             minSize: 100,
32478             autoScroll:true,
32479             collapsible:true,
32480             titlebar: true,
32481             cmargins:{top:5,left:0, right:0, bottom:0}
32482         }, c.preview) : false,
32483         center: Roo.apply({
32484             autoScroll:false,
32485             titlebar:false,
32486             minHeight:200
32487         }, c.listView)
32488     });
32489     this.add('center', new Roo.NestedLayoutPanel(inner,
32490             Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
32491
32492     this.endUpdate();
32493
32494     this.regions.preview = inner.getRegion('south');
32495     this.regions.listView = inner.getRegion('center');
32496 };
32497
32498 Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
32499  * Based on:
32500  * Ext JS Library 1.1.1
32501  * Copyright(c) 2006-2007, Ext JS, LLC.
32502  *
32503  * Originally Released Under LGPL - original licence link has changed is not relivant.
32504  *
32505  * Fork - LGPL
32506  * <script type="text/javascript">
32507  */
32508  
32509 /**
32510  * @class Roo.grid.Grid
32511  * @extends Roo.util.Observable
32512  * This class represents the primary interface of a component based grid control.
32513  * <br><br>Usage:<pre><code>
32514  var grid = new Roo.grid.Grid("my-container-id", {
32515      ds: myDataStore,
32516      cm: myColModel,
32517      selModel: mySelectionModel,
32518      autoSizeColumns: true,
32519      monitorWindowResize: false,
32520      trackMouseOver: true
32521  });
32522  // set any options
32523  grid.render();
32524  * </code></pre>
32525  * <b>Common Problems:</b><br/>
32526  * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
32527  * element will correct this<br/>
32528  * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
32529  * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
32530  * are unpredictable.<br/>
32531  * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
32532  * grid to calculate dimensions/offsets.<br/>
32533   * @constructor
32534  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
32535  * The container MUST have some type of size defined for the grid to fill. The container will be
32536  * automatically set to position relative if it isn't already.
32537  * @param {Object} config A config object that sets properties on this grid.
32538  */
32539 Roo.grid.Grid = function(container, config){
32540         // initialize the container
32541         this.container = Roo.get(container);
32542         this.container.update("");
32543         this.container.setStyle("overflow", "hidden");
32544     this.container.addClass('x-grid-container');
32545
32546     this.id = this.container.id;
32547
32548     Roo.apply(this, config);
32549     // check and correct shorthanded configs
32550     if(this.ds){
32551         this.dataSource = this.ds;
32552         delete this.ds;
32553     }
32554     if(this.cm){
32555         this.colModel = this.cm;
32556         delete this.cm;
32557     }
32558     if(this.sm){
32559         this.selModel = this.sm;
32560         delete this.sm;
32561     }
32562
32563     if (this.selModel) {
32564         this.selModel = Roo.factory(this.selModel, Roo.grid);
32565         this.sm = this.selModel;
32566         this.sm.xmodule = this.xmodule || false;
32567     }
32568     if (typeof(this.colModel.config) == 'undefined') {
32569         this.colModel = new Roo.grid.ColumnModel(this.colModel);
32570         this.cm = this.colModel;
32571         this.cm.xmodule = this.xmodule || false;
32572     }
32573     if (this.dataSource) {
32574         this.dataSource= Roo.factory(this.dataSource, Roo.data);
32575         this.ds = this.dataSource;
32576         this.ds.xmodule = this.xmodule || false;
32577          
32578     }
32579     
32580     
32581     
32582     if(this.width){
32583         this.container.setWidth(this.width);
32584     }
32585
32586     if(this.height){
32587         this.container.setHeight(this.height);
32588     }
32589     /** @private */
32590         this.addEvents({
32591         // raw events
32592         /**
32593          * @event click
32594          * The raw click event for the entire grid.
32595          * @param {Roo.EventObject} e
32596          */
32597         "click" : true,
32598         /**
32599          * @event dblclick
32600          * The raw dblclick event for the entire grid.
32601          * @param {Roo.EventObject} e
32602          */
32603         "dblclick" : true,
32604         /**
32605          * @event contextmenu
32606          * The raw contextmenu event for the entire grid.
32607          * @param {Roo.EventObject} e
32608          */
32609         "contextmenu" : true,
32610         /**
32611          * @event mousedown
32612          * The raw mousedown event for the entire grid.
32613          * @param {Roo.EventObject} e
32614          */
32615         "mousedown" : true,
32616         /**
32617          * @event mouseup
32618          * The raw mouseup event for the entire grid.
32619          * @param {Roo.EventObject} e
32620          */
32621         "mouseup" : true,
32622         /**
32623          * @event mouseover
32624          * The raw mouseover event for the entire grid.
32625          * @param {Roo.EventObject} e
32626          */
32627         "mouseover" : true,
32628         /**
32629          * @event mouseout
32630          * The raw mouseout event for the entire grid.
32631          * @param {Roo.EventObject} e
32632          */
32633         "mouseout" : true,
32634         /**
32635          * @event keypress
32636          * The raw keypress event for the entire grid.
32637          * @param {Roo.EventObject} e
32638          */
32639         "keypress" : true,
32640         /**
32641          * @event keydown
32642          * The raw keydown event for the entire grid.
32643          * @param {Roo.EventObject} e
32644          */
32645         "keydown" : true,
32646
32647         // custom events
32648
32649         /**
32650          * @event cellclick
32651          * Fires when a cell is clicked
32652          * @param {Grid} this
32653          * @param {Number} rowIndex
32654          * @param {Number} columnIndex
32655          * @param {Roo.EventObject} e
32656          */
32657         "cellclick" : true,
32658         /**
32659          * @event celldblclick
32660          * Fires when a cell is double clicked
32661          * @param {Grid} this
32662          * @param {Number} rowIndex
32663          * @param {Number} columnIndex
32664          * @param {Roo.EventObject} e
32665          */
32666         "celldblclick" : true,
32667         /**
32668          * @event rowclick
32669          * Fires when a row is clicked
32670          * @param {Grid} this
32671          * @param {Number} rowIndex
32672          * @param {Roo.EventObject} e
32673          */
32674         "rowclick" : true,
32675         /**
32676          * @event rowdblclick
32677          * Fires when a row is double clicked
32678          * @param {Grid} this
32679          * @param {Number} rowIndex
32680          * @param {Roo.EventObject} e
32681          */
32682         "rowdblclick" : true,
32683         /**
32684          * @event headerclick
32685          * Fires when a header is clicked
32686          * @param {Grid} this
32687          * @param {Number} columnIndex
32688          * @param {Roo.EventObject} e
32689          */
32690         "headerclick" : true,
32691         /**
32692          * @event headerdblclick
32693          * Fires when a header cell is double clicked
32694          * @param {Grid} this
32695          * @param {Number} columnIndex
32696          * @param {Roo.EventObject} e
32697          */
32698         "headerdblclick" : true,
32699         /**
32700          * @event rowcontextmenu
32701          * Fires when a row is right clicked
32702          * @param {Grid} this
32703          * @param {Number} rowIndex
32704          * @param {Roo.EventObject} e
32705          */
32706         "rowcontextmenu" : true,
32707         /**
32708          * @event cellcontextmenu
32709          * Fires when a cell is right clicked
32710          * @param {Grid} this
32711          * @param {Number} rowIndex
32712          * @param {Number} cellIndex
32713          * @param {Roo.EventObject} e
32714          */
32715          "cellcontextmenu" : true,
32716         /**
32717          * @event headercontextmenu
32718          * Fires when a header is right clicked
32719          * @param {Grid} this
32720          * @param {Number} columnIndex
32721          * @param {Roo.EventObject} e
32722          */
32723         "headercontextmenu" : true,
32724         /**
32725          * @event bodyscroll
32726          * Fires when the body element is scrolled
32727          * @param {Number} scrollLeft
32728          * @param {Number} scrollTop
32729          */
32730         "bodyscroll" : true,
32731         /**
32732          * @event columnresize
32733          * Fires when the user resizes a column
32734          * @param {Number} columnIndex
32735          * @param {Number} newSize
32736          */
32737         "columnresize" : true,
32738         /**
32739          * @event columnmove
32740          * Fires when the user moves a column
32741          * @param {Number} oldIndex
32742          * @param {Number} newIndex
32743          */
32744         "columnmove" : true,
32745         /**
32746          * @event startdrag
32747          * Fires when row(s) start being dragged
32748          * @param {Grid} this
32749          * @param {Roo.GridDD} dd The drag drop object
32750          * @param {event} e The raw browser event
32751          */
32752         "startdrag" : true,
32753         /**
32754          * @event enddrag
32755          * Fires when a drag operation is complete
32756          * @param {Grid} this
32757          * @param {Roo.GridDD} dd The drag drop object
32758          * @param {event} e The raw browser event
32759          */
32760         "enddrag" : true,
32761         /**
32762          * @event dragdrop
32763          * Fires when dragged row(s) are dropped on a valid DD target
32764          * @param {Grid} this
32765          * @param {Roo.GridDD} dd The drag drop object
32766          * @param {String} targetId The target drag drop object
32767          * @param {event} e The raw browser event
32768          */
32769         "dragdrop" : true,
32770         /**
32771          * @event dragover
32772          * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
32773          * @param {Grid} this
32774          * @param {Roo.GridDD} dd The drag drop object
32775          * @param {String} targetId The target drag drop object
32776          * @param {event} e The raw browser event
32777          */
32778         "dragover" : true,
32779         /**
32780          * @event dragenter
32781          *  Fires when the dragged row(s) first cross another DD target while being dragged
32782          * @param {Grid} this
32783          * @param {Roo.GridDD} dd The drag drop object
32784          * @param {String} targetId The target drag drop object
32785          * @param {event} e The raw browser event
32786          */
32787         "dragenter" : true,
32788         /**
32789          * @event dragout
32790          * Fires when the dragged row(s) leave another DD target while being dragged
32791          * @param {Grid} this
32792          * @param {Roo.GridDD} dd The drag drop object
32793          * @param {String} targetId The target drag drop object
32794          * @param {event} e The raw browser event
32795          */
32796         "dragout" : true,
32797         /**
32798          * @event rowclass
32799          * Fires when a row is rendered, so you can change add a style to it.
32800          * @param {GridView} gridview   The grid view
32801          * @param {Object} rowcfg   contains record  rowIndex and rowClass - set rowClass to add a style.
32802          */
32803         'rowclass' : true,
32804
32805         /**
32806          * @event render
32807          * Fires when the grid is rendered
32808          * @param {Grid} grid
32809          */
32810         'render' : true
32811     });
32812
32813     Roo.grid.Grid.superclass.constructor.call(this);
32814 };
32815 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
32816     
32817     /**
32818          * @cfg {Roo.grid.AbstractSelectionModel} sm The selection Model (default = Roo.grid.RowSelectionModel)
32819          */
32820         /**
32821          * @cfg {Roo.grid.GridView} view  The view that renders the grid (default = Roo.grid.GridView)
32822          */
32823         /**
32824          * @cfg {Roo.grid.ColumnModel} cm[] The columns of the grid
32825          */
32826         /**
32827          * @cfg {Roo.grid.Store} ds The data store for the grid
32828          */
32829         /**
32830          * @cfg {Roo.Toolbar} toolbar a toolbar for buttons etc.
32831          */
32832         /**
32833      * @cfg {String} ddGroup - drag drop group.
32834      */
32835       /**
32836      * @cfg {String} dragGroup - drag group (?? not sure if needed.)
32837      */
32838
32839     /**
32840      * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
32841      */
32842     minColumnWidth : 25,
32843
32844     /**
32845      * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
32846      * <b>on initial render.</b> It is more efficient to explicitly size the columns
32847      * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option.  Default is false.
32848      */
32849     autoSizeColumns : false,
32850
32851     /**
32852      * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
32853      */
32854     autoSizeHeaders : true,
32855
32856     /**
32857      * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
32858      */
32859     monitorWindowResize : true,
32860
32861     /**
32862      * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
32863      * rows measured to get a columns size. Default is 0 (all rows).
32864      */
32865     maxRowsToMeasure : 0,
32866
32867     /**
32868      * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
32869      */
32870     trackMouseOver : true,
32871
32872     /**
32873     * @cfg {Boolean} enableDrag  True to enable drag of rows. Default is false. (double check if this is needed?)
32874     */
32875       /**
32876     * @cfg {Boolean} enableDrop  True to enable drop of elements. Default is false. (double check if this is needed?)
32877     */
32878     
32879     /**
32880     * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
32881     */
32882     enableDragDrop : false,
32883     
32884     /**
32885     * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
32886     */
32887     enableColumnMove : true,
32888     
32889     /**
32890     * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
32891     */
32892     enableColumnHide : true,
32893     
32894     /**
32895     * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
32896     */
32897     enableRowHeightSync : false,
32898     
32899     /**
32900     * @cfg {Boolean} stripeRows True to stripe the rows.  Default is true.
32901     */
32902     stripeRows : true,
32903     
32904     /**
32905     * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
32906     */
32907     autoHeight : false,
32908
32909     /**
32910      * @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.
32911      */
32912     autoExpandColumn : false,
32913
32914     /**
32915     * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
32916     * Default is 50.
32917     */
32918     autoExpandMin : 50,
32919
32920     /**
32921     * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
32922     */
32923     autoExpandMax : 1000,
32924
32925     /**
32926     * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
32927     */
32928     view : null,
32929
32930     /**
32931     * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
32932     */
32933     loadMask : false,
32934     /**
32935     * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
32936     */
32937     dropTarget: false,
32938     
32939    
32940     
32941     // private
32942     rendered : false,
32943
32944     /**
32945     * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
32946     * of a fixed width. Default is false.
32947     */
32948     /**
32949     * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
32950     */
32951     
32952     
32953     /**
32954     * @cfg {String} ddText Configures the text is the drag proxy (defaults to "%0 selected row(s)").
32955     * %0 is replaced with the number of selected rows.
32956     */
32957     ddText : "{0} selected row{1}",
32958     
32959     
32960     /**
32961      * Called once after all setup has been completed and the grid is ready to be rendered.
32962      * @return {Roo.grid.Grid} this
32963      */
32964     render : function()
32965     {
32966         var c = this.container;
32967         // try to detect autoHeight/width mode
32968         if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
32969             this.autoHeight = true;
32970         }
32971         var view = this.getView();
32972         view.init(this);
32973
32974         c.on("click", this.onClick, this);
32975         c.on("dblclick", this.onDblClick, this);
32976         c.on("contextmenu", this.onContextMenu, this);
32977         c.on("keydown", this.onKeyDown, this);
32978         if (Roo.isTouch) {
32979             c.on("touchstart", this.onTouchStart, this);
32980         }
32981
32982         this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
32983
32984         this.getSelectionModel().init(this);
32985
32986         view.render();
32987
32988         if(this.loadMask){
32989             this.loadMask = new Roo.LoadMask(this.container,
32990                     Roo.apply({store:this.dataSource}, this.loadMask));
32991         }
32992         
32993         
32994         if (this.toolbar && this.toolbar.xtype) {
32995             this.toolbar.container = this.getView().getHeaderPanel(true);
32996             this.toolbar = new Roo.Toolbar(this.toolbar);
32997         }
32998         if (this.footer && this.footer.xtype) {
32999             this.footer.dataSource = this.getDataSource();
33000             this.footer.container = this.getView().getFooterPanel(true);
33001             this.footer = Roo.factory(this.footer, Roo);
33002         }
33003         if (this.dropTarget && this.dropTarget.xtype) {
33004             delete this.dropTarget.xtype;
33005             this.dropTarget =  new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
33006         }
33007         
33008         
33009         this.rendered = true;
33010         this.fireEvent('render', this);
33011         return this;
33012     },
33013
33014     /**
33015      * Reconfigures the grid to use a different Store and Column Model.
33016      * The View will be bound to the new objects and refreshed.
33017      * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
33018      * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
33019      */
33020     reconfigure : function(dataSource, colModel){
33021         if(this.loadMask){
33022             this.loadMask.destroy();
33023             this.loadMask = new Roo.LoadMask(this.container,
33024                     Roo.apply({store:dataSource}, this.loadMask));
33025         }
33026         this.view.bind(dataSource, colModel);
33027         this.dataSource = dataSource;
33028         this.colModel = colModel;
33029         this.view.refresh(true);
33030     },
33031     /**
33032      * addColumns
33033      * Add's a column, default at the end..
33034      
33035      * @param {int} position to add (default end)
33036      * @param {Array} of objects of column configuration see {@link Roo.grid.ColumnModel} 
33037      */
33038     addColumns : function(pos, ar)
33039     {
33040         
33041         for (var i =0;i< ar.length;i++) {
33042             var cfg = ar[i];
33043             cfg.id = typeof(cfg.id) == 'undefined' ? Roo.id() : cfg.id; // don't normally use this..
33044             this.cm.lookup[cfg.id] = cfg;
33045         }
33046         
33047         
33048         if (typeof(pos) == 'undefined' || pos >= this.cm.config.length) {
33049             pos = this.cm.config.length; //this.cm.config.push(cfg);
33050         } 
33051         pos = Math.max(0,pos);
33052         ar.unshift(0);
33053         ar.unshift(pos);
33054         this.cm.config.splice.apply(this.cm.config, ar);
33055         
33056         
33057         
33058         this.view.generateRules(this.cm);
33059         this.view.refresh(true);
33060         
33061     },
33062     
33063     
33064     
33065     
33066     // private
33067     onKeyDown : function(e){
33068         this.fireEvent("keydown", e);
33069     },
33070
33071     /**
33072      * Destroy this grid.
33073      * @param {Boolean} removeEl True to remove the element
33074      */
33075     destroy : function(removeEl, keepListeners){
33076         if(this.loadMask){
33077             this.loadMask.destroy();
33078         }
33079         var c = this.container;
33080         c.removeAllListeners();
33081         this.view.destroy();
33082         this.colModel.purgeListeners();
33083         if(!keepListeners){
33084             this.purgeListeners();
33085         }
33086         c.update("");
33087         if(removeEl === true){
33088             c.remove();
33089         }
33090     },
33091
33092     // private
33093     processEvent : function(name, e){
33094         // does this fire select???
33095         //Roo.log('grid:processEvent '  + name);
33096         
33097         if (name != 'touchstart' ) {
33098             this.fireEvent(name, e);    
33099         }
33100         
33101         var t = e.getTarget();
33102         var v = this.view;
33103         var header = v.findHeaderIndex(t);
33104         if(header !== false){
33105             var ename = name == 'touchstart' ? 'click' : name;
33106              
33107             this.fireEvent("header" + ename, this, header, e);
33108         }else{
33109             var row = v.findRowIndex(t);
33110             var cell = v.findCellIndex(t);
33111             if (name == 'touchstart') {
33112                 // first touch is always a click.
33113                 // hopefull this happens after selection is updated.?
33114                 name = false;
33115                 
33116                 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
33117                     var cs = this.selModel.getSelectedCell();
33118                     if (row == cs[0] && cell == cs[1]){
33119                         name = 'dblclick';
33120                     }
33121                 }
33122                 if (typeof(this.selModel.getSelections) != 'undefined') {
33123                     var cs = this.selModel.getSelections();
33124                     var ds = this.dataSource;
33125                     if (cs.length == 1 && ds.getAt(row) == cs[0]){
33126                         name = 'dblclick';
33127                     }
33128                 }
33129                 if (!name) {
33130                     return;
33131                 }
33132             }
33133             
33134             
33135             if(row !== false){
33136                 this.fireEvent("row" + name, this, row, e);
33137                 if(cell !== false){
33138                     this.fireEvent("cell" + name, this, row, cell, e);
33139                 }
33140             }
33141         }
33142     },
33143
33144     // private
33145     onClick : function(e){
33146         this.processEvent("click", e);
33147     },
33148    // private
33149     onTouchStart : function(e){
33150         this.processEvent("touchstart", e);
33151     },
33152
33153     // private
33154     onContextMenu : function(e, t){
33155         this.processEvent("contextmenu", e);
33156     },
33157
33158     // private
33159     onDblClick : function(e){
33160         this.processEvent("dblclick", e);
33161     },
33162
33163     // private
33164     walkCells : function(row, col, step, fn, scope){
33165         var cm = this.colModel, clen = cm.getColumnCount();
33166         var ds = this.dataSource, rlen = ds.getCount(), first = true;
33167         if(step < 0){
33168             if(col < 0){
33169                 row--;
33170                 first = false;
33171             }
33172             while(row >= 0){
33173                 if(!first){
33174                     col = clen-1;
33175                 }
33176                 first = false;
33177                 while(col >= 0){
33178                     if(fn.call(scope || this, row, col, cm) === true){
33179                         return [row, col];
33180                     }
33181                     col--;
33182                 }
33183                 row--;
33184             }
33185         } else {
33186             if(col >= clen){
33187                 row++;
33188                 first = false;
33189             }
33190             while(row < rlen){
33191                 if(!first){
33192                     col = 0;
33193                 }
33194                 first = false;
33195                 while(col < clen){
33196                     if(fn.call(scope || this, row, col, cm) === true){
33197                         return [row, col];
33198                     }
33199                     col++;
33200                 }
33201                 row++;
33202             }
33203         }
33204         return null;
33205     },
33206
33207     // private
33208     getSelections : function(){
33209         return this.selModel.getSelections();
33210     },
33211
33212     /**
33213      * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
33214      * but if manual update is required this method will initiate it.
33215      */
33216     autoSize : function(){
33217         if(this.rendered){
33218             this.view.layout();
33219             if(this.view.adjustForScroll){
33220                 this.view.adjustForScroll();
33221             }
33222         }
33223     },
33224
33225     /**
33226      * Returns the grid's underlying element.
33227      * @return {Element} The element
33228      */
33229     getGridEl : function(){
33230         return this.container;
33231     },
33232
33233     // private for compatibility, overridden by editor grid
33234     stopEditing : function(){},
33235
33236     /**
33237      * Returns the grid's SelectionModel.
33238      * @return {SelectionModel}
33239      */
33240     getSelectionModel : function(){
33241         if(!this.selModel){
33242             this.selModel = new Roo.grid.RowSelectionModel();
33243         }
33244         return this.selModel;
33245     },
33246
33247     /**
33248      * Returns the grid's DataSource.
33249      * @return {DataSource}
33250      */
33251     getDataSource : function(){
33252         return this.dataSource;
33253     },
33254
33255     /**
33256      * Returns the grid's ColumnModel.
33257      * @return {ColumnModel}
33258      */
33259     getColumnModel : function(){
33260         return this.colModel;
33261     },
33262
33263     /**
33264      * Returns the grid's GridView object.
33265      * @return {GridView}
33266      */
33267     getView : function(){
33268         if(!this.view){
33269             this.view = new Roo.grid.GridView(this.viewConfig);
33270             this.relayEvents(this.view, [
33271                 "beforerowremoved", "beforerowsinserted",
33272                 "beforerefresh", "rowremoved",
33273                 "rowsinserted", "rowupdated" ,"refresh"
33274             ]);
33275         }
33276         return this.view;
33277     },
33278     /**
33279      * Called to get grid's drag proxy text, by default returns this.ddText.
33280      * Override this to put something different in the dragged text.
33281      * @return {String}
33282      */
33283     getDragDropText : function(){
33284         var count = this.selModel.getCount();
33285         return String.format(this.ddText, count, count == 1 ? '' : 's');
33286     }
33287 });
33288 /*
33289  * Based on:
33290  * Ext JS Library 1.1.1
33291  * Copyright(c) 2006-2007, Ext JS, LLC.
33292  *
33293  * Originally Released Under LGPL - original licence link has changed is not relivant.
33294  *
33295  * Fork - LGPL
33296  * <script type="text/javascript">
33297  */
33298  /**
33299  * @class Roo.grid.AbstractGridView
33300  * @extends Roo.util.Observable
33301  * @abstract
33302  * Abstract base class for grid Views
33303  * @constructor
33304  */
33305 Roo.grid.AbstractGridView = function(){
33306         this.grid = null;
33307         
33308         this.events = {
33309             "beforerowremoved" : true,
33310             "beforerowsinserted" : true,
33311             "beforerefresh" : true,
33312             "rowremoved" : true,
33313             "rowsinserted" : true,
33314             "rowupdated" : true,
33315             "refresh" : true
33316         };
33317     Roo.grid.AbstractGridView.superclass.constructor.call(this);
33318 };
33319
33320 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
33321     rowClass : "x-grid-row",
33322     cellClass : "x-grid-cell",
33323     tdClass : "x-grid-td",
33324     hdClass : "x-grid-hd",
33325     splitClass : "x-grid-hd-split",
33326     
33327     init: function(grid){
33328         this.grid = grid;
33329                 var cid = this.grid.getGridEl().id;
33330         this.colSelector = "#" + cid + " ." + this.cellClass + "-";
33331         this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
33332         this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
33333         this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
33334         },
33335         
33336     getColumnRenderers : function(){
33337         var renderers = [];
33338         var cm = this.grid.colModel;
33339         var colCount = cm.getColumnCount();
33340         for(var i = 0; i < colCount; i++){
33341             renderers[i] = cm.getRenderer(i);
33342         }
33343         return renderers;
33344     },
33345     
33346     getColumnIds : function(){
33347         var ids = [];
33348         var cm = this.grid.colModel;
33349         var colCount = cm.getColumnCount();
33350         for(var i = 0; i < colCount; i++){
33351             ids[i] = cm.getColumnId(i);
33352         }
33353         return ids;
33354     },
33355     
33356     getDataIndexes : function(){
33357         if(!this.indexMap){
33358             this.indexMap = this.buildIndexMap();
33359         }
33360         return this.indexMap.colToData;
33361     },
33362     
33363     getColumnIndexByDataIndex : function(dataIndex){
33364         if(!this.indexMap){
33365             this.indexMap = this.buildIndexMap();
33366         }
33367         return this.indexMap.dataToCol[dataIndex];
33368     },
33369     
33370     /**
33371      * Set a css style for a column dynamically. 
33372      * @param {Number} colIndex The index of the column
33373      * @param {String} name The css property name
33374      * @param {String} value The css value
33375      */
33376     setCSSStyle : function(colIndex, name, value){
33377         var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
33378         Roo.util.CSS.updateRule(selector, name, value);
33379     },
33380     
33381     generateRules : function(cm){
33382         var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
33383         Roo.util.CSS.removeStyleSheet(rulesId);
33384         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
33385             var cid = cm.getColumnId(i);
33386             ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
33387                          this.tdSelector, cid, " {\n}\n",
33388                          this.hdSelector, cid, " {\n}\n",
33389                          this.splitSelector, cid, " {\n}\n");
33390         }
33391         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
33392     }
33393 });/*
33394  * Based on:
33395  * Ext JS Library 1.1.1
33396  * Copyright(c) 2006-2007, Ext JS, LLC.
33397  *
33398  * Originally Released Under LGPL - original licence link has changed is not relivant.
33399  *
33400  * Fork - LGPL
33401  * <script type="text/javascript">
33402  */
33403
33404 // private
33405 // This is a support class used internally by the Grid components
33406 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
33407     this.grid = grid;
33408     this.view = grid.getView();
33409     this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
33410     Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
33411     if(hd2){
33412         this.setHandleElId(Roo.id(hd));
33413         this.setOuterHandleElId(Roo.id(hd2));
33414     }
33415     this.scroll = false;
33416 };
33417 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
33418     maxDragWidth: 120,
33419     getDragData : function(e){
33420         var t = Roo.lib.Event.getTarget(e);
33421         var h = this.view.findHeaderCell(t);
33422         if(h){
33423             return {ddel: h.firstChild, header:h};
33424         }
33425         return false;
33426     },
33427
33428     onInitDrag : function(e){
33429         this.view.headersDisabled = true;
33430         var clone = this.dragData.ddel.cloneNode(true);
33431         clone.id = Roo.id();
33432         clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
33433         this.proxy.update(clone);
33434         return true;
33435     },
33436
33437     afterValidDrop : function(){
33438         var v = this.view;
33439         setTimeout(function(){
33440             v.headersDisabled = false;
33441         }, 50);
33442     },
33443
33444     afterInvalidDrop : function(){
33445         var v = this.view;
33446         setTimeout(function(){
33447             v.headersDisabled = false;
33448         }, 50);
33449     }
33450 });
33451 /*
33452  * Based on:
33453  * Ext JS Library 1.1.1
33454  * Copyright(c) 2006-2007, Ext JS, LLC.
33455  *
33456  * Originally Released Under LGPL - original licence link has changed is not relivant.
33457  *
33458  * Fork - LGPL
33459  * <script type="text/javascript">
33460  */
33461 // private
33462 // This is a support class used internally by the Grid components
33463 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
33464     this.grid = grid;
33465     this.view = grid.getView();
33466     // split the proxies so they don't interfere with mouse events
33467     this.proxyTop = Roo.DomHelper.append(document.body, {
33468         cls:"col-move-top", html:"&#160;"
33469     }, true);
33470     this.proxyBottom = Roo.DomHelper.append(document.body, {
33471         cls:"col-move-bottom", html:"&#160;"
33472     }, true);
33473     this.proxyTop.hide = this.proxyBottom.hide = function(){
33474         this.setLeftTop(-100,-100);
33475         this.setStyle("visibility", "hidden");
33476     };
33477     this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
33478     // temporarily disabled
33479     //Roo.dd.ScrollManager.register(this.view.scroller.dom);
33480     Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
33481 };
33482 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
33483     proxyOffsets : [-4, -9],
33484     fly: Roo.Element.fly,
33485
33486     getTargetFromEvent : function(e){
33487         var t = Roo.lib.Event.getTarget(e);
33488         var cindex = this.view.findCellIndex(t);
33489         if(cindex !== false){
33490             return this.view.getHeaderCell(cindex);
33491         }
33492         return null;
33493     },
33494
33495     nextVisible : function(h){
33496         var v = this.view, cm = this.grid.colModel;
33497         h = h.nextSibling;
33498         while(h){
33499             if(!cm.isHidden(v.getCellIndex(h))){
33500                 return h;
33501             }
33502             h = h.nextSibling;
33503         }
33504         return null;
33505     },
33506
33507     prevVisible : function(h){
33508         var v = this.view, cm = this.grid.colModel;
33509         h = h.prevSibling;
33510         while(h){
33511             if(!cm.isHidden(v.getCellIndex(h))){
33512                 return h;
33513             }
33514             h = h.prevSibling;
33515         }
33516         return null;
33517     },
33518
33519     positionIndicator : function(h, n, e){
33520         var x = Roo.lib.Event.getPageX(e);
33521         var r = Roo.lib.Dom.getRegion(n.firstChild);
33522         var px, pt, py = r.top + this.proxyOffsets[1];
33523         if((r.right - x) <= (r.right-r.left)/2){
33524             px = r.right+this.view.borderWidth;
33525             pt = "after";
33526         }else{
33527             px = r.left;
33528             pt = "before";
33529         }
33530         var oldIndex = this.view.getCellIndex(h);
33531         var newIndex = this.view.getCellIndex(n);
33532
33533         if(this.grid.colModel.isFixed(newIndex)){
33534             return false;
33535         }
33536
33537         var locked = this.grid.colModel.isLocked(newIndex);
33538
33539         if(pt == "after"){
33540             newIndex++;
33541         }
33542         if(oldIndex < newIndex){
33543             newIndex--;
33544         }
33545         if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
33546             return false;
33547         }
33548         px +=  this.proxyOffsets[0];
33549         this.proxyTop.setLeftTop(px, py);
33550         this.proxyTop.show();
33551         if(!this.bottomOffset){
33552             this.bottomOffset = this.view.mainHd.getHeight();
33553         }
33554         this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
33555         this.proxyBottom.show();
33556         return pt;
33557     },
33558
33559     onNodeEnter : function(n, dd, e, data){
33560         if(data.header != n){
33561             this.positionIndicator(data.header, n, e);
33562         }
33563     },
33564
33565     onNodeOver : function(n, dd, e, data){
33566         var result = false;
33567         if(data.header != n){
33568             result = this.positionIndicator(data.header, n, e);
33569         }
33570         if(!result){
33571             this.proxyTop.hide();
33572             this.proxyBottom.hide();
33573         }
33574         return result ? this.dropAllowed : this.dropNotAllowed;
33575     },
33576
33577     onNodeOut : function(n, dd, e, data){
33578         this.proxyTop.hide();
33579         this.proxyBottom.hide();
33580     },
33581
33582     onNodeDrop : function(n, dd, e, data){
33583         var h = data.header;
33584         if(h != n){
33585             var cm = this.grid.colModel;
33586             var x = Roo.lib.Event.getPageX(e);
33587             var r = Roo.lib.Dom.getRegion(n.firstChild);
33588             var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
33589             var oldIndex = this.view.getCellIndex(h);
33590             var newIndex = this.view.getCellIndex(n);
33591             var locked = cm.isLocked(newIndex);
33592             if(pt == "after"){
33593                 newIndex++;
33594             }
33595             if(oldIndex < newIndex){
33596                 newIndex--;
33597             }
33598             if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
33599                 return false;
33600             }
33601             cm.setLocked(oldIndex, locked, true);
33602             cm.moveColumn(oldIndex, newIndex);
33603             this.grid.fireEvent("columnmove", oldIndex, newIndex);
33604             return true;
33605         }
33606         return false;
33607     }
33608 });
33609 /*
33610  * Based on:
33611  * Ext JS Library 1.1.1
33612  * Copyright(c) 2006-2007, Ext JS, LLC.
33613  *
33614  * Originally Released Under LGPL - original licence link has changed is not relivant.
33615  *
33616  * Fork - LGPL
33617  * <script type="text/javascript">
33618  */
33619   
33620 /**
33621  * @class Roo.grid.GridView
33622  * @extends Roo.util.Observable
33623  *
33624  * @constructor
33625  * @param {Object} config
33626  */
33627 Roo.grid.GridView = function(config){
33628     Roo.grid.GridView.superclass.constructor.call(this);
33629     this.el = null;
33630
33631     Roo.apply(this, config);
33632 };
33633
33634 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
33635
33636     unselectable :  'unselectable="on"',
33637     unselectableCls :  'x-unselectable',
33638     
33639     
33640     rowClass : "x-grid-row",
33641
33642     cellClass : "x-grid-col",
33643
33644     tdClass : "x-grid-td",
33645
33646     hdClass : "x-grid-hd",
33647
33648     splitClass : "x-grid-split",
33649
33650     sortClasses : ["sort-asc", "sort-desc"],
33651
33652     enableMoveAnim : false,
33653
33654     hlColor: "C3DAF9",
33655
33656     dh : Roo.DomHelper,
33657
33658     fly : Roo.Element.fly,
33659
33660     css : Roo.util.CSS,
33661
33662     borderWidth: 1,
33663
33664     splitOffset: 3,
33665
33666     scrollIncrement : 22,
33667
33668     cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
33669
33670     findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
33671
33672     bind : function(ds, cm){
33673         if(this.ds){
33674             this.ds.un("load", this.onLoad, this);
33675             this.ds.un("datachanged", this.onDataChange, this);
33676             this.ds.un("add", this.onAdd, this);
33677             this.ds.un("remove", this.onRemove, this);
33678             this.ds.un("update", this.onUpdate, this);
33679             this.ds.un("clear", this.onClear, this);
33680         }
33681         if(ds){
33682             ds.on("load", this.onLoad, this);
33683             ds.on("datachanged", this.onDataChange, this);
33684             ds.on("add", this.onAdd, this);
33685             ds.on("remove", this.onRemove, this);
33686             ds.on("update", this.onUpdate, this);
33687             ds.on("clear", this.onClear, this);
33688         }
33689         this.ds = ds;
33690
33691         if(this.cm){
33692             this.cm.un("widthchange", this.onColWidthChange, this);
33693             this.cm.un("headerchange", this.onHeaderChange, this);
33694             this.cm.un("hiddenchange", this.onHiddenChange, this);
33695             this.cm.un("columnmoved", this.onColumnMove, this);
33696             this.cm.un("columnlockchange", this.onColumnLock, this);
33697         }
33698         if(cm){
33699             this.generateRules(cm);
33700             cm.on("widthchange", this.onColWidthChange, this);
33701             cm.on("headerchange", this.onHeaderChange, this);
33702             cm.on("hiddenchange", this.onHiddenChange, this);
33703             cm.on("columnmoved", this.onColumnMove, this);
33704             cm.on("columnlockchange", this.onColumnLock, this);
33705         }
33706         this.cm = cm;
33707     },
33708
33709     init: function(grid){
33710         Roo.grid.GridView.superclass.init.call(this, grid);
33711
33712         this.bind(grid.dataSource, grid.colModel);
33713
33714         grid.on("headerclick", this.handleHeaderClick, this);
33715
33716         if(grid.trackMouseOver){
33717             grid.on("mouseover", this.onRowOver, this);
33718             grid.on("mouseout", this.onRowOut, this);
33719         }
33720         grid.cancelTextSelection = function(){};
33721         this.gridId = grid.id;
33722
33723         var tpls = this.templates || {};
33724
33725         if(!tpls.master){
33726             tpls.master = new Roo.Template(
33727                '<div class="x-grid" hidefocus="true">',
33728                 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
33729                   '<div class="x-grid-topbar"></div>',
33730                   '<div class="x-grid-scroller"><div></div></div>',
33731                   '<div class="x-grid-locked">',
33732                       '<div class="x-grid-header">{lockedHeader}</div>',
33733                       '<div class="x-grid-body">{lockedBody}</div>',
33734                   "</div>",
33735                   '<div class="x-grid-viewport">',
33736                       '<div class="x-grid-header">{header}</div>',
33737                       '<div class="x-grid-body">{body}</div>',
33738                   "</div>",
33739                   '<div class="x-grid-bottombar"></div>',
33740                  
33741                   '<div class="x-grid-resize-proxy">&#160;</div>',
33742                "</div>"
33743             );
33744             tpls.master.disableformats = true;
33745         }
33746
33747         if(!tpls.header){
33748             tpls.header = new Roo.Template(
33749                '<table border="0" cellspacing="0" cellpadding="0">',
33750                '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
33751                "</table>{splits}"
33752             );
33753             tpls.header.disableformats = true;
33754         }
33755         tpls.header.compile();
33756
33757         if(!tpls.hcell){
33758             tpls.hcell = new Roo.Template(
33759                 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
33760                 '<div class="x-grid-hd-text ' + this.unselectableCls +  '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
33761                 "</div></td>"
33762              );
33763              tpls.hcell.disableFormats = true;
33764         }
33765         tpls.hcell.compile();
33766
33767         if(!tpls.hsplit){
33768             tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
33769                                             this.unselectableCls +  '" ' + this.unselectable +'>&#160;</div>');
33770             tpls.hsplit.disableFormats = true;
33771         }
33772         tpls.hsplit.compile();
33773
33774         if(!tpls.body){
33775             tpls.body = new Roo.Template(
33776                '<table border="0" cellspacing="0" cellpadding="0">',
33777                "<tbody>{rows}</tbody>",
33778                "</table>"
33779             );
33780             tpls.body.disableFormats = true;
33781         }
33782         tpls.body.compile();
33783
33784         if(!tpls.row){
33785             tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
33786             tpls.row.disableFormats = true;
33787         }
33788         tpls.row.compile();
33789
33790         if(!tpls.cell){
33791             tpls.cell = new Roo.Template(
33792                 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
33793                 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
33794                     this.unselectableCls +  '" ' + this.unselectable +'" {attr}>{value}</div></div>',
33795                 "</td>"
33796             );
33797             tpls.cell.disableFormats = true;
33798         }
33799         tpls.cell.compile();
33800
33801         this.templates = tpls;
33802     },
33803
33804     // remap these for backwards compat
33805     onColWidthChange : function(){
33806         this.updateColumns.apply(this, arguments);
33807     },
33808     onHeaderChange : function(){
33809         this.updateHeaders.apply(this, arguments);
33810     }, 
33811     onHiddenChange : function(){
33812         this.handleHiddenChange.apply(this, arguments);
33813     },
33814     onColumnMove : function(){
33815         this.handleColumnMove.apply(this, arguments);
33816     },
33817     onColumnLock : function(){
33818         this.handleLockChange.apply(this, arguments);
33819     },
33820
33821     onDataChange : function(){
33822         this.refresh();
33823         this.updateHeaderSortState();
33824     },
33825
33826     onClear : function(){
33827         this.refresh();
33828     },
33829
33830     onUpdate : function(ds, record){
33831         this.refreshRow(record);
33832     },
33833
33834     refreshRow : function(record){
33835         var ds = this.ds, index;
33836         if(typeof record == 'number'){
33837             index = record;
33838             record = ds.getAt(index);
33839         }else{
33840             index = ds.indexOf(record);
33841         }
33842         this.insertRows(ds, index, index, true);
33843         this.onRemove(ds, record, index+1, true);
33844         this.syncRowHeights(index, index);
33845         this.layout();
33846         this.fireEvent("rowupdated", this, index, record);
33847     },
33848
33849     onAdd : function(ds, records, index){
33850         this.insertRows(ds, index, index + (records.length-1));
33851     },
33852
33853     onRemove : function(ds, record, index, isUpdate){
33854         if(isUpdate !== true){
33855             this.fireEvent("beforerowremoved", this, index, record);
33856         }
33857         var bt = this.getBodyTable(), lt = this.getLockedTable();
33858         if(bt.rows[index]){
33859             bt.firstChild.removeChild(bt.rows[index]);
33860         }
33861         if(lt.rows[index]){
33862             lt.firstChild.removeChild(lt.rows[index]);
33863         }
33864         if(isUpdate !== true){
33865             this.stripeRows(index);
33866             this.syncRowHeights(index, index);
33867             this.layout();
33868             this.fireEvent("rowremoved", this, index, record);
33869         }
33870     },
33871
33872     onLoad : function(){
33873         this.scrollToTop();
33874     },
33875
33876     /**
33877      * Scrolls the grid to the top
33878      */
33879     scrollToTop : function(){
33880         if(this.scroller){
33881             this.scroller.dom.scrollTop = 0;
33882             this.syncScroll();
33883         }
33884     },
33885
33886     /**
33887      * Gets a panel in the header of the grid that can be used for toolbars etc.
33888      * After modifying the contents of this panel a call to grid.autoSize() may be
33889      * required to register any changes in size.
33890      * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
33891      * @return Roo.Element
33892      */
33893     getHeaderPanel : function(doShow){
33894         if(doShow){
33895             this.headerPanel.show();
33896         }
33897         return this.headerPanel;
33898     },
33899
33900     /**
33901      * Gets a panel in the footer of the grid that can be used for toolbars etc.
33902      * After modifying the contents of this panel a call to grid.autoSize() may be
33903      * required to register any changes in size.
33904      * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
33905      * @return Roo.Element
33906      */
33907     getFooterPanel : function(doShow){
33908         if(doShow){
33909             this.footerPanel.show();
33910         }
33911         return this.footerPanel;
33912     },
33913
33914     initElements : function(){
33915         var E = Roo.Element;
33916         var el = this.grid.getGridEl().dom.firstChild;
33917         var cs = el.childNodes;
33918
33919         this.el = new E(el);
33920         
33921          this.focusEl = new E(el.firstChild);
33922         this.focusEl.swallowEvent("click", true);
33923         
33924         this.headerPanel = new E(cs[1]);
33925         this.headerPanel.enableDisplayMode("block");
33926
33927         this.scroller = new E(cs[2]);
33928         this.scrollSizer = new E(this.scroller.dom.firstChild);
33929
33930         this.lockedWrap = new E(cs[3]);
33931         this.lockedHd = new E(this.lockedWrap.dom.firstChild);
33932         this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
33933
33934         this.mainWrap = new E(cs[4]);
33935         this.mainHd = new E(this.mainWrap.dom.firstChild);
33936         this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
33937
33938         this.footerPanel = new E(cs[5]);
33939         this.footerPanel.enableDisplayMode("block");
33940
33941         this.resizeProxy = new E(cs[6]);
33942
33943         this.headerSelector = String.format(
33944            '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
33945            this.lockedHd.id, this.mainHd.id
33946         );
33947
33948         this.splitterSelector = String.format(
33949            '#{0} div.x-grid-split, #{1} div.x-grid-split',
33950            this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
33951         );
33952     },
33953     idToCssName : function(s)
33954     {
33955         return s.replace(/[^a-z0-9]+/ig, '-');
33956     },
33957
33958     getHeaderCell : function(index){
33959         return Roo.DomQuery.select(this.headerSelector)[index];
33960     },
33961
33962     getHeaderCellMeasure : function(index){
33963         return this.getHeaderCell(index).firstChild;
33964     },
33965
33966     getHeaderCellText : function(index){
33967         return this.getHeaderCell(index).firstChild.firstChild;
33968     },
33969
33970     getLockedTable : function(){
33971         return this.lockedBody.dom.firstChild;
33972     },
33973
33974     getBodyTable : function(){
33975         return this.mainBody.dom.firstChild;
33976     },
33977
33978     getLockedRow : function(index){
33979         return this.getLockedTable().rows[index];
33980     },
33981
33982     getRow : function(index){
33983         return this.getBodyTable().rows[index];
33984     },
33985
33986     getRowComposite : function(index){
33987         if(!this.rowEl){
33988             this.rowEl = new Roo.CompositeElementLite();
33989         }
33990         var els = [], lrow, mrow;
33991         if(lrow = this.getLockedRow(index)){
33992             els.push(lrow);
33993         }
33994         if(mrow = this.getRow(index)){
33995             els.push(mrow);
33996         }
33997         this.rowEl.elements = els;
33998         return this.rowEl;
33999     },
34000     /**
34001      * Gets the 'td' of the cell
34002      * 
34003      * @param {Integer} rowIndex row to select
34004      * @param {Integer} colIndex column to select
34005      * 
34006      * @return {Object} 
34007      */
34008     getCell : function(rowIndex, colIndex){
34009         var locked = this.cm.getLockedCount();
34010         var source;
34011         if(colIndex < locked){
34012             source = this.lockedBody.dom.firstChild;
34013         }else{
34014             source = this.mainBody.dom.firstChild;
34015             colIndex -= locked;
34016         }
34017         return source.rows[rowIndex].childNodes[colIndex];
34018     },
34019
34020     getCellText : function(rowIndex, colIndex){
34021         return this.getCell(rowIndex, colIndex).firstChild.firstChild;
34022     },
34023
34024     getCellBox : function(cell){
34025         var b = this.fly(cell).getBox();
34026         if(Roo.isOpera){ // opera fails to report the Y
34027             b.y = cell.offsetTop + this.mainBody.getY();
34028         }
34029         return b;
34030     },
34031
34032     getCellIndex : function(cell){
34033         var id = String(cell.className).match(this.cellRE);
34034         if(id){
34035             return parseInt(id[1], 10);
34036         }
34037         return 0;
34038     },
34039
34040     findHeaderIndex : function(n){
34041         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
34042         return r ? this.getCellIndex(r) : false;
34043     },
34044
34045     findHeaderCell : function(n){
34046         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
34047         return r ? r : false;
34048     },
34049
34050     findRowIndex : function(n){
34051         if(!n){
34052             return false;
34053         }
34054         var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
34055         return r ? r.rowIndex : false;
34056     },
34057
34058     findCellIndex : function(node){
34059         var stop = this.el.dom;
34060         while(node && node != stop){
34061             if(this.findRE.test(node.className)){
34062                 return this.getCellIndex(node);
34063             }
34064             node = node.parentNode;
34065         }
34066         return false;
34067     },
34068
34069     getColumnId : function(index){
34070         return this.cm.getColumnId(index);
34071     },
34072
34073     getSplitters : function()
34074     {
34075         if(this.splitterSelector){
34076            return Roo.DomQuery.select(this.splitterSelector);
34077         }else{
34078             return null;
34079       }
34080     },
34081
34082     getSplitter : function(index){
34083         return this.getSplitters()[index];
34084     },
34085
34086     onRowOver : function(e, t){
34087         var row;
34088         if((row = this.findRowIndex(t)) !== false){
34089             this.getRowComposite(row).addClass("x-grid-row-over");
34090         }
34091     },
34092
34093     onRowOut : function(e, t){
34094         var row;
34095         if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
34096             this.getRowComposite(row).removeClass("x-grid-row-over");
34097         }
34098     },
34099
34100     renderHeaders : function(){
34101         var cm = this.cm;
34102         var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
34103         var cb = [], lb = [], sb = [], lsb = [], p = {};
34104         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
34105             p.cellId = "x-grid-hd-0-" + i;
34106             p.splitId = "x-grid-csplit-0-" + i;
34107             p.id = cm.getColumnId(i);
34108             p.value = cm.getColumnHeader(i) || "";
34109             p.title = cm.getColumnTooltip(i) || (''+p.value).match(/\</)  ? '' :  p.value  || "";
34110             p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
34111             if(!cm.isLocked(i)){
34112                 cb[cb.length] = ct.apply(p);
34113                 sb[sb.length] = st.apply(p);
34114             }else{
34115                 lb[lb.length] = ct.apply(p);
34116                 lsb[lsb.length] = st.apply(p);
34117             }
34118         }
34119         return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
34120                 ht.apply({cells: cb.join(""), splits:sb.join("")})];
34121     },
34122
34123     updateHeaders : function(){
34124         var html = this.renderHeaders();
34125         this.lockedHd.update(html[0]);
34126         this.mainHd.update(html[1]);
34127     },
34128
34129     /**
34130      * Focuses the specified row.
34131      * @param {Number} row The row index
34132      */
34133     focusRow : function(row)
34134     {
34135         //Roo.log('GridView.focusRow');
34136         var x = this.scroller.dom.scrollLeft;
34137         this.focusCell(row, 0, false);
34138         this.scroller.dom.scrollLeft = x;
34139     },
34140
34141     /**
34142      * Focuses the specified cell.
34143      * @param {Number} row The row index
34144      * @param {Number} col The column index
34145      * @param {Boolean} hscroll false to disable horizontal scrolling
34146      */
34147     focusCell : function(row, col, hscroll)
34148     {
34149         //Roo.log('GridView.focusCell');
34150         var el = this.ensureVisible(row, col, hscroll);
34151         this.focusEl.alignTo(el, "tl-tl");
34152         if(Roo.isGecko){
34153             this.focusEl.focus();
34154         }else{
34155             this.focusEl.focus.defer(1, this.focusEl);
34156         }
34157     },
34158
34159     /**
34160      * Scrolls the specified cell into view
34161      * @param {Number} row The row index
34162      * @param {Number} col The column index
34163      * @param {Boolean} hscroll false to disable horizontal scrolling
34164      */
34165     ensureVisible : function(row, col, hscroll)
34166     {
34167         //Roo.log('GridView.ensureVisible,' + row + ',' + col);
34168         //return null; //disable for testing.
34169         if(typeof row != "number"){
34170             row = row.rowIndex;
34171         }
34172         if(row < 0 && row >= this.ds.getCount()){
34173             return  null;
34174         }
34175         col = (col !== undefined ? col : 0);
34176         var cm = this.grid.colModel;
34177         while(cm.isHidden(col)){
34178             col++;
34179         }
34180
34181         var el = this.getCell(row, col);
34182         if(!el){
34183             return null;
34184         }
34185         var c = this.scroller.dom;
34186
34187         var ctop = parseInt(el.offsetTop, 10);
34188         var cleft = parseInt(el.offsetLeft, 10);
34189         var cbot = ctop + el.offsetHeight;
34190         var cright = cleft + el.offsetWidth;
34191         
34192         var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
34193         var stop = parseInt(c.scrollTop, 10);
34194         var sleft = parseInt(c.scrollLeft, 10);
34195         var sbot = stop + ch;
34196         var sright = sleft + c.clientWidth;
34197         /*
34198         Roo.log('GridView.ensureVisible:' +
34199                 ' ctop:' + ctop +
34200                 ' c.clientHeight:' + c.clientHeight +
34201                 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
34202                 ' stop:' + stop +
34203                 ' cbot:' + cbot +
34204                 ' sbot:' + sbot +
34205                 ' ch:' + ch  
34206                 );
34207         */
34208         if(ctop < stop){
34209             c.scrollTop = ctop;
34210             //Roo.log("set scrolltop to ctop DISABLE?");
34211         }else if(cbot > sbot){
34212             //Roo.log("set scrolltop to cbot-ch");
34213             c.scrollTop = cbot-ch;
34214         }
34215         
34216         if(hscroll !== false){
34217             if(cleft < sleft){
34218                 c.scrollLeft = cleft;
34219             }else if(cright > sright){
34220                 c.scrollLeft = cright-c.clientWidth;
34221             }
34222         }
34223          
34224         return el;
34225     },
34226
34227     updateColumns : function(){
34228         this.grid.stopEditing();
34229         var cm = this.grid.colModel, colIds = this.getColumnIds();
34230         //var totalWidth = cm.getTotalWidth();
34231         var pos = 0;
34232         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
34233             //if(cm.isHidden(i)) continue;
34234             var w = cm.getColumnWidth(i);
34235             this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
34236             this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
34237         }
34238         this.updateSplitters();
34239     },
34240
34241     generateRules : function(cm){
34242         var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
34243         Roo.util.CSS.removeStyleSheet(rulesId);
34244         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
34245             var cid = cm.getColumnId(i);
34246             var align = '';
34247             if(cm.config[i].align){
34248                 align = 'text-align:'+cm.config[i].align+';';
34249             }
34250             var hidden = '';
34251             if(cm.isHidden(i)){
34252                 hidden = 'display:none;';
34253             }
34254             var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
34255             ruleBuf.push(
34256                     this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
34257                     this.hdSelector, cid, " {\n", align, width, "}\n",
34258                     this.tdSelector, cid, " {\n",hidden,"\n}\n",
34259                     this.splitSelector, cid, " {\n", hidden , "\n}\n");
34260         }
34261         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
34262     },
34263
34264     updateSplitters : function(){
34265         var cm = this.cm, s = this.getSplitters();
34266         if(s){ // splitters not created yet
34267             var pos = 0, locked = true;
34268             for(var i = 0, len = cm.getColumnCount(); i < len; i++){
34269                 if(cm.isHidden(i)) {
34270                     continue;
34271                 }
34272                 var w = cm.getColumnWidth(i); // make sure it's a number
34273                 if(!cm.isLocked(i) && locked){
34274                     pos = 0;
34275                     locked = false;
34276                 }
34277                 pos += w;
34278                 s[i].style.left = (pos-this.splitOffset) + "px";
34279             }
34280         }
34281     },
34282
34283     handleHiddenChange : function(colModel, colIndex, hidden){
34284         if(hidden){
34285             this.hideColumn(colIndex);
34286         }else{
34287             this.unhideColumn(colIndex);
34288         }
34289     },
34290
34291     hideColumn : function(colIndex){
34292         var cid = this.getColumnId(colIndex);
34293         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
34294         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
34295         if(Roo.isSafari){
34296             this.updateHeaders();
34297         }
34298         this.updateSplitters();
34299         this.layout();
34300     },
34301
34302     unhideColumn : function(colIndex){
34303         var cid = this.getColumnId(colIndex);
34304         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
34305         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
34306
34307         if(Roo.isSafari){
34308             this.updateHeaders();
34309         }
34310         this.updateSplitters();
34311         this.layout();
34312     },
34313
34314     insertRows : function(dm, firstRow, lastRow, isUpdate){
34315         if(firstRow == 0 && lastRow == dm.getCount()-1){
34316             this.refresh();
34317         }else{
34318             if(!isUpdate){
34319                 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
34320             }
34321             var s = this.getScrollState();
34322             var markup = this.renderRows(firstRow, lastRow);
34323             this.bufferRows(markup[0], this.getLockedTable(), firstRow);
34324             this.bufferRows(markup[1], this.getBodyTable(), firstRow);
34325             this.restoreScroll(s);
34326             if(!isUpdate){
34327                 this.fireEvent("rowsinserted", this, firstRow, lastRow);
34328                 this.syncRowHeights(firstRow, lastRow);
34329                 this.stripeRows(firstRow);
34330                 this.layout();
34331             }
34332         }
34333     },
34334
34335     bufferRows : function(markup, target, index){
34336         var before = null, trows = target.rows, tbody = target.tBodies[0];
34337         if(index < trows.length){
34338             before = trows[index];
34339         }
34340         var b = document.createElement("div");
34341         b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
34342         var rows = b.firstChild.rows;
34343         for(var i = 0, len = rows.length; i < len; i++){
34344             if(before){
34345                 tbody.insertBefore(rows[0], before);
34346             }else{
34347                 tbody.appendChild(rows[0]);
34348             }
34349         }
34350         b.innerHTML = "";
34351         b = null;
34352     },
34353
34354     deleteRows : function(dm, firstRow, lastRow){
34355         if(dm.getRowCount()<1){
34356             this.fireEvent("beforerefresh", this);
34357             this.mainBody.update("");
34358             this.lockedBody.update("");
34359             this.fireEvent("refresh", this);
34360         }else{
34361             this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
34362             var bt = this.getBodyTable();
34363             var tbody = bt.firstChild;
34364             var rows = bt.rows;
34365             for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
34366                 tbody.removeChild(rows[firstRow]);
34367             }
34368             this.stripeRows(firstRow);
34369             this.fireEvent("rowsdeleted", this, firstRow, lastRow);
34370         }
34371     },
34372
34373     updateRows : function(dataSource, firstRow, lastRow){
34374         var s = this.getScrollState();
34375         this.refresh();
34376         this.restoreScroll(s);
34377     },
34378
34379     handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
34380         if(!noRefresh){
34381            this.refresh();
34382         }
34383         this.updateHeaderSortState();
34384     },
34385
34386     getScrollState : function(){
34387         
34388         var sb = this.scroller.dom;
34389         return {left: sb.scrollLeft, top: sb.scrollTop};
34390     },
34391
34392     stripeRows : function(startRow){
34393         if(!this.grid.stripeRows || this.ds.getCount() < 1){
34394             return;
34395         }
34396         startRow = startRow || 0;
34397         var rows = this.getBodyTable().rows;
34398         var lrows = this.getLockedTable().rows;
34399         var cls = ' x-grid-row-alt ';
34400         for(var i = startRow, len = rows.length; i < len; i++){
34401             var row = rows[i], lrow = lrows[i];
34402             var isAlt = ((i+1) % 2 == 0);
34403             var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
34404             if(isAlt == hasAlt){
34405                 continue;
34406             }
34407             if(isAlt){
34408                 row.className += " x-grid-row-alt";
34409             }else{
34410                 row.className = row.className.replace("x-grid-row-alt", "");
34411             }
34412             if(lrow){
34413                 lrow.className = row.className;
34414             }
34415         }
34416     },
34417
34418     restoreScroll : function(state){
34419         //Roo.log('GridView.restoreScroll');
34420         var sb = this.scroller.dom;
34421         sb.scrollLeft = state.left;
34422         sb.scrollTop = state.top;
34423         this.syncScroll();
34424     },
34425
34426     syncScroll : function(){
34427         //Roo.log('GridView.syncScroll');
34428         var sb = this.scroller.dom;
34429         var sh = this.mainHd.dom;
34430         var bs = this.mainBody.dom;
34431         var lv = this.lockedBody.dom;
34432         sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
34433         lv.scrollTop = bs.scrollTop = sb.scrollTop;
34434     },
34435
34436     handleScroll : function(e){
34437         this.syncScroll();
34438         var sb = this.scroller.dom;
34439         this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
34440         e.stopEvent();
34441     },
34442
34443     handleWheel : function(e){
34444         var d = e.getWheelDelta();
34445         this.scroller.dom.scrollTop -= d*22;
34446         // set this here to prevent jumpy scrolling on large tables
34447         this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
34448         e.stopEvent();
34449     },
34450
34451     renderRows : function(startRow, endRow){
34452         // pull in all the crap needed to render rows
34453         var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
34454         var colCount = cm.getColumnCount();
34455
34456         if(ds.getCount() < 1){
34457             return ["", ""];
34458         }
34459
34460         // build a map for all the columns
34461         var cs = [];
34462         for(var i = 0; i < colCount; i++){
34463             var name = cm.getDataIndex(i);
34464             cs[i] = {
34465                 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
34466                 renderer : cm.getRenderer(i),
34467                 id : cm.getColumnId(i),
34468                 locked : cm.isLocked(i),
34469                 has_editor : cm.isCellEditable(i)
34470             };
34471         }
34472
34473         startRow = startRow || 0;
34474         endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
34475
34476         // records to render
34477         var rs = ds.getRange(startRow, endRow);
34478
34479         return this.doRender(cs, rs, ds, startRow, colCount, stripe);
34480     },
34481
34482     // As much as I hate to duplicate code, this was branched because FireFox really hates
34483     // [].join("") on strings. The performance difference was substantial enough to
34484     // branch this function
34485     doRender : Roo.isGecko ?
34486             function(cs, rs, ds, startRow, colCount, stripe){
34487                 var ts = this.templates, ct = ts.cell, rt = ts.row;
34488                 // buffers
34489                 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
34490                 
34491                 var hasListener = this.grid.hasListener('rowclass');
34492                 var rowcfg = {};
34493                 for(var j = 0, len = rs.length; j < len; j++){
34494                     r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
34495                     for(var i = 0; i < colCount; i++){
34496                         c = cs[i];
34497                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
34498                         p.id = c.id;
34499                         p.css = p.attr = "";
34500                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
34501                         if(p.value == undefined || p.value === "") {
34502                             p.value = "&#160;";
34503                         }
34504                         if(c.has_editor){
34505                             p.css += ' x-grid-editable-cell';
34506                         }
34507                         if(c.dirty && typeof r.modified[c.name] !== 'undefined'){
34508                             p.css +=  ' x-grid-dirty-cell';
34509                         }
34510                         var markup = ct.apply(p);
34511                         if(!c.locked){
34512                             cb+= markup;
34513                         }else{
34514                             lcb+= markup;
34515                         }
34516                     }
34517                     var alt = [];
34518                     if(stripe && ((rowIndex+1) % 2 == 0)){
34519                         alt.push("x-grid-row-alt")
34520                     }
34521                     if(r.dirty){
34522                         alt.push(  " x-grid-dirty-row");
34523                     }
34524                     rp.cells = lcb;
34525                     if(this.getRowClass){
34526                         alt.push(this.getRowClass(r, rowIndex));
34527                     }
34528                     if (hasListener) {
34529                         rowcfg = {
34530                              
34531                             record: r,
34532                             rowIndex : rowIndex,
34533                             rowClass : ''
34534                         };
34535                         this.grid.fireEvent('rowclass', this, rowcfg);
34536                         alt.push(rowcfg.rowClass);
34537                     }
34538                     rp.alt = alt.join(" ");
34539                     lbuf+= rt.apply(rp);
34540                     rp.cells = cb;
34541                     buf+=  rt.apply(rp);
34542                 }
34543                 return [lbuf, buf];
34544             } :
34545             function(cs, rs, ds, startRow, colCount, stripe){
34546                 var ts = this.templates, ct = ts.cell, rt = ts.row;
34547                 // buffers
34548                 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
34549                 var hasListener = this.grid.hasListener('rowclass');
34550  
34551                 var rowcfg = {};
34552                 for(var j = 0, len = rs.length; j < len; j++){
34553                     r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
34554                     for(var i = 0; i < colCount; i++){
34555                         c = cs[i];
34556                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
34557                         p.id = c.id;
34558                         p.css = p.attr = "";
34559                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
34560                         if(p.value == undefined || p.value === "") {
34561                             p.value = "&#160;";
34562                         }
34563                         //Roo.log(c);
34564                          if(c.has_editor){
34565                             p.css += ' x-grid-editable-cell';
34566                         }
34567                         if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
34568                             p.css += ' x-grid-dirty-cell' 
34569                         }
34570                         
34571                         var markup = ct.apply(p);
34572                         if(!c.locked){
34573                             cb[cb.length] = markup;
34574                         }else{
34575                             lcb[lcb.length] = markup;
34576                         }
34577                     }
34578                     var alt = [];
34579                     if(stripe && ((rowIndex+1) % 2 == 0)){
34580                         alt.push( "x-grid-row-alt");
34581                     }
34582                     if(r.dirty){
34583                         alt.push(" x-grid-dirty-row");
34584                     }
34585                     rp.cells = lcb;
34586                     if(this.getRowClass){
34587                         alt.push( this.getRowClass(r, rowIndex));
34588                     }
34589                     if (hasListener) {
34590                         rowcfg = {
34591                              
34592                             record: r,
34593                             rowIndex : rowIndex,
34594                             rowClass : ''
34595                         };
34596                         this.grid.fireEvent('rowclass', this, rowcfg);
34597                         alt.push(rowcfg.rowClass);
34598                     }
34599                     
34600                     rp.alt = alt.join(" ");
34601                     rp.cells = lcb.join("");
34602                     lbuf[lbuf.length] = rt.apply(rp);
34603                     rp.cells = cb.join("");
34604                     buf[buf.length] =  rt.apply(rp);
34605                 }
34606                 return [lbuf.join(""), buf.join("")];
34607             },
34608
34609     renderBody : function(){
34610         var markup = this.renderRows();
34611         var bt = this.templates.body;
34612         return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
34613     },
34614
34615     /**
34616      * Refreshes the grid
34617      * @param {Boolean} headersToo
34618      */
34619     refresh : function(headersToo){
34620         this.fireEvent("beforerefresh", this);
34621         this.grid.stopEditing();
34622         var result = this.renderBody();
34623         this.lockedBody.update(result[0]);
34624         this.mainBody.update(result[1]);
34625         if(headersToo === true){
34626             this.updateHeaders();
34627             this.updateColumns();
34628             this.updateSplitters();
34629             this.updateHeaderSortState();
34630         }
34631         this.syncRowHeights();
34632         this.layout();
34633         this.fireEvent("refresh", this);
34634     },
34635
34636     handleColumnMove : function(cm, oldIndex, newIndex){
34637         this.indexMap = null;
34638         var s = this.getScrollState();
34639         this.refresh(true);
34640         this.restoreScroll(s);
34641         this.afterMove(newIndex);
34642     },
34643
34644     afterMove : function(colIndex){
34645         if(this.enableMoveAnim && Roo.enableFx){
34646             this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
34647         }
34648         // if multisort - fix sortOrder, and reload..
34649         if (this.grid.dataSource.multiSort) {
34650             // the we can call sort again..
34651             var dm = this.grid.dataSource;
34652             var cm = this.grid.colModel;
34653             var so = [];
34654             for(var i = 0; i < cm.config.length; i++ ) {
34655                 
34656                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
34657                     continue; // dont' bother, it's not in sort list or being set.
34658                 }
34659                 
34660                 so.push(cm.config[i].dataIndex);
34661             };
34662             dm.sortOrder = so;
34663             dm.load(dm.lastOptions);
34664             
34665             
34666         }
34667         
34668     },
34669
34670     updateCell : function(dm, rowIndex, dataIndex){
34671         var colIndex = this.getColumnIndexByDataIndex(dataIndex);
34672         if(typeof colIndex == "undefined"){ // not present in grid
34673             return;
34674         }
34675         var cm = this.grid.colModel;
34676         var cell = this.getCell(rowIndex, colIndex);
34677         var cellText = this.getCellText(rowIndex, colIndex);
34678
34679         var p = {
34680             cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
34681             id : cm.getColumnId(colIndex),
34682             css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
34683         };
34684         var renderer = cm.getRenderer(colIndex);
34685         var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
34686         if(typeof val == "undefined" || val === "") {
34687             val = "&#160;";
34688         }
34689         cellText.innerHTML = val;
34690         cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
34691         this.syncRowHeights(rowIndex, rowIndex);
34692     },
34693
34694     calcColumnWidth : function(colIndex, maxRowsToMeasure){
34695         var maxWidth = 0;
34696         if(this.grid.autoSizeHeaders){
34697             var h = this.getHeaderCellMeasure(colIndex);
34698             maxWidth = Math.max(maxWidth, h.scrollWidth);
34699         }
34700         var tb, index;
34701         if(this.cm.isLocked(colIndex)){
34702             tb = this.getLockedTable();
34703             index = colIndex;
34704         }else{
34705             tb = this.getBodyTable();
34706             index = colIndex - this.cm.getLockedCount();
34707         }
34708         if(tb && tb.rows){
34709             var rows = tb.rows;
34710             var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
34711             for(var i = 0; i < stopIndex; i++){
34712                 var cell = rows[i].childNodes[index].firstChild;
34713                 maxWidth = Math.max(maxWidth, cell.scrollWidth);
34714             }
34715         }
34716         return maxWidth + /*margin for error in IE*/ 5;
34717     },
34718     /**
34719      * Autofit a column to its content.
34720      * @param {Number} colIndex
34721      * @param {Boolean} forceMinSize true to force the column to go smaller if possible
34722      */
34723      autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
34724          if(this.cm.isHidden(colIndex)){
34725              return; // can't calc a hidden column
34726          }
34727         if(forceMinSize){
34728             var cid = this.cm.getColumnId(colIndex);
34729             this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
34730            if(this.grid.autoSizeHeaders){
34731                this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
34732            }
34733         }
34734         var newWidth = this.calcColumnWidth(colIndex);
34735         this.cm.setColumnWidth(colIndex,
34736             Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
34737         if(!suppressEvent){
34738             this.grid.fireEvent("columnresize", colIndex, newWidth);
34739         }
34740     },
34741
34742     /**
34743      * Autofits all columns to their content and then expands to fit any extra space in the grid
34744      */
34745      autoSizeColumns : function(){
34746         var cm = this.grid.colModel;
34747         var colCount = cm.getColumnCount();
34748         for(var i = 0; i < colCount; i++){
34749             this.autoSizeColumn(i, true, true);
34750         }
34751         if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
34752             this.fitColumns();
34753         }else{
34754             this.updateColumns();
34755             this.layout();
34756         }
34757     },
34758
34759     /**
34760      * Autofits all columns to the grid's width proportionate with their current size
34761      * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
34762      */
34763     fitColumns : function(reserveScrollSpace){
34764         var cm = this.grid.colModel;
34765         var colCount = cm.getColumnCount();
34766         var cols = [];
34767         var width = 0;
34768         var i, w;
34769         for (i = 0; i < colCount; i++){
34770             if(!cm.isHidden(i) && !cm.isFixed(i)){
34771                 w = cm.getColumnWidth(i);
34772                 cols.push(i);
34773                 cols.push(w);
34774                 width += w;
34775             }
34776         }
34777         var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
34778         if(reserveScrollSpace){
34779             avail -= 17;
34780         }
34781         var frac = (avail - cm.getTotalWidth())/width;
34782         while (cols.length){
34783             w = cols.pop();
34784             i = cols.pop();
34785             cm.setColumnWidth(i, Math.floor(w + w*frac), true);
34786         }
34787         this.updateColumns();
34788         this.layout();
34789     },
34790
34791     onRowSelect : function(rowIndex){
34792         var row = this.getRowComposite(rowIndex);
34793         row.addClass("x-grid-row-selected");
34794     },
34795
34796     onRowDeselect : function(rowIndex){
34797         var row = this.getRowComposite(rowIndex);
34798         row.removeClass("x-grid-row-selected");
34799     },
34800
34801     onCellSelect : function(row, col){
34802         var cell = this.getCell(row, col);
34803         if(cell){
34804             Roo.fly(cell).addClass("x-grid-cell-selected");
34805         }
34806     },
34807
34808     onCellDeselect : function(row, col){
34809         var cell = this.getCell(row, col);
34810         if(cell){
34811             Roo.fly(cell).removeClass("x-grid-cell-selected");
34812         }
34813     },
34814
34815     updateHeaderSortState : function(){
34816         
34817         // sort state can be single { field: xxx, direction : yyy}
34818         // or   { xxx=>ASC , yyy : DESC ..... }
34819         
34820         var mstate = {};
34821         if (!this.ds.multiSort) { 
34822             var state = this.ds.getSortState();
34823             if(!state){
34824                 return;
34825             }
34826             mstate[state.field] = state.direction;
34827             // FIXME... - this is not used here.. but might be elsewhere..
34828             this.sortState = state;
34829             
34830         } else {
34831             mstate = this.ds.sortToggle;
34832         }
34833         //remove existing sort classes..
34834         
34835         var sc = this.sortClasses;
34836         var hds = this.el.select(this.headerSelector).removeClass(sc);
34837         
34838         for(var f in mstate) {
34839         
34840             var sortColumn = this.cm.findColumnIndex(f);
34841             
34842             if(sortColumn != -1){
34843                 var sortDir = mstate[f];        
34844                 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
34845             }
34846         }
34847         
34848          
34849         
34850     },
34851
34852
34853     handleHeaderClick : function(g, index,e){
34854         
34855         Roo.log("header click");
34856         
34857         if (Roo.isTouch) {
34858             // touch events on header are handled by context
34859             this.handleHdCtx(g,index,e);
34860             return;
34861         }
34862         
34863         
34864         if(this.headersDisabled){
34865             return;
34866         }
34867         var dm = g.dataSource, cm = g.colModel;
34868         if(!cm.isSortable(index)){
34869             return;
34870         }
34871         g.stopEditing();
34872         
34873         if (dm.multiSort) {
34874             // update the sortOrder
34875             var so = [];
34876             for(var i = 0; i < cm.config.length; i++ ) {
34877                 
34878                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
34879                     continue; // dont' bother, it's not in sort list or being set.
34880                 }
34881                 
34882                 so.push(cm.config[i].dataIndex);
34883             };
34884             dm.sortOrder = so;
34885         }
34886         
34887         
34888         dm.sort(cm.getDataIndex(index));
34889     },
34890
34891
34892     destroy : function(){
34893         if(this.colMenu){
34894             this.colMenu.removeAll();
34895             Roo.menu.MenuMgr.unregister(this.colMenu);
34896             this.colMenu.getEl().remove();
34897             delete this.colMenu;
34898         }
34899         if(this.hmenu){
34900             this.hmenu.removeAll();
34901             Roo.menu.MenuMgr.unregister(this.hmenu);
34902             this.hmenu.getEl().remove();
34903             delete this.hmenu;
34904         }
34905         if(this.grid.enableColumnMove){
34906             var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
34907             if(dds){
34908                 for(var dd in dds){
34909                     if(!dds[dd].config.isTarget && dds[dd].dragElId){
34910                         var elid = dds[dd].dragElId;
34911                         dds[dd].unreg();
34912                         Roo.get(elid).remove();
34913                     } else if(dds[dd].config.isTarget){
34914                         dds[dd].proxyTop.remove();
34915                         dds[dd].proxyBottom.remove();
34916                         dds[dd].unreg();
34917                     }
34918                     if(Roo.dd.DDM.locationCache[dd]){
34919                         delete Roo.dd.DDM.locationCache[dd];
34920                     }
34921                 }
34922                 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
34923             }
34924         }
34925         Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
34926         this.bind(null, null);
34927         Roo.EventManager.removeResizeListener(this.onWindowResize, this);
34928     },
34929
34930     handleLockChange : function(){
34931         this.refresh(true);
34932     },
34933
34934     onDenyColumnLock : function(){
34935
34936     },
34937
34938     onDenyColumnHide : function(){
34939
34940     },
34941
34942     handleHdMenuClick : function(item){
34943         var index = this.hdCtxIndex;
34944         var cm = this.cm, ds = this.ds;
34945         switch(item.id){
34946             case "asc":
34947                 ds.sort(cm.getDataIndex(index), "ASC");
34948                 break;
34949             case "desc":
34950                 ds.sort(cm.getDataIndex(index), "DESC");
34951                 break;
34952             case "lock":
34953                 var lc = cm.getLockedCount();
34954                 if(cm.getColumnCount(true) <= lc+1){
34955                     this.onDenyColumnLock();
34956                     return;
34957                 }
34958                 if(lc != index){
34959                     cm.setLocked(index, true, true);
34960                     cm.moveColumn(index, lc);
34961                     this.grid.fireEvent("columnmove", index, lc);
34962                 }else{
34963                     cm.setLocked(index, true);
34964                 }
34965             break;
34966             case "unlock":
34967                 var lc = cm.getLockedCount();
34968                 if((lc-1) != index){
34969                     cm.setLocked(index, false, true);
34970                     cm.moveColumn(index, lc-1);
34971                     this.grid.fireEvent("columnmove", index, lc-1);
34972                 }else{
34973                     cm.setLocked(index, false);
34974                 }
34975             break;
34976             case 'wider': // used to expand cols on touch..
34977             case 'narrow':
34978                 var cw = cm.getColumnWidth(index);
34979                 cw += (item.id == 'wider' ? 1 : -1) * 50;
34980                 cw = Math.max(0, cw);
34981                 cw = Math.min(cw,4000);
34982                 cm.setColumnWidth(index, cw);
34983                 break;
34984                 
34985             default:
34986                 index = cm.getIndexById(item.id.substr(4));
34987                 if(index != -1){
34988                     if(item.checked && cm.getColumnCount(true) <= 1){
34989                         this.onDenyColumnHide();
34990                         return false;
34991                     }
34992                     cm.setHidden(index, item.checked);
34993                 }
34994         }
34995         return true;
34996     },
34997
34998     beforeColMenuShow : function(){
34999         var cm = this.cm,  colCount = cm.getColumnCount();
35000         this.colMenu.removeAll();
35001         for(var i = 0; i < colCount; i++){
35002             this.colMenu.add(new Roo.menu.CheckItem({
35003                 id: "col-"+cm.getColumnId(i),
35004                 text: cm.getColumnHeader(i),
35005                 checked: !cm.isHidden(i),
35006                 hideOnClick:false
35007             }));
35008         }
35009     },
35010
35011     handleHdCtx : function(g, index, e){
35012         e.stopEvent();
35013         var hd = this.getHeaderCell(index);
35014         this.hdCtxIndex = index;
35015         var ms = this.hmenu.items, cm = this.cm;
35016         ms.get("asc").setDisabled(!cm.isSortable(index));
35017         ms.get("desc").setDisabled(!cm.isSortable(index));
35018         if(this.grid.enableColLock !== false){
35019             ms.get("lock").setDisabled(cm.isLocked(index));
35020             ms.get("unlock").setDisabled(!cm.isLocked(index));
35021         }
35022         this.hmenu.show(hd, "tl-bl");
35023     },
35024
35025     handleHdOver : function(e){
35026         var hd = this.findHeaderCell(e.getTarget());
35027         if(hd && !this.headersDisabled){
35028             if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
35029                this.fly(hd).addClass("x-grid-hd-over");
35030             }
35031         }
35032     },
35033
35034     handleHdOut : function(e){
35035         var hd = this.findHeaderCell(e.getTarget());
35036         if(hd){
35037             this.fly(hd).removeClass("x-grid-hd-over");
35038         }
35039     },
35040
35041     handleSplitDblClick : function(e, t){
35042         var i = this.getCellIndex(t);
35043         if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
35044             this.autoSizeColumn(i, true);
35045             this.layout();
35046         }
35047     },
35048
35049     render : function(){
35050
35051         var cm = this.cm;
35052         var colCount = cm.getColumnCount();
35053
35054         if(this.grid.monitorWindowResize === true){
35055             Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
35056         }
35057         var header = this.renderHeaders();
35058         var body = this.templates.body.apply({rows:""});
35059         var html = this.templates.master.apply({
35060             lockedBody: body,
35061             body: body,
35062             lockedHeader: header[0],
35063             header: header[1]
35064         });
35065
35066         //this.updateColumns();
35067
35068         this.grid.getGridEl().dom.innerHTML = html;
35069
35070         this.initElements();
35071         
35072         // a kludge to fix the random scolling effect in webkit
35073         this.el.on("scroll", function() {
35074             this.el.dom.scrollTop=0; // hopefully not recursive..
35075         },this);
35076
35077         this.scroller.on("scroll", this.handleScroll, this);
35078         this.lockedBody.on("mousewheel", this.handleWheel, this);
35079         this.mainBody.on("mousewheel", this.handleWheel, this);
35080
35081         this.mainHd.on("mouseover", this.handleHdOver, this);
35082         this.mainHd.on("mouseout", this.handleHdOut, this);
35083         this.mainHd.on("dblclick", this.handleSplitDblClick, this,
35084                 {delegate: "."+this.splitClass});
35085
35086         this.lockedHd.on("mouseover", this.handleHdOver, this);
35087         this.lockedHd.on("mouseout", this.handleHdOut, this);
35088         this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
35089                 {delegate: "."+this.splitClass});
35090
35091         if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
35092             new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
35093         }
35094
35095         this.updateSplitters();
35096
35097         if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
35098             new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
35099             new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
35100         }
35101
35102         if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
35103             this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
35104             this.hmenu.add(
35105                 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
35106                 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
35107             );
35108             if(this.grid.enableColLock !== false){
35109                 this.hmenu.add('-',
35110                     {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
35111                     {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
35112                 );
35113             }
35114             if (Roo.isTouch) {
35115                  this.hmenu.add('-',
35116                     {id:"wider", text: this.columnsWiderText},
35117                     {id:"narrow", text: this.columnsNarrowText }
35118                 );
35119                 
35120                  
35121             }
35122             
35123             if(this.grid.enableColumnHide !== false){
35124
35125                 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
35126                 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
35127                 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
35128
35129                 this.hmenu.add('-',
35130                     {id:"columns", text: this.columnsText, menu: this.colMenu}
35131                 );
35132             }
35133             this.hmenu.on("itemclick", this.handleHdMenuClick, this);
35134
35135             this.grid.on("headercontextmenu", this.handleHdCtx, this);
35136         }
35137
35138         if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
35139             this.dd = new Roo.grid.GridDragZone(this.grid, {
35140                 ddGroup : this.grid.ddGroup || 'GridDD'
35141             });
35142             
35143         }
35144
35145         /*
35146         for(var i = 0; i < colCount; i++){
35147             if(cm.isHidden(i)){
35148                 this.hideColumn(i);
35149             }
35150             if(cm.config[i].align){
35151                 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
35152                 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
35153             }
35154         }*/
35155         
35156         this.updateHeaderSortState();
35157
35158         this.beforeInitialResize();
35159         this.layout(true);
35160
35161         // two part rendering gives faster view to the user
35162         this.renderPhase2.defer(1, this);
35163     },
35164
35165     renderPhase2 : function(){
35166         // render the rows now
35167         this.refresh();
35168         if(this.grid.autoSizeColumns){
35169             this.autoSizeColumns();
35170         }
35171     },
35172
35173     beforeInitialResize : function(){
35174
35175     },
35176
35177     onColumnSplitterMoved : function(i, w){
35178         this.userResized = true;
35179         var cm = this.grid.colModel;
35180         cm.setColumnWidth(i, w, true);
35181         var cid = cm.getColumnId(i);
35182         this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
35183         this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
35184         this.updateSplitters();
35185         this.layout();
35186         this.grid.fireEvent("columnresize", i, w);
35187     },
35188
35189     syncRowHeights : function(startIndex, endIndex){
35190         if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
35191             startIndex = startIndex || 0;
35192             var mrows = this.getBodyTable().rows;
35193             var lrows = this.getLockedTable().rows;
35194             var len = mrows.length-1;
35195             endIndex = Math.min(endIndex || len, len);
35196             for(var i = startIndex; i <= endIndex; i++){
35197                 var m = mrows[i], l = lrows[i];
35198                 var h = Math.max(m.offsetHeight, l.offsetHeight);
35199                 m.style.height = l.style.height = h + "px";
35200             }
35201         }
35202     },
35203
35204     layout : function(initialRender, is2ndPass)
35205     {
35206         var g = this.grid;
35207         var auto = g.autoHeight;
35208         var scrollOffset = 16;
35209         var c = g.getGridEl(), cm = this.cm,
35210                 expandCol = g.autoExpandColumn,
35211                 gv = this;
35212         //c.beginMeasure();
35213
35214         if(!c.dom.offsetWidth){ // display:none?
35215             if(initialRender){
35216                 this.lockedWrap.show();
35217                 this.mainWrap.show();
35218             }
35219             return;
35220         }
35221
35222         var hasLock = this.cm.isLocked(0);
35223
35224         var tbh = this.headerPanel.getHeight();
35225         var bbh = this.footerPanel.getHeight();
35226
35227         if(auto){
35228             var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
35229             var newHeight = ch + c.getBorderWidth("tb");
35230             if(g.maxHeight){
35231                 newHeight = Math.min(g.maxHeight, newHeight);
35232             }
35233             c.setHeight(newHeight);
35234         }
35235
35236         if(g.autoWidth){
35237             c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
35238         }
35239
35240         var s = this.scroller;
35241
35242         var csize = c.getSize(true);
35243
35244         this.el.setSize(csize.width, csize.height);
35245
35246         this.headerPanel.setWidth(csize.width);
35247         this.footerPanel.setWidth(csize.width);
35248
35249         var hdHeight = this.mainHd.getHeight();
35250         var vw = csize.width;
35251         var vh = csize.height - (tbh + bbh);
35252
35253         s.setSize(vw, vh);
35254
35255         var bt = this.getBodyTable();
35256         
35257         if(cm.getLockedCount() == cm.config.length){
35258             bt = this.getLockedTable();
35259         }
35260         
35261         var ltWidth = hasLock ?
35262                       Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
35263
35264         var scrollHeight = bt.offsetHeight;
35265         var scrollWidth = ltWidth + bt.offsetWidth;
35266         var vscroll = false, hscroll = false;
35267
35268         this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
35269
35270         var lw = this.lockedWrap, mw = this.mainWrap;
35271         var lb = this.lockedBody, mb = this.mainBody;
35272
35273         setTimeout(function(){
35274             var t = s.dom.offsetTop;
35275             var w = s.dom.clientWidth,
35276                 h = s.dom.clientHeight;
35277
35278             lw.setTop(t);
35279             lw.setSize(ltWidth, h);
35280
35281             mw.setLeftTop(ltWidth, t);
35282             mw.setSize(w-ltWidth, h);
35283
35284             lb.setHeight(h-hdHeight);
35285             mb.setHeight(h-hdHeight);
35286
35287             if(is2ndPass !== true && !gv.userResized && expandCol){
35288                 // high speed resize without full column calculation
35289                 
35290                 var ci = cm.getIndexById(expandCol);
35291                 if (ci < 0) {
35292                     ci = cm.findColumnIndex(expandCol);
35293                 }
35294                 ci = Math.max(0, ci); // make sure it's got at least the first col.
35295                 var expandId = cm.getColumnId(ci);
35296                 var  tw = cm.getTotalWidth(false);
35297                 var currentWidth = cm.getColumnWidth(ci);
35298                 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
35299                 if(currentWidth != cw){
35300                     cm.setColumnWidth(ci, cw, true);
35301                     gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
35302                     gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
35303                     gv.updateSplitters();
35304                     gv.layout(false, true);
35305                 }
35306             }
35307
35308             if(initialRender){
35309                 lw.show();
35310                 mw.show();
35311             }
35312             //c.endMeasure();
35313         }, 10);
35314     },
35315
35316     onWindowResize : function(){
35317         if(!this.grid.monitorWindowResize || this.grid.autoHeight){
35318             return;
35319         }
35320         this.layout();
35321     },
35322
35323     appendFooter : function(parentEl){
35324         return null;
35325     },
35326
35327     sortAscText : "Sort Ascending",
35328     sortDescText : "Sort Descending",
35329     lockText : "Lock Column",
35330     unlockText : "Unlock Column",
35331     columnsText : "Columns",
35332  
35333     columnsWiderText : "Wider",
35334     columnsNarrowText : "Thinner"
35335 });
35336
35337
35338 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
35339     Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
35340     this.proxy.el.addClass('x-grid3-col-dd');
35341 };
35342
35343 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
35344     handleMouseDown : function(e){
35345
35346     },
35347
35348     callHandleMouseDown : function(e){
35349         Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
35350     }
35351 });
35352 /*
35353  * Based on:
35354  * Ext JS Library 1.1.1
35355  * Copyright(c) 2006-2007, Ext JS, LLC.
35356  *
35357  * Originally Released Under LGPL - original licence link has changed is not relivant.
35358  *
35359  * Fork - LGPL
35360  * <script type="text/javascript">
35361  */
35362  /**
35363  * @extends Roo.dd.DDProxy
35364  * @class Roo.grid.SplitDragZone
35365  * Support for Column Header resizing
35366  * @constructor
35367  * @param {Object} config
35368  */
35369 // private
35370 // This is a support class used internally by the Grid components
35371 Roo.grid.SplitDragZone = function(grid, hd, hd2){
35372     this.grid = grid;
35373     this.view = grid.getView();
35374     this.proxy = this.view.resizeProxy;
35375     Roo.grid.SplitDragZone.superclass.constructor.call(
35376         this,
35377         hd, // ID
35378         "gridSplitters" + this.grid.getGridEl().id, // SGROUP
35379         {  // CONFIG
35380             dragElId : Roo.id(this.proxy.dom),
35381             resizeFrame:false
35382         }
35383     );
35384     
35385     this.setHandleElId(Roo.id(hd));
35386     if (hd2 !== false) {
35387         this.setOuterHandleElId(Roo.id(hd2));
35388     }
35389     
35390     this.scroll = false;
35391 };
35392 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
35393     fly: Roo.Element.fly,
35394
35395     b4StartDrag : function(x, y){
35396         this.view.headersDisabled = true;
35397         var h = this.view.mainWrap ? this.view.mainWrap.getHeight() : (
35398                     this.view.headEl.getHeight() + this.view.bodyEl.getHeight()
35399         );
35400         this.proxy.setHeight(h);
35401         
35402         // for old system colWidth really stored the actual width?
35403         // in bootstrap we tried using xs/ms/etc.. to do % sizing?
35404         // which in reality did not work.. - it worked only for fixed sizes
35405         // for resizable we need to use actual sizes.
35406         var w = this.cm.getColumnWidth(this.cellIndex);
35407         if (!this.view.mainWrap) {
35408             // bootstrap.
35409             w = this.view.getHeaderIndex(this.cellIndex).getWidth();
35410         }
35411         
35412         
35413         
35414         // this was w-this.grid.minColumnWidth;
35415         // doesnt really make sense? - w = thie curren width or the rendered one?
35416         var minw = Math.max(w-this.grid.minColumnWidth, 0);
35417         this.resetConstraints();
35418         this.setXConstraint(minw, 1000);
35419         this.setYConstraint(0, 0);
35420         this.minX = x - minw;
35421         this.maxX = x + 1000;
35422         this.startPos = x;
35423         if (!this.view.mainWrap) { // this is Bootstrap code..
35424             this.getDragEl().style.display='block';
35425         }
35426         
35427         Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
35428     },
35429
35430
35431     handleMouseDown : function(e){
35432         ev = Roo.EventObject.setEvent(e);
35433         var t = this.fly(ev.getTarget());
35434         if(t.hasClass("x-grid-split")){
35435             this.cellIndex = this.view.getCellIndex(t.dom);
35436             this.split = t.dom;
35437             this.cm = this.grid.colModel;
35438             if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
35439                 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
35440             }
35441         }
35442     },
35443
35444     endDrag : function(e){
35445         this.view.headersDisabled = false;
35446         var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
35447         var diff = endX - this.startPos;
35448         // 
35449         var w = this.cm.getColumnWidth(this.cellIndex);
35450         if (!this.view.mainWrap) {
35451             w = 0;
35452         }
35453         this.view.onColumnSplitterMoved(this.cellIndex, w+diff);
35454     },
35455
35456     autoOffset : function(){
35457         this.setDelta(0,0);
35458     }
35459 });/*
35460  * Based on:
35461  * Ext JS Library 1.1.1
35462  * Copyright(c) 2006-2007, Ext JS, LLC.
35463  *
35464  * Originally Released Under LGPL - original licence link has changed is not relivant.
35465  *
35466  * Fork - LGPL
35467  * <script type="text/javascript">
35468  */
35469  
35470 // private
35471 // This is a support class used internally by the Grid components
35472 Roo.grid.GridDragZone = function(grid, config){
35473     this.view = grid.getView();
35474     Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
35475     if(this.view.lockedBody){
35476         this.setHandleElId(Roo.id(this.view.mainBody.dom));
35477         this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
35478     }
35479     this.scroll = false;
35480     this.grid = grid;
35481     this.ddel = document.createElement('div');
35482     this.ddel.className = 'x-grid-dd-wrap';
35483 };
35484
35485 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
35486     ddGroup : "GridDD",
35487
35488     getDragData : function(e){
35489         var t = Roo.lib.Event.getTarget(e);
35490         var rowIndex = this.view.findRowIndex(t);
35491         var sm = this.grid.selModel;
35492             
35493         //Roo.log(rowIndex);
35494         
35495         if (sm.getSelectedCell) {
35496             // cell selection..
35497             if (!sm.getSelectedCell()) {
35498                 return false;
35499             }
35500             if (rowIndex != sm.getSelectedCell()[0]) {
35501                 return false;
35502             }
35503         
35504         }
35505         if (sm.getSelections && sm.getSelections().length < 1) {
35506             return false;
35507         }
35508         
35509         
35510         // before it used to all dragging of unseleted... - now we dont do that.
35511         if(rowIndex !== false){
35512             
35513             // if editorgrid.. 
35514             
35515             
35516             //Roo.log([ sm.getSelectedCell() ? sm.getSelectedCell()[0] : 'NO' , rowIndex ]);
35517                
35518             //if(!sm.isSelected(rowIndex) || e.hasModifier()){
35519               //  
35520             //}
35521             if (e.hasModifier()){
35522                 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
35523             }
35524             
35525             Roo.log("getDragData");
35526             
35527             return {
35528                 grid: this.grid,
35529                 ddel: this.ddel,
35530                 rowIndex: rowIndex,
35531                 selections: sm.getSelections ? sm.getSelections() : (
35532                     sm.getSelectedCell() ? [ this.grid.ds.getAt(sm.getSelectedCell()[0]) ] : [])
35533             };
35534         }
35535         return false;
35536     },
35537     
35538     
35539     onInitDrag : function(e){
35540         var data = this.dragData;
35541         this.ddel.innerHTML = this.grid.getDragDropText();
35542         this.proxy.update(this.ddel);
35543         // fire start drag?
35544     },
35545
35546     afterRepair : function(){
35547         this.dragging = false;
35548     },
35549
35550     getRepairXY : function(e, data){
35551         return false;
35552     },
35553
35554     onEndDrag : function(data, e){
35555         // fire end drag?
35556     },
35557
35558     onValidDrop : function(dd, e, id){
35559         // fire drag drop?
35560         this.hideProxy();
35561     },
35562
35563     beforeInvalidDrop : function(e, id){
35564
35565     }
35566 });/*
35567  * Based on:
35568  * Ext JS Library 1.1.1
35569  * Copyright(c) 2006-2007, Ext JS, LLC.
35570  *
35571  * Originally Released Under LGPL - original licence link has changed is not relivant.
35572  *
35573  * Fork - LGPL
35574  * <script type="text/javascript">
35575  */
35576  
35577
35578 /**
35579  * @class Roo.grid.ColumnModel
35580  * @extends Roo.util.Observable
35581  * This is the default implementation of a ColumnModel used by the Grid. It defines
35582  * the columns in the grid.
35583  * <br>Usage:<br>
35584  <pre><code>
35585  var colModel = new Roo.grid.ColumnModel([
35586         {header: "Ticker", width: 60, sortable: true, locked: true},
35587         {header: "Company Name", width: 150, sortable: true},
35588         {header: "Market Cap.", width: 100, sortable: true},
35589         {header: "$ Sales", width: 100, sortable: true, renderer: money},
35590         {header: "Employees", width: 100, sortable: true, resizable: false}
35591  ]);
35592  </code></pre>
35593  * <p>
35594  
35595  * The config options listed for this class are options which may appear in each
35596  * individual column definition.
35597  * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
35598  * @constructor
35599  * @param {Object} config An Array of column config objects. See this class's
35600  * config objects for details.
35601 */
35602 Roo.grid.ColumnModel = function(config){
35603         /**
35604      * The config passed into the constructor
35605      */
35606     this.config = []; //config;
35607     this.lookup = {};
35608
35609     // if no id, create one
35610     // if the column does not have a dataIndex mapping,
35611     // map it to the order it is in the config
35612     for(var i = 0, len = config.length; i < len; i++){
35613         this.addColumn(config[i]);
35614         
35615     }
35616
35617     /**
35618      * The width of columns which have no width specified (defaults to 100)
35619      * @type Number
35620      */
35621     this.defaultWidth = 100;
35622
35623     /**
35624      * Default sortable of columns which have no sortable specified (defaults to false)
35625      * @type Boolean
35626      */
35627     this.defaultSortable = false;
35628
35629     this.addEvents({
35630         /**
35631              * @event widthchange
35632              * Fires when the width of a column changes.
35633              * @param {ColumnModel} this
35634              * @param {Number} columnIndex The column index
35635              * @param {Number} newWidth The new width
35636              */
35637             "widthchange": true,
35638         /**
35639              * @event headerchange
35640              * Fires when the text of a header changes.
35641              * @param {ColumnModel} this
35642              * @param {Number} columnIndex The column index
35643              * @param {Number} newText The new header text
35644              */
35645             "headerchange": true,
35646         /**
35647              * @event hiddenchange
35648              * Fires when a column is hidden or "unhidden".
35649              * @param {ColumnModel} this
35650              * @param {Number} columnIndex The column index
35651              * @param {Boolean} hidden true if hidden, false otherwise
35652              */
35653             "hiddenchange": true,
35654             /**
35655          * @event columnmoved
35656          * Fires when a column is moved.
35657          * @param {ColumnModel} this
35658          * @param {Number} oldIndex
35659          * @param {Number} newIndex
35660          */
35661         "columnmoved" : true,
35662         /**
35663          * @event columlockchange
35664          * Fires when a column's locked state is changed
35665          * @param {ColumnModel} this
35666          * @param {Number} colIndex
35667          * @param {Boolean} locked true if locked
35668          */
35669         "columnlockchange" : true
35670     });
35671     Roo.grid.ColumnModel.superclass.constructor.call(this);
35672 };
35673 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
35674     /**
35675      * @cfg {String} header The header text to display in the Grid view.
35676      */
35677         /**
35678      * @cfg {String} xsHeader Header at Bootsrap Extra Small width (default for all)
35679      */
35680         /**
35681      * @cfg {String} smHeader Header at Bootsrap Small width
35682      */
35683         /**
35684      * @cfg {String} mdHeader Header at Bootsrap Medium width
35685      */
35686         /**
35687      * @cfg {String} lgHeader Header at Bootsrap Large width
35688      */
35689         /**
35690      * @cfg {String} xlHeader Header at Bootsrap extra Large width
35691      */
35692     /**
35693      * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
35694      * {@link Roo.data.Record} definition from which to draw the column's value. If not
35695      * specified, the column's index is used as an index into the Record's data Array.
35696      */
35697     /**
35698      * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
35699      * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
35700      */
35701     /**
35702      * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
35703      * Defaults to the value of the {@link #defaultSortable} property.
35704      * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
35705      */
35706     /**
35707      * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid.  Defaults to false.
35708      */
35709     /**
35710      * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed.  Defaults to false.
35711      */
35712     /**
35713      * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
35714      */
35715     /**
35716      * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
35717      */
35718     /**
35719      * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
35720      * given the cell's data value. See {@link #setRenderer}. If not specified, the
35721      * default renderer returns the escaped data value. If an object is returned (bootstrap only)
35722      * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
35723      */
35724        /**
35725      * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor 
35726      */
35727     /**
35728      * @cfg {String} align (Optional) Set the CSS text-align property of the column.  Defaults to undefined.
35729      */
35730     /**
35731      * @cfg {String} valign (Optional) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc).  Defaults to undefined.
35732      */
35733     /**
35734      * @cfg {String} cursor (Optional)
35735      */
35736     /**
35737      * @cfg {String} tooltip (Optional)
35738      */
35739     /**
35740      * @cfg {Number} xs (Optional) can be '0' for hidden at this size (number less than 12)
35741      */
35742     /**
35743      * @cfg {Number} sm (Optional) can be '0' for hidden at this size (number less than 12)
35744      */
35745     /**
35746      * @cfg {Number} md (Optional) can be '0' for hidden at this size (number less than 12)
35747      */
35748     /**
35749      * @cfg {Number} lg (Optional) can be '0' for hidden at this size (number less than 12)
35750      */
35751         /**
35752      * @cfg {Number} xl (Optional) can be '0' for hidden at this size (number less than 12)
35753      */
35754     /**
35755      * Returns the id of the column at the specified index.
35756      * @param {Number} index The column index
35757      * @return {String} the id
35758      */
35759     getColumnId : function(index){
35760         return this.config[index].id;
35761     },
35762
35763     /**
35764      * Returns the column for a specified id.
35765      * @param {String} id The column id
35766      * @return {Object} the column
35767      */
35768     getColumnById : function(id){
35769         return this.lookup[id];
35770     },
35771
35772     
35773     /**
35774      * Returns the column Object for a specified dataIndex.
35775      * @param {String} dataIndex The column dataIndex
35776      * @return {Object|Boolean} the column or false if not found
35777      */
35778     getColumnByDataIndex: function(dataIndex){
35779         var index = this.findColumnIndex(dataIndex);
35780         return index > -1 ? this.config[index] : false;
35781     },
35782     
35783     /**
35784      * Returns the index for a specified column id.
35785      * @param {String} id The column id
35786      * @return {Number} the index, or -1 if not found
35787      */
35788     getIndexById : function(id){
35789         for(var i = 0, len = this.config.length; i < len; i++){
35790             if(this.config[i].id == id){
35791                 return i;
35792             }
35793         }
35794         return -1;
35795     },
35796     
35797     /**
35798      * Returns the index for a specified column dataIndex.
35799      * @param {String} dataIndex The column dataIndex
35800      * @return {Number} the index, or -1 if not found
35801      */
35802     
35803     findColumnIndex : function(dataIndex){
35804         for(var i = 0, len = this.config.length; i < len; i++){
35805             if(this.config[i].dataIndex == dataIndex){
35806                 return i;
35807             }
35808         }
35809         return -1;
35810     },
35811     
35812     
35813     moveColumn : function(oldIndex, newIndex){
35814         var c = this.config[oldIndex];
35815         this.config.splice(oldIndex, 1);
35816         this.config.splice(newIndex, 0, c);
35817         this.dataMap = null;
35818         this.fireEvent("columnmoved", this, oldIndex, newIndex);
35819     },
35820
35821     isLocked : function(colIndex){
35822         return this.config[colIndex].locked === true;
35823     },
35824
35825     setLocked : function(colIndex, value, suppressEvent){
35826         if(this.isLocked(colIndex) == value){
35827             return;
35828         }
35829         this.config[colIndex].locked = value;
35830         if(!suppressEvent){
35831             this.fireEvent("columnlockchange", this, colIndex, value);
35832         }
35833     },
35834
35835     getTotalLockedWidth : function(){
35836         var totalWidth = 0;
35837         for(var i = 0; i < this.config.length; i++){
35838             if(this.isLocked(i) && !this.isHidden(i)){
35839                 this.totalWidth += this.getColumnWidth(i);
35840             }
35841         }
35842         return totalWidth;
35843     },
35844
35845     getLockedCount : function(){
35846         for(var i = 0, len = this.config.length; i < len; i++){
35847             if(!this.isLocked(i)){
35848                 return i;
35849             }
35850         }
35851         
35852         return this.config.length;
35853     },
35854
35855     /**
35856      * Returns the number of columns.
35857      * @return {Number}
35858      */
35859     getColumnCount : function(visibleOnly){
35860         if(visibleOnly === true){
35861             var c = 0;
35862             for(var i = 0, len = this.config.length; i < len; i++){
35863                 if(!this.isHidden(i)){
35864                     c++;
35865                 }
35866             }
35867             return c;
35868         }
35869         return this.config.length;
35870     },
35871
35872     /**
35873      * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
35874      * @param {Function} fn
35875      * @param {Object} scope (optional)
35876      * @return {Array} result
35877      */
35878     getColumnsBy : function(fn, scope){
35879         var r = [];
35880         for(var i = 0, len = this.config.length; i < len; i++){
35881             var c = this.config[i];
35882             if(fn.call(scope||this, c, i) === true){
35883                 r[r.length] = c;
35884             }
35885         }
35886         return r;
35887     },
35888
35889     /**
35890      * Returns true if the specified column is sortable.
35891      * @param {Number} col The column index
35892      * @return {Boolean}
35893      */
35894     isSortable : function(col){
35895         if(typeof this.config[col].sortable == "undefined"){
35896             return this.defaultSortable;
35897         }
35898         return this.config[col].sortable;
35899     },
35900
35901     /**
35902      * Returns the rendering (formatting) function defined for the column.
35903      * @param {Number} col The column index.
35904      * @return {Function} The function used to render the cell. See {@link #setRenderer}.
35905      */
35906     getRenderer : function(col){
35907         if(!this.config[col].renderer){
35908             return Roo.grid.ColumnModel.defaultRenderer;
35909         }
35910         return this.config[col].renderer;
35911     },
35912
35913     /**
35914      * Sets the rendering (formatting) function for a column.
35915      * @param {Number} col The column index
35916      * @param {Function} fn The function to use to process the cell's raw data
35917      * to return HTML markup for the grid view. The render function is called with
35918      * the following parameters:<ul>
35919      * <li>Data value.</li>
35920      * <li>Cell metadata. An object in which you may set the following attributes:<ul>
35921      * <li>css A CSS style string to apply to the table cell.</li>
35922      * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
35923      * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
35924      * <li>Row index</li>
35925      * <li>Column index</li>
35926      * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
35927      */
35928     setRenderer : function(col, fn){
35929         this.config[col].renderer = fn;
35930     },
35931
35932     /**
35933      * Returns the width for the specified column.
35934      * @param {Number} col The column index
35935      * @param (optional) {String} gridSize bootstrap width size.
35936      * @return {Number}
35937      */
35938     getColumnWidth : function(col, gridSize)
35939         {
35940                 var cfg = this.config[col];
35941                 
35942                 if (typeof(gridSize) == 'undefined') {
35943                         return cfg.width * 1 || this.defaultWidth;
35944                 }
35945                 if (gridSize === false) { // if we set it..
35946                         return cfg.width || false;
35947                 }
35948                 var sizes = ['xl', 'lg', 'md', 'sm', 'xs'];
35949                 
35950                 for(var i = sizes.indexOf(gridSize); i < sizes.length; i++) {
35951                         if (typeof(cfg[ sizes[i] ] ) == 'undefined') {
35952                                 continue;
35953                         }
35954                         return cfg[ sizes[i] ];
35955                 }
35956                 return 1;
35957                 
35958     },
35959
35960     /**
35961      * Sets the width for a column.
35962      * @param {Number} col The column index
35963      * @param {Number} width The new width
35964      */
35965     setColumnWidth : function(col, width, suppressEvent){
35966         this.config[col].width = width;
35967         this.totalWidth = null;
35968         if(!suppressEvent){
35969              this.fireEvent("widthchange", this, col, width);
35970         }
35971     },
35972
35973     /**
35974      * Returns the total width of all columns.
35975      * @param {Boolean} includeHidden True to include hidden column widths
35976      * @return {Number}
35977      */
35978     getTotalWidth : function(includeHidden){
35979         if(!this.totalWidth){
35980             this.totalWidth = 0;
35981             for(var i = 0, len = this.config.length; i < len; i++){
35982                 if(includeHidden || !this.isHidden(i)){
35983                     this.totalWidth += this.getColumnWidth(i);
35984                 }
35985             }
35986         }
35987         return this.totalWidth;
35988     },
35989
35990     /**
35991      * Returns the header for the specified column.
35992      * @param {Number} col The column index
35993      * @return {String}
35994      */
35995     getColumnHeader : function(col){
35996         return this.config[col].header;
35997     },
35998
35999     /**
36000      * Sets the header for a column.
36001      * @param {Number} col The column index
36002      * @param {String} header The new header
36003      */
36004     setColumnHeader : function(col, header){
36005         this.config[col].header = header;
36006         this.fireEvent("headerchange", this, col, header);
36007     },
36008
36009     /**
36010      * Returns the tooltip for the specified column.
36011      * @param {Number} col The column index
36012      * @return {String}
36013      */
36014     getColumnTooltip : function(col){
36015             return this.config[col].tooltip;
36016     },
36017     /**
36018      * Sets the tooltip for a column.
36019      * @param {Number} col The column index
36020      * @param {String} tooltip The new tooltip
36021      */
36022     setColumnTooltip : function(col, tooltip){
36023             this.config[col].tooltip = tooltip;
36024     },
36025
36026     /**
36027      * Returns the dataIndex for the specified column.
36028      * @param {Number} col The column index
36029      * @return {Number}
36030      */
36031     getDataIndex : function(col){
36032         return this.config[col].dataIndex;
36033     },
36034
36035     /**
36036      * Sets the dataIndex for a column.
36037      * @param {Number} col The column index
36038      * @param {Number} dataIndex The new dataIndex
36039      */
36040     setDataIndex : function(col, dataIndex){
36041         this.config[col].dataIndex = dataIndex;
36042     },
36043
36044     
36045     
36046     /**
36047      * Returns true if the cell is editable.
36048      * @param {Number} colIndex The column index
36049      * @param {Number} rowIndex The row index - this is nto actually used..?
36050      * @return {Boolean}
36051      */
36052     isCellEditable : function(colIndex, rowIndex){
36053         return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
36054     },
36055
36056     /**
36057      * Returns the editor defined for the cell/column.
36058      * return false or null to disable editing.
36059      * @param {Number} colIndex The column index
36060      * @param {Number} rowIndex The row index
36061      * @return {Object}
36062      */
36063     getCellEditor : function(colIndex, rowIndex){
36064         return this.config[colIndex].editor;
36065     },
36066
36067     /**
36068      * Sets if a column is editable.
36069      * @param {Number} col The column index
36070      * @param {Boolean} editable True if the column is editable
36071      */
36072     setEditable : function(col, editable){
36073         this.config[col].editable = editable;
36074     },
36075
36076
36077     /**
36078      * Returns true if the column is hidden.
36079      * @param {Number} colIndex The column index
36080      * @return {Boolean}
36081      */
36082     isHidden : function(colIndex){
36083         return this.config[colIndex].hidden;
36084     },
36085
36086
36087     /**
36088      * Returns true if the column width cannot be changed
36089      */
36090     isFixed : function(colIndex){
36091         return this.config[colIndex].fixed;
36092     },
36093
36094     /**
36095      * Returns true if the column can be resized
36096      * @return {Boolean}
36097      */
36098     isResizable : function(colIndex){
36099         return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
36100     },
36101     /**
36102      * Sets if a column is hidden.
36103      * @param {Number} colIndex The column index
36104      * @param {Boolean} hidden True if the column is hidden
36105      */
36106     setHidden : function(colIndex, hidden){
36107         this.config[colIndex].hidden = hidden;
36108         this.totalWidth = null;
36109         this.fireEvent("hiddenchange", this, colIndex, hidden);
36110     },
36111
36112     /**
36113      * Sets the editor for a column.
36114      * @param {Number} col The column index
36115      * @param {Object} editor The editor object
36116      */
36117     setEditor : function(col, editor){
36118         this.config[col].editor = editor;
36119     },
36120     /**
36121      * Add a column (experimental...) - defaults to adding to the end..
36122      * @param {Object} config 
36123     */
36124     addColumn : function(c)
36125     {
36126     
36127         var i = this.config.length;
36128         this.config[i] = c;
36129         
36130         if(typeof c.dataIndex == "undefined"){
36131             c.dataIndex = i;
36132         }
36133         if(typeof c.renderer == "string"){
36134             c.renderer = Roo.util.Format[c.renderer];
36135         }
36136         if(typeof c.id == "undefined"){
36137             c.id = Roo.id();
36138         }
36139         if(c.editor && c.editor.xtype){
36140             c.editor  = Roo.factory(c.editor, Roo.grid);
36141         }
36142         if(c.editor && c.editor.isFormField){
36143             c.editor = new Roo.grid.GridEditor(c.editor);
36144         }
36145         this.lookup[c.id] = c;
36146     }
36147     
36148 });
36149
36150 Roo.grid.ColumnModel.defaultRenderer = function(value)
36151 {
36152     if(typeof value == "object") {
36153         return value;
36154     }
36155         if(typeof value == "string" && value.length < 1){
36156             return "&#160;";
36157         }
36158     
36159         return String.format("{0}", value);
36160 };
36161
36162 // Alias for backwards compatibility
36163 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
36164 /*
36165  * Based on:
36166  * Ext JS Library 1.1.1
36167  * Copyright(c) 2006-2007, Ext JS, LLC.
36168  *
36169  * Originally Released Under LGPL - original licence link has changed is not relivant.
36170  *
36171  * Fork - LGPL
36172  * <script type="text/javascript">
36173  */
36174
36175 /**
36176  * @class Roo.grid.AbstractSelectionModel
36177  * @extends Roo.util.Observable
36178  * @abstract
36179  * Abstract base class for grid SelectionModels.  It provides the interface that should be
36180  * implemented by descendant classes.  This class should not be directly instantiated.
36181  * @constructor
36182  */
36183 Roo.grid.AbstractSelectionModel = function(){
36184     this.locked = false;
36185     Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
36186 };
36187
36188 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable,  {
36189     /** @ignore Called by the grid automatically. Do not call directly. */
36190     init : function(grid){
36191         this.grid = grid;
36192         this.initEvents();
36193     },
36194
36195     /**
36196      * Locks the selections.
36197      */
36198     lock : function(){
36199         this.locked = true;
36200     },
36201
36202     /**
36203      * Unlocks the selections.
36204      */
36205     unlock : function(){
36206         this.locked = false;
36207     },
36208
36209     /**
36210      * Returns true if the selections are locked.
36211      * @return {Boolean}
36212      */
36213     isLocked : function(){
36214         return this.locked;
36215     }
36216 });/*
36217  * Based on:
36218  * Ext JS Library 1.1.1
36219  * Copyright(c) 2006-2007, Ext JS, LLC.
36220  *
36221  * Originally Released Under LGPL - original licence link has changed is not relivant.
36222  *
36223  * Fork - LGPL
36224  * <script type="text/javascript">
36225  */
36226 /**
36227  * @extends Roo.grid.AbstractSelectionModel
36228  * @class Roo.grid.RowSelectionModel
36229  * The default SelectionModel used by {@link Roo.grid.Grid}.
36230  * It supports multiple selections and keyboard selection/navigation. 
36231  * @constructor
36232  * @param {Object} config
36233  */
36234 Roo.grid.RowSelectionModel = function(config){
36235     Roo.apply(this, config);
36236     this.selections = new Roo.util.MixedCollection(false, function(o){
36237         return o.id;
36238     });
36239
36240     this.last = false;
36241     this.lastActive = false;
36242
36243     this.addEvents({
36244         /**
36245         * @event selectionchange
36246         * Fires when the selection changes
36247         * @param {SelectionModel} this
36248         */
36249        "selectionchange" : true,
36250        /**
36251         * @event afterselectionchange
36252         * Fires after the selection changes (eg. by key press or clicking)
36253         * @param {SelectionModel} this
36254         */
36255        "afterselectionchange" : true,
36256        /**
36257         * @event beforerowselect
36258         * Fires when a row is selected being selected, return false to cancel.
36259         * @param {SelectionModel} this
36260         * @param {Number} rowIndex The selected index
36261         * @param {Boolean} keepExisting False if other selections will be cleared
36262         */
36263        "beforerowselect" : true,
36264        /**
36265         * @event rowselect
36266         * Fires when a row is selected.
36267         * @param {SelectionModel} this
36268         * @param {Number} rowIndex The selected index
36269         * @param {Roo.data.Record} r The record
36270         */
36271        "rowselect" : true,
36272        /**
36273         * @event rowdeselect
36274         * Fires when a row is deselected.
36275         * @param {SelectionModel} this
36276         * @param {Number} rowIndex The selected index
36277         */
36278         "rowdeselect" : true
36279     });
36280     Roo.grid.RowSelectionModel.superclass.constructor.call(this);
36281     this.locked = false;
36282 };
36283
36284 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel,  {
36285     /**
36286      * @cfg {Boolean} singleSelect
36287      * True to allow selection of only one row at a time (defaults to false)
36288      */
36289     singleSelect : false,
36290
36291     // private
36292     initEvents : function(){
36293
36294         if(!this.grid.enableDragDrop && !this.grid.enableDrag){
36295             this.grid.on("mousedown", this.handleMouseDown, this);
36296         }else{ // allow click to work like normal
36297             this.grid.on("rowclick", this.handleDragableRowClick, this);
36298         }
36299         // bootstrap does not have a view..
36300         var view = this.grid.view ? this.grid.view : this.grid;
36301         this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
36302             "up" : function(e){
36303                 if(!e.shiftKey){
36304                     this.selectPrevious(e.shiftKey);
36305                 }else if(this.last !== false && this.lastActive !== false){
36306                     var last = this.last;
36307                     this.selectRange(this.last,  this.lastActive-1);
36308                     view.focusRow(this.lastActive);
36309                     if(last !== false){
36310                         this.last = last;
36311                     }
36312                 }else{
36313                     this.selectFirstRow();
36314                 }
36315                 this.fireEvent("afterselectionchange", this);
36316             },
36317             "down" : function(e){
36318                 if(!e.shiftKey){
36319                     this.selectNext(e.shiftKey);
36320                 }else if(this.last !== false && this.lastActive !== false){
36321                     var last = this.last;
36322                     this.selectRange(this.last,  this.lastActive+1);
36323                     view.focusRow(this.lastActive);
36324                     if(last !== false){
36325                         this.last = last;
36326                     }
36327                 }else{
36328                     this.selectFirstRow();
36329                 }
36330                 this.fireEvent("afterselectionchange", this);
36331             },
36332             scope: this
36333         });
36334
36335          
36336         view.on("refresh", this.onRefresh, this);
36337         view.on("rowupdated", this.onRowUpdated, this);
36338         view.on("rowremoved", this.onRemove, this);
36339     },
36340
36341     // private
36342     onRefresh : function(){
36343         var ds = this.grid.ds, i, v = this.grid.view;
36344         var s = this.selections;
36345         s.each(function(r){
36346             if((i = ds.indexOfId(r.id)) != -1){
36347                 v.onRowSelect(i);
36348                 s.add(ds.getAt(i)); // updating the selection relate data
36349             }else{
36350                 s.remove(r);
36351             }
36352         });
36353     },
36354
36355     // private
36356     onRemove : function(v, index, r){
36357         this.selections.remove(r);
36358     },
36359
36360     // private
36361     onRowUpdated : function(v, index, r){
36362         if(this.isSelected(r)){
36363             v.onRowSelect(index);
36364         }
36365     },
36366
36367     /**
36368      * Select records.
36369      * @param {Array} records The records to select
36370      * @param {Boolean} keepExisting (optional) True to keep existing selections
36371      */
36372     selectRecords : function(records, keepExisting){
36373         if(!keepExisting){
36374             this.clearSelections();
36375         }
36376         var ds = this.grid.ds;
36377         for(var i = 0, len = records.length; i < len; i++){
36378             this.selectRow(ds.indexOf(records[i]), true);
36379         }
36380     },
36381
36382     /**
36383      * Gets the number of selected rows.
36384      * @return {Number}
36385      */
36386     getCount : function(){
36387         return this.selections.length;
36388     },
36389
36390     /**
36391      * Selects the first row in the grid.
36392      */
36393     selectFirstRow : function(){
36394         this.selectRow(0);
36395     },
36396
36397     /**
36398      * Select the last row.
36399      * @param {Boolean} keepExisting (optional) True to keep existing selections
36400      */
36401     selectLastRow : function(keepExisting){
36402         this.selectRow(this.grid.ds.getCount() - 1, keepExisting);
36403     },
36404
36405     /**
36406      * Selects the row immediately following the last selected row.
36407      * @param {Boolean} keepExisting (optional) True to keep existing selections
36408      */
36409     selectNext : function(keepExisting){
36410         if(this.last !== false && (this.last+1) < this.grid.ds.getCount()){
36411             this.selectRow(this.last+1, keepExisting);
36412             var view = this.grid.view ? this.grid.view : this.grid;
36413             view.focusRow(this.last);
36414         }
36415     },
36416
36417     /**
36418      * Selects the row that precedes the last selected row.
36419      * @param {Boolean} keepExisting (optional) True to keep existing selections
36420      */
36421     selectPrevious : function(keepExisting){
36422         if(this.last){
36423             this.selectRow(this.last-1, keepExisting);
36424             var view = this.grid.view ? this.grid.view : this.grid;
36425             view.focusRow(this.last);
36426         }
36427     },
36428
36429     /**
36430      * Returns the selected records
36431      * @return {Array} Array of selected records
36432      */
36433     getSelections : function(){
36434         return [].concat(this.selections.items);
36435     },
36436
36437     /**
36438      * Returns the first selected record.
36439      * @return {Record}
36440      */
36441     getSelected : function(){
36442         return this.selections.itemAt(0);
36443     },
36444
36445
36446     /**
36447      * Clears all selections.
36448      */
36449     clearSelections : function(fast){
36450         if(this.locked) {
36451             return;
36452         }
36453         if(fast !== true){
36454             var ds = this.grid.ds;
36455             var s = this.selections;
36456             s.each(function(r){
36457                 this.deselectRow(ds.indexOfId(r.id));
36458             }, this);
36459             s.clear();
36460         }else{
36461             this.selections.clear();
36462         }
36463         this.last = false;
36464     },
36465
36466
36467     /**
36468      * Selects all rows.
36469      */
36470     selectAll : function(){
36471         if(this.locked) {
36472             return;
36473         }
36474         this.selections.clear();
36475         for(var i = 0, len = this.grid.ds.getCount(); i < len; i++){
36476             this.selectRow(i, true);
36477         }
36478     },
36479
36480     /**
36481      * Returns True if there is a selection.
36482      * @return {Boolean}
36483      */
36484     hasSelection : function(){
36485         return this.selections.length > 0;
36486     },
36487
36488     /**
36489      * Returns True if the specified row is selected.
36490      * @param {Number/Record} record The record or index of the record to check
36491      * @return {Boolean}
36492      */
36493     isSelected : function(index){
36494         var r = typeof index == "number" ? this.grid.ds.getAt(index) : index;
36495         return (r && this.selections.key(r.id) ? true : false);
36496     },
36497
36498     /**
36499      * Returns True if the specified record id is selected.
36500      * @param {String} id The id of record to check
36501      * @return {Boolean}
36502      */
36503     isIdSelected : function(id){
36504         return (this.selections.key(id) ? true : false);
36505     },
36506
36507     // private
36508     handleMouseDown : function(e, t)
36509     {
36510         var view = this.grid.view ? this.grid.view : this.grid;
36511         var rowIndex;
36512         if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
36513             return;
36514         };
36515         if(e.shiftKey && this.last !== false){
36516             var last = this.last;
36517             this.selectRange(last, rowIndex, e.ctrlKey);
36518             this.last = last; // reset the last
36519             view.focusRow(rowIndex);
36520         }else{
36521             var isSelected = this.isSelected(rowIndex);
36522             if(e.button !== 0 && isSelected){
36523                 view.focusRow(rowIndex);
36524             }else if(e.ctrlKey && isSelected){
36525                 this.deselectRow(rowIndex);
36526             }else if(!isSelected){
36527                 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
36528                 view.focusRow(rowIndex);
36529             }
36530         }
36531         this.fireEvent("afterselectionchange", this);
36532     },
36533     // private
36534     handleDragableRowClick :  function(grid, rowIndex, e) 
36535     {
36536         if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
36537             this.selectRow(rowIndex, false);
36538             var view = this.grid.view ? this.grid.view : this.grid;
36539             view.focusRow(rowIndex);
36540              this.fireEvent("afterselectionchange", this);
36541         }
36542     },
36543     
36544     /**
36545      * Selects multiple rows.
36546      * @param {Array} rows Array of the indexes of the row to select
36547      * @param {Boolean} keepExisting (optional) True to keep existing selections
36548      */
36549     selectRows : function(rows, keepExisting){
36550         if(!keepExisting){
36551             this.clearSelections();
36552         }
36553         for(var i = 0, len = rows.length; i < len; i++){
36554             this.selectRow(rows[i], true);
36555         }
36556     },
36557
36558     /**
36559      * Selects a range of rows. All rows in between startRow and endRow are also selected.
36560      * @param {Number} startRow The index of the first row in the range
36561      * @param {Number} endRow The index of the last row in the range
36562      * @param {Boolean} keepExisting (optional) True to retain existing selections
36563      */
36564     selectRange : function(startRow, endRow, keepExisting){
36565         if(this.locked) {
36566             return;
36567         }
36568         if(!keepExisting){
36569             this.clearSelections();
36570         }
36571         if(startRow <= endRow){
36572             for(var i = startRow; i <= endRow; i++){
36573                 this.selectRow(i, true);
36574             }
36575         }else{
36576             for(var i = startRow; i >= endRow; i--){
36577                 this.selectRow(i, true);
36578             }
36579         }
36580     },
36581
36582     /**
36583      * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
36584      * @param {Number} startRow The index of the first row in the range
36585      * @param {Number} endRow The index of the last row in the range
36586      */
36587     deselectRange : function(startRow, endRow, preventViewNotify){
36588         if(this.locked) {
36589             return;
36590         }
36591         for(var i = startRow; i <= endRow; i++){
36592             this.deselectRow(i, preventViewNotify);
36593         }
36594     },
36595
36596     /**
36597      * Selects a row.
36598      * @param {Number} row The index of the row to select
36599      * @param {Boolean} keepExisting (optional) True to keep existing selections
36600      */
36601     selectRow : function(index, keepExisting, preventViewNotify){
36602         if(this.locked || (index < 0 || index >= this.grid.ds.getCount())) {
36603             return;
36604         }
36605         if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
36606             if(!keepExisting || this.singleSelect){
36607                 this.clearSelections();
36608             }
36609             var r = this.grid.ds.getAt(index);
36610             this.selections.add(r);
36611             this.last = this.lastActive = index;
36612             if(!preventViewNotify){
36613                 var view = this.grid.view ? this.grid.view : this.grid;
36614                 view.onRowSelect(index);
36615             }
36616             this.fireEvent("rowselect", this, index, r);
36617             this.fireEvent("selectionchange", this);
36618         }
36619     },
36620
36621     /**
36622      * Deselects a row.
36623      * @param {Number} row The index of the row to deselect
36624      */
36625     deselectRow : function(index, preventViewNotify){
36626         if(this.locked) {
36627             return;
36628         }
36629         if(this.last == index){
36630             this.last = false;
36631         }
36632         if(this.lastActive == index){
36633             this.lastActive = false;
36634         }
36635         var r = this.grid.ds.getAt(index);
36636         this.selections.remove(r);
36637         if(!preventViewNotify){
36638             var view = this.grid.view ? this.grid.view : this.grid;
36639             view.onRowDeselect(index);
36640         }
36641         this.fireEvent("rowdeselect", this, index);
36642         this.fireEvent("selectionchange", this);
36643     },
36644
36645     // private
36646     restoreLast : function(){
36647         if(this._last){
36648             this.last = this._last;
36649         }
36650     },
36651
36652     // private
36653     acceptsNav : function(row, col, cm){
36654         return !cm.isHidden(col) && cm.isCellEditable(col, row);
36655     },
36656
36657     // private
36658     onEditorKey : function(field, e){
36659         var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
36660         if(k == e.TAB){
36661             e.stopEvent();
36662             ed.completeEdit();
36663             if(e.shiftKey){
36664                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
36665             }else{
36666                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
36667             }
36668         }else if(k == e.ENTER && !e.ctrlKey){
36669             e.stopEvent();
36670             ed.completeEdit();
36671             if(e.shiftKey){
36672                 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
36673             }else{
36674                 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
36675             }
36676         }else if(k == e.ESC){
36677             ed.cancelEdit();
36678         }
36679         if(newCell){
36680             g.startEditing(newCell[0], newCell[1]);
36681         }
36682     }
36683 });/*
36684  * Based on:
36685  * Ext JS Library 1.1.1
36686  * Copyright(c) 2006-2007, Ext JS, LLC.
36687  *
36688  * Originally Released Under LGPL - original licence link has changed is not relivant.
36689  *
36690  * Fork - LGPL
36691  * <script type="text/javascript">
36692  */
36693 /**
36694  * @class Roo.grid.CellSelectionModel
36695  * @extends Roo.grid.AbstractSelectionModel
36696  * This class provides the basic implementation for cell selection in a grid.
36697  * @constructor
36698  * @param {Object} config The object containing the configuration of this model.
36699  * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
36700  */
36701 Roo.grid.CellSelectionModel = function(config){
36702     Roo.apply(this, config);
36703
36704     this.selection = null;
36705
36706     this.addEvents({
36707         /**
36708              * @event beforerowselect
36709              * Fires before a cell is selected.
36710              * @param {SelectionModel} this
36711              * @param {Number} rowIndex The selected row index
36712              * @param {Number} colIndex The selected cell index
36713              */
36714             "beforecellselect" : true,
36715         /**
36716              * @event cellselect
36717              * Fires when a cell is selected.
36718              * @param {SelectionModel} this
36719              * @param {Number} rowIndex The selected row index
36720              * @param {Number} colIndex The selected cell index
36721              */
36722             "cellselect" : true,
36723         /**
36724              * @event selectionchange
36725              * Fires when the active selection changes.
36726              * @param {SelectionModel} this
36727              * @param {Object} selection null for no selection or an object (o) with two properties
36728                 <ul>
36729                 <li>o.record: the record object for the row the selection is in</li>
36730                 <li>o.cell: An array of [rowIndex, columnIndex]</li>
36731                 </ul>
36732              */
36733             "selectionchange" : true,
36734         /**
36735              * @event tabend
36736              * Fires when the tab (or enter) was pressed on the last editable cell
36737              * You can use this to trigger add new row.
36738              * @param {SelectionModel} this
36739              */
36740             "tabend" : true,
36741          /**
36742              * @event beforeeditnext
36743              * Fires before the next editable sell is made active
36744              * You can use this to skip to another cell or fire the tabend
36745              *    if you set cell to false
36746              * @param {Object} eventdata object : { cell : [ row, col ] } 
36747              */
36748             "beforeeditnext" : true
36749     });
36750     Roo.grid.CellSelectionModel.superclass.constructor.call(this);
36751 };
36752
36753 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel,  {
36754     
36755     enter_is_tab: false,
36756
36757     /** @ignore */
36758     initEvents : function(){
36759         this.grid.on("mousedown", this.handleMouseDown, this);
36760         this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
36761         var view = this.grid.view;
36762         view.on("refresh", this.onViewChange, this);
36763         view.on("rowupdated", this.onRowUpdated, this);
36764         view.on("beforerowremoved", this.clearSelections, this);
36765         view.on("beforerowsinserted", this.clearSelections, this);
36766         if(this.grid.isEditor){
36767             this.grid.on("beforeedit", this.beforeEdit,  this);
36768         }
36769     },
36770
36771         //private
36772     beforeEdit : function(e){
36773         this.select(e.row, e.column, false, true, e.record);
36774     },
36775
36776         //private
36777     onRowUpdated : function(v, index, r){
36778         if(this.selection && this.selection.record == r){
36779             v.onCellSelect(index, this.selection.cell[1]);
36780         }
36781     },
36782
36783         //private
36784     onViewChange : function(){
36785         this.clearSelections(true);
36786     },
36787
36788         /**
36789          * Returns the currently selected cell,.
36790          * @return {Array} The selected cell (row, column) or null if none selected.
36791          */
36792     getSelectedCell : function(){
36793         return this.selection ? this.selection.cell : null;
36794     },
36795
36796     /**
36797      * Clears all selections.
36798      * @param {Boolean} true to prevent the gridview from being notified about the change.
36799      */
36800     clearSelections : function(preventNotify){
36801         var s = this.selection;
36802         if(s){
36803             if(preventNotify !== true){
36804                 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
36805             }
36806             this.selection = null;
36807             this.fireEvent("selectionchange", this, null);
36808         }
36809     },
36810
36811     /**
36812      * Returns true if there is a selection.
36813      * @return {Boolean}
36814      */
36815     hasSelection : function(){
36816         return this.selection ? true : false;
36817     },
36818
36819     /** @ignore */
36820     handleMouseDown : function(e, t){
36821         var v = this.grid.getView();
36822         if(this.isLocked()){
36823             return;
36824         };
36825         var row = v.findRowIndex(t);
36826         var cell = v.findCellIndex(t);
36827         if(row !== false && cell !== false){
36828             this.select(row, cell);
36829         }
36830     },
36831
36832     /**
36833      * Selects a cell.
36834      * @param {Number} rowIndex
36835      * @param {Number} collIndex
36836      */
36837     select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
36838         if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
36839             this.clearSelections();
36840             r = r || this.grid.dataSource.getAt(rowIndex);
36841             this.selection = {
36842                 record : r,
36843                 cell : [rowIndex, colIndex]
36844             };
36845             if(!preventViewNotify){
36846                 var v = this.grid.getView();
36847                 v.onCellSelect(rowIndex, colIndex);
36848                 if(preventFocus !== true){
36849                     v.focusCell(rowIndex, colIndex);
36850                 }
36851             }
36852             this.fireEvent("cellselect", this, rowIndex, colIndex);
36853             this.fireEvent("selectionchange", this, this.selection);
36854         }
36855     },
36856
36857         //private
36858     isSelectable : function(rowIndex, colIndex, cm){
36859         return !cm.isHidden(colIndex);
36860     },
36861
36862     /** @ignore */
36863     handleKeyDown : function(e){
36864         //Roo.log('Cell Sel Model handleKeyDown');
36865         if(!e.isNavKeyPress()){
36866             return;
36867         }
36868         var g = this.grid, s = this.selection;
36869         if(!s){
36870             e.stopEvent();
36871             var cell = g.walkCells(0, 0, 1, this.isSelectable,  this);
36872             if(cell){
36873                 this.select(cell[0], cell[1]);
36874             }
36875             return;
36876         }
36877         var sm = this;
36878         var walk = function(row, col, step){
36879             return g.walkCells(row, col, step, sm.isSelectable,  sm);
36880         };
36881         var k = e.getKey(), r = s.cell[0], c = s.cell[1];
36882         var newCell;
36883
36884       
36885
36886         switch(k){
36887             case e.TAB:
36888                 // handled by onEditorKey
36889                 if (g.isEditor && g.editing) {
36890                     return;
36891                 }
36892                 if(e.shiftKey) {
36893                     newCell = walk(r, c-1, -1);
36894                 } else {
36895                     newCell = walk(r, c+1, 1);
36896                 }
36897                 break;
36898             
36899             case e.DOWN:
36900                newCell = walk(r+1, c, 1);
36901                 break;
36902             
36903             case e.UP:
36904                 newCell = walk(r-1, c, -1);
36905                 break;
36906             
36907             case e.RIGHT:
36908                 newCell = walk(r, c+1, 1);
36909                 break;
36910             
36911             case e.LEFT:
36912                 newCell = walk(r, c-1, -1);
36913                 break;
36914             
36915             case e.ENTER:
36916                 
36917                 if(g.isEditor && !g.editing){
36918                    g.startEditing(r, c);
36919                    e.stopEvent();
36920                    return;
36921                 }
36922                 
36923                 
36924              break;
36925         };
36926         if(newCell){
36927             this.select(newCell[0], newCell[1]);
36928             e.stopEvent();
36929             
36930         }
36931     },
36932
36933     acceptsNav : function(row, col, cm){
36934         return !cm.isHidden(col) && cm.isCellEditable(col, row);
36935     },
36936     /**
36937      * Selects a cell.
36938      * @param {Number} field (not used) - as it's normally used as a listener
36939      * @param {Number} e - event - fake it by using
36940      *
36941      * var e = Roo.EventObjectImpl.prototype;
36942      * e.keyCode = e.TAB
36943      *
36944      * 
36945      */
36946     onEditorKey : function(field, e){
36947         
36948         var k = e.getKey(),
36949             newCell,
36950             g = this.grid,
36951             ed = g.activeEditor,
36952             forward = false;
36953         ///Roo.log('onEditorKey' + k);
36954         
36955         
36956         if (this.enter_is_tab && k == e.ENTER) {
36957             k = e.TAB;
36958         }
36959         
36960         if(k == e.TAB){
36961             if(e.shiftKey){
36962                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
36963             }else{
36964                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
36965                 forward = true;
36966             }
36967             
36968             e.stopEvent();
36969             
36970         } else if(k == e.ENTER &&  !e.ctrlKey){
36971             ed.completeEdit();
36972             e.stopEvent();
36973             newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
36974         
36975                 } else if(k == e.ESC){
36976             ed.cancelEdit();
36977         }
36978                 
36979         if (newCell) {
36980             var ecall = { cell : newCell, forward : forward };
36981             this.fireEvent('beforeeditnext', ecall );
36982             newCell = ecall.cell;
36983                         forward = ecall.forward;
36984         }
36985                 
36986         if(newCell){
36987             //Roo.log('next cell after edit');
36988             g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
36989         } else if (forward) {
36990             // tabbed past last
36991             this.fireEvent.defer(100, this, ['tabend',this]);
36992         }
36993     }
36994 });/*
36995  * Based on:
36996  * Ext JS Library 1.1.1
36997  * Copyright(c) 2006-2007, Ext JS, LLC.
36998  *
36999  * Originally Released Under LGPL - original licence link has changed is not relivant.
37000  *
37001  * Fork - LGPL
37002  * <script type="text/javascript">
37003  */
37004  
37005 /**
37006  * @class Roo.grid.EditorGrid
37007  * @extends Roo.grid.Grid
37008  * Class for creating and editable grid.
37009  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered - 
37010  * The container MUST have some type of size defined for the grid to fill. The container will be 
37011  * automatically set to position relative if it isn't already.
37012  * @param {Object} dataSource The data model to bind to
37013  * @param {Object} colModel The column model with info about this grid's columns
37014  */
37015 Roo.grid.EditorGrid = function(container, config){
37016     Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
37017     this.getGridEl().addClass("xedit-grid");
37018
37019     if(!this.selModel){
37020         this.selModel = new Roo.grid.CellSelectionModel();
37021     }
37022
37023     this.activeEditor = null;
37024
37025         this.addEvents({
37026             /**
37027              * @event beforeedit
37028              * Fires before cell editing is triggered. The edit event object has the following properties <br />
37029              * <ul style="padding:5px;padding-left:16px;">
37030              * <li>grid - This grid</li>
37031              * <li>record - The record being edited</li>
37032              * <li>field - The field name being edited</li>
37033              * <li>value - The value for the field being edited.</li>
37034              * <li>row - The grid row index</li>
37035              * <li>column - The grid column index</li>
37036              * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
37037              * </ul>
37038              * @param {Object} e An edit event (see above for description)
37039              */
37040             "beforeedit" : true,
37041             /**
37042              * @event afteredit
37043              * Fires after a cell is edited. <br />
37044              * <ul style="padding:5px;padding-left:16px;">
37045              * <li>grid - This grid</li>
37046              * <li>record - The record being edited</li>
37047              * <li>field - The field name being edited</li>
37048              * <li>value - The value being set</li>
37049              * <li>originalValue - The original value for the field, before the edit.</li>
37050              * <li>row - The grid row index</li>
37051              * <li>column - The grid column index</li>
37052              * </ul>
37053              * @param {Object} e An edit event (see above for description)
37054              */
37055             "afteredit" : true,
37056             /**
37057              * @event validateedit
37058              * Fires after a cell is edited, but before the value is set in the record. 
37059          * You can use this to modify the value being set in the field, Return false
37060              * to cancel the change. The edit event object has the following properties <br />
37061              * <ul style="padding:5px;padding-left:16px;">
37062          * <li>editor - This editor</li>
37063              * <li>grid - This grid</li>
37064              * <li>record - The record being edited</li>
37065              * <li>field - The field name being edited</li>
37066              * <li>value - The value being set</li>
37067              * <li>originalValue - The original value for the field, before the edit.</li>
37068              * <li>row - The grid row index</li>
37069              * <li>column - The grid column index</li>
37070              * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
37071              * </ul>
37072              * @param {Object} e An edit event (see above for description)
37073              */
37074             "validateedit" : true
37075         });
37076     this.on("bodyscroll", this.stopEditing,  this);
37077     this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick,  this);
37078 };
37079
37080 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
37081     /**
37082      * @cfg {Number} clicksToEdit
37083      * The number of clicks on a cell required to display the cell's editor (defaults to 2)
37084      */
37085     clicksToEdit: 2,
37086
37087     // private
37088     isEditor : true,
37089     // private
37090     trackMouseOver: false, // causes very odd FF errors
37091
37092     onCellDblClick : function(g, row, col){
37093         this.startEditing(row, col);
37094     },
37095
37096     onEditComplete : function(ed, value, startValue){
37097         this.editing = false;
37098         this.activeEditor = null;
37099         ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
37100         var r = ed.record;
37101         var field = this.colModel.getDataIndex(ed.col);
37102         var e = {
37103             grid: this,
37104             record: r,
37105             field: field,
37106             originalValue: startValue,
37107             value: value,
37108             row: ed.row,
37109             column: ed.col,
37110             cancel:false,
37111             editor: ed
37112         };
37113         var cell = Roo.get(this.view.getCell(ed.row,ed.col));
37114         cell.show();
37115           
37116         if(String(value) !== String(startValue)){
37117             
37118             if(this.fireEvent("validateedit", e) !== false && !e.cancel){
37119                 r.set(field, e.value);
37120                 // if we are dealing with a combo box..
37121                 // then we also set the 'name' colum to be the displayField
37122                 if (ed.field.displayField && ed.field.name) {
37123                     r.set(ed.field.name, ed.field.el.dom.value);
37124                 }
37125                 
37126                 delete e.cancel; //?? why!!!
37127                 this.fireEvent("afteredit", e);
37128             }
37129         } else {
37130             this.fireEvent("afteredit", e); // always fire it!
37131         }
37132         this.view.focusCell(ed.row, ed.col);
37133     },
37134
37135     /**
37136      * Starts editing the specified for the specified row/column
37137      * @param {Number} rowIndex
37138      * @param {Number} colIndex
37139      */
37140     startEditing : function(row, col){
37141         this.stopEditing();
37142         if(this.colModel.isCellEditable(col, row)){
37143             this.view.ensureVisible(row, col, true);
37144           
37145             var r = this.dataSource.getAt(row);
37146             var field = this.colModel.getDataIndex(col);
37147             var cell = Roo.get(this.view.getCell(row,col));
37148             var e = {
37149                 grid: this,
37150                 record: r,
37151                 field: field,
37152                 value: r.data[field],
37153                 row: row,
37154                 column: col,
37155                 cancel:false 
37156             };
37157             if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
37158                 this.editing = true;
37159                 var ed = this.colModel.getCellEditor(col, row);
37160                 
37161                 if (!ed) {
37162                     return;
37163                 }
37164                 if(!ed.rendered){
37165                     ed.render(ed.parentEl || document.body);
37166                 }
37167                 ed.field.reset();
37168                
37169                 cell.hide();
37170                 
37171                 (function(){ // complex but required for focus issues in safari, ie and opera
37172                     ed.row = row;
37173                     ed.col = col;
37174                     ed.record = r;
37175                     ed.on("complete",   this.onEditComplete,        this,       {single: true});
37176                     ed.on("specialkey", this.selModel.onEditorKey,  this.selModel);
37177                     this.activeEditor = ed;
37178                     var v = r.data[field];
37179                     ed.startEdit(this.view.getCell(row, col), v);
37180                     // combo's with 'displayField and name set
37181                     if (ed.field.displayField && ed.field.name) {
37182                         ed.field.el.dom.value = r.data[ed.field.name];
37183                     }
37184                     
37185                     
37186                 }).defer(50, this);
37187             }
37188         }
37189     },
37190         
37191     /**
37192      * Stops any active editing
37193      */
37194     stopEditing : function(){
37195         if(this.activeEditor){
37196             this.activeEditor.completeEdit();
37197         }
37198         this.activeEditor = null;
37199     },
37200         
37201          /**
37202      * Called to get grid's drag proxy text, by default returns this.ddText.
37203      * @return {String}
37204      */
37205     getDragDropText : function(){
37206         var count = this.selModel.getSelectedCell() ? 1 : 0;
37207         return String.format(this.ddText, count, count == 1 ? '' : 's');
37208     }
37209         
37210 });/*
37211  * Based on:
37212  * Ext JS Library 1.1.1
37213  * Copyright(c) 2006-2007, Ext JS, LLC.
37214  *
37215  * Originally Released Under LGPL - original licence link has changed is not relivant.
37216  *
37217  * Fork - LGPL
37218  * <script type="text/javascript">
37219  */
37220
37221 // private - not really -- you end up using it !
37222 // This is a support class used internally by the Grid components
37223
37224 /**
37225  * @class Roo.grid.GridEditor
37226  * @extends Roo.Editor
37227  * Class for creating and editable grid elements.
37228  * @param {Object} config any settings (must include field)
37229  */
37230 Roo.grid.GridEditor = function(field, config){
37231     if (!config && field.field) {
37232         config = field;
37233         field = Roo.factory(config.field, Roo.form);
37234     }
37235     Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
37236     field.monitorTab = false;
37237 };
37238
37239 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
37240     
37241     /**
37242      * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
37243      */
37244     
37245     alignment: "tl-tl",
37246     autoSize: "width",
37247     hideEl : false,
37248     cls: "x-small-editor x-grid-editor",
37249     shim:false,
37250     shadow:"frame"
37251 });/*
37252  * Based on:
37253  * Ext JS Library 1.1.1
37254  * Copyright(c) 2006-2007, Ext JS, LLC.
37255  *
37256  * Originally Released Under LGPL - original licence link has changed is not relivant.
37257  *
37258  * Fork - LGPL
37259  * <script type="text/javascript">
37260  */
37261   
37262
37263   
37264 Roo.grid.PropertyRecord = Roo.data.Record.create([
37265     {name:'name',type:'string'},  'value'
37266 ]);
37267
37268
37269 Roo.grid.PropertyStore = function(grid, source){
37270     this.grid = grid;
37271     this.store = new Roo.data.Store({
37272         recordType : Roo.grid.PropertyRecord
37273     });
37274     this.store.on('update', this.onUpdate,  this);
37275     if(source){
37276         this.setSource(source);
37277     }
37278     Roo.grid.PropertyStore.superclass.constructor.call(this);
37279 };
37280
37281
37282
37283 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
37284     setSource : function(o){
37285         this.source = o;
37286         this.store.removeAll();
37287         var data = [];
37288         for(var k in o){
37289             if(this.isEditableValue(o[k])){
37290                 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
37291             }
37292         }
37293         this.store.loadRecords({records: data}, {}, true);
37294     },
37295
37296     onUpdate : function(ds, record, type){
37297         if(type == Roo.data.Record.EDIT){
37298             var v = record.data['value'];
37299             var oldValue = record.modified['value'];
37300             if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
37301                 this.source[record.id] = v;
37302                 record.commit();
37303                 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
37304             }else{
37305                 record.reject();
37306             }
37307         }
37308     },
37309
37310     getProperty : function(row){
37311        return this.store.getAt(row);
37312     },
37313
37314     isEditableValue: function(val){
37315         if(val && val instanceof Date){
37316             return true;
37317         }else if(typeof val == 'object' || typeof val == 'function'){
37318             return false;
37319         }
37320         return true;
37321     },
37322
37323     setValue : function(prop, value){
37324         this.source[prop] = value;
37325         this.store.getById(prop).set('value', value);
37326     },
37327
37328     getSource : function(){
37329         return this.source;
37330     }
37331 });
37332
37333 Roo.grid.PropertyColumnModel = function(grid, store){
37334     this.grid = grid;
37335     var g = Roo.grid;
37336     g.PropertyColumnModel.superclass.constructor.call(this, [
37337         {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
37338         {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
37339     ]);
37340     this.store = store;
37341     this.bselect = Roo.DomHelper.append(document.body, {
37342         tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
37343             {tag: 'option', value: 'true', html: 'true'},
37344             {tag: 'option', value: 'false', html: 'false'}
37345         ]
37346     });
37347     Roo.id(this.bselect);
37348     var f = Roo.form;
37349     this.editors = {
37350         'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
37351         'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
37352         'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
37353         'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
37354         'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
37355     };
37356     this.renderCellDelegate = this.renderCell.createDelegate(this);
37357     this.renderPropDelegate = this.renderProp.createDelegate(this);
37358 };
37359
37360 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
37361     
37362     
37363     nameText : 'Name',
37364     valueText : 'Value',
37365     
37366     dateFormat : 'm/j/Y',
37367     
37368     
37369     renderDate : function(dateVal){
37370         return dateVal.dateFormat(this.dateFormat);
37371     },
37372
37373     renderBool : function(bVal){
37374         return bVal ? 'true' : 'false';
37375     },
37376
37377     isCellEditable : function(colIndex, rowIndex){
37378         return colIndex == 1;
37379     },
37380
37381     getRenderer : function(col){
37382         return col == 1 ?
37383             this.renderCellDelegate : this.renderPropDelegate;
37384     },
37385
37386     renderProp : function(v){
37387         return this.getPropertyName(v);
37388     },
37389
37390     renderCell : function(val){
37391         var rv = val;
37392         if(val instanceof Date){
37393             rv = this.renderDate(val);
37394         }else if(typeof val == 'boolean'){
37395             rv = this.renderBool(val);
37396         }
37397         return Roo.util.Format.htmlEncode(rv);
37398     },
37399
37400     getPropertyName : function(name){
37401         var pn = this.grid.propertyNames;
37402         return pn && pn[name] ? pn[name] : name;
37403     },
37404
37405     getCellEditor : function(colIndex, rowIndex){
37406         var p = this.store.getProperty(rowIndex);
37407         var n = p.data['name'], val = p.data['value'];
37408         
37409         if(typeof(this.grid.customEditors[n]) == 'string'){
37410             return this.editors[this.grid.customEditors[n]];
37411         }
37412         if(typeof(this.grid.customEditors[n]) != 'undefined'){
37413             return this.grid.customEditors[n];
37414         }
37415         if(val instanceof Date){
37416             return this.editors['date'];
37417         }else if(typeof val == 'number'){
37418             return this.editors['number'];
37419         }else if(typeof val == 'boolean'){
37420             return this.editors['boolean'];
37421         }else{
37422             return this.editors['string'];
37423         }
37424     }
37425 });
37426
37427 /**
37428  * @class Roo.grid.PropertyGrid
37429  * @extends Roo.grid.EditorGrid
37430  * This class represents the  interface of a component based property grid control.
37431  * <br><br>Usage:<pre><code>
37432  var grid = new Roo.grid.PropertyGrid("my-container-id", {
37433       
37434  });
37435  // set any options
37436  grid.render();
37437  * </code></pre>
37438   
37439  * @constructor
37440  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
37441  * The container MUST have some type of size defined for the grid to fill. The container will be
37442  * automatically set to position relative if it isn't already.
37443  * @param {Object} config A config object that sets properties on this grid.
37444  */
37445 Roo.grid.PropertyGrid = function(container, config){
37446     config = config || {};
37447     var store = new Roo.grid.PropertyStore(this);
37448     this.store = store;
37449     var cm = new Roo.grid.PropertyColumnModel(this, store);
37450     store.store.sort('name', 'ASC');
37451     Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
37452         ds: store.store,
37453         cm: cm,
37454         enableColLock:false,
37455         enableColumnMove:false,
37456         stripeRows:false,
37457         trackMouseOver: false,
37458         clicksToEdit:1
37459     }, config));
37460     this.getGridEl().addClass('x-props-grid');
37461     this.lastEditRow = null;
37462     this.on('columnresize', this.onColumnResize, this);
37463     this.addEvents({
37464          /**
37465              * @event beforepropertychange
37466              * Fires before a property changes (return false to stop?)
37467              * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
37468              * @param {String} id Record Id
37469              * @param {String} newval New Value
37470          * @param {String} oldval Old Value
37471              */
37472         "beforepropertychange": true,
37473         /**
37474              * @event propertychange
37475              * Fires after a property changes
37476              * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
37477              * @param {String} id Record Id
37478              * @param {String} newval New Value
37479          * @param {String} oldval Old Value
37480              */
37481         "propertychange": true
37482     });
37483     this.customEditors = this.customEditors || {};
37484 };
37485 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
37486     
37487      /**
37488      * @cfg {Object} customEditors map of colnames=> custom editors.
37489      * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
37490      * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
37491      * false disables editing of the field.
37492          */
37493     
37494       /**
37495      * @cfg {Object} propertyNames map of property Names to their displayed value
37496          */
37497     
37498     render : function(){
37499         Roo.grid.PropertyGrid.superclass.render.call(this);
37500         this.autoSize.defer(100, this);
37501     },
37502
37503     autoSize : function(){
37504         Roo.grid.PropertyGrid.superclass.autoSize.call(this);
37505         if(this.view){
37506             this.view.fitColumns();
37507         }
37508     },
37509
37510     onColumnResize : function(){
37511         this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
37512         this.autoSize();
37513     },
37514     /**
37515      * Sets the data for the Grid
37516      * accepts a Key => Value object of all the elements avaiable.
37517      * @param {Object} data  to appear in grid.
37518      */
37519     setSource : function(source){
37520         this.store.setSource(source);
37521         //this.autoSize();
37522     },
37523     /**
37524      * Gets all the data from the grid.
37525      * @return {Object} data  data stored in grid
37526      */
37527     getSource : function(){
37528         return this.store.getSource();
37529     }
37530 });/*
37531   
37532  * Licence LGPL
37533  
37534  */
37535  
37536 /**
37537  * @class Roo.grid.Calendar
37538  * @extends Roo.grid.Grid
37539  * This class extends the Grid to provide a calendar widget
37540  * <br><br>Usage:<pre><code>
37541  var grid = new Roo.grid.Calendar("my-container-id", {
37542      ds: myDataStore,
37543      cm: myColModel,
37544      selModel: mySelectionModel,
37545      autoSizeColumns: true,
37546      monitorWindowResize: false,
37547      trackMouseOver: true
37548      eventstore : real data store..
37549  });
37550  // set any options
37551  grid.render();
37552   
37553   * @constructor
37554  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
37555  * The container MUST have some type of size defined for the grid to fill. The container will be
37556  * automatically set to position relative if it isn't already.
37557  * @param {Object} config A config object that sets properties on this grid.
37558  */
37559 Roo.grid.Calendar = function(container, config){
37560         // initialize the container
37561         this.container = Roo.get(container);
37562         this.container.update("");
37563         this.container.setStyle("overflow", "hidden");
37564     this.container.addClass('x-grid-container');
37565
37566     this.id = this.container.id;
37567
37568     Roo.apply(this, config);
37569     // check and correct shorthanded configs
37570     
37571     var rows = [];
37572     var d =1;
37573     for (var r = 0;r < 6;r++) {
37574         
37575         rows[r]=[];
37576         for (var c =0;c < 7;c++) {
37577             rows[r][c]= '';
37578         }
37579     }
37580     if (this.eventStore) {
37581         this.eventStore= Roo.factory(this.eventStore, Roo.data);
37582         this.eventStore.on('load',this.onLoad, this);
37583         this.eventStore.on('beforeload',this.clearEvents, this);
37584          
37585     }
37586     
37587     this.dataSource = new Roo.data.Store({
37588             proxy: new Roo.data.MemoryProxy(rows),
37589             reader: new Roo.data.ArrayReader({}, [
37590                    'weekday0', 'weekday1', 'weekday2', 'weekday3', 'weekday4', 'weekday5', 'weekday6' ])
37591     });
37592
37593     this.dataSource.load();
37594     this.ds = this.dataSource;
37595     this.ds.xmodule = this.xmodule || false;
37596     
37597     
37598     var cellRender = function(v,x,r)
37599     {
37600         return String.format(
37601             '<div class="fc-day  fc-widget-content"><div>' +
37602                 '<div class="fc-event-container"></div>' +
37603                 '<div class="fc-day-number">{0}</div>'+
37604                 
37605                 '<div class="fc-day-content"><div style="position:relative"></div></div>' +
37606             '</div></div>', v);
37607     
37608     }
37609     
37610     
37611     this.colModel = new Roo.grid.ColumnModel( [
37612         {
37613             xtype: 'ColumnModel',
37614             xns: Roo.grid,
37615             dataIndex : 'weekday0',
37616             header : 'Sunday',
37617             renderer : cellRender
37618         },
37619         {
37620             xtype: 'ColumnModel',
37621             xns: Roo.grid,
37622             dataIndex : 'weekday1',
37623             header : 'Monday',
37624             renderer : cellRender
37625         },
37626         {
37627             xtype: 'ColumnModel',
37628             xns: Roo.grid,
37629             dataIndex : 'weekday2',
37630             header : 'Tuesday',
37631             renderer : cellRender
37632         },
37633         {
37634             xtype: 'ColumnModel',
37635             xns: Roo.grid,
37636             dataIndex : 'weekday3',
37637             header : 'Wednesday',
37638             renderer : cellRender
37639         },
37640         {
37641             xtype: 'ColumnModel',
37642             xns: Roo.grid,
37643             dataIndex : 'weekday4',
37644             header : 'Thursday',
37645             renderer : cellRender
37646         },
37647         {
37648             xtype: 'ColumnModel',
37649             xns: Roo.grid,
37650             dataIndex : 'weekday5',
37651             header : 'Friday',
37652             renderer : cellRender
37653         },
37654         {
37655             xtype: 'ColumnModel',
37656             xns: Roo.grid,
37657             dataIndex : 'weekday6',
37658             header : 'Saturday',
37659             renderer : cellRender
37660         }
37661     ]);
37662     this.cm = this.colModel;
37663     this.cm.xmodule = this.xmodule || false;
37664  
37665         
37666           
37667     //this.selModel = new Roo.grid.CellSelectionModel();
37668     //this.sm = this.selModel;
37669     //this.selModel.init(this);
37670     
37671     
37672     if(this.width){
37673         this.container.setWidth(this.width);
37674     }
37675
37676     if(this.height){
37677         this.container.setHeight(this.height);
37678     }
37679     /** @private */
37680         this.addEvents({
37681         // raw events
37682         /**
37683          * @event click
37684          * The raw click event for the entire grid.
37685          * @param {Roo.EventObject} e
37686          */
37687         "click" : true,
37688         /**
37689          * @event dblclick
37690          * The raw dblclick event for the entire grid.
37691          * @param {Roo.EventObject} e
37692          */
37693         "dblclick" : true,
37694         /**
37695          * @event contextmenu
37696          * The raw contextmenu event for the entire grid.
37697          * @param {Roo.EventObject} e
37698          */
37699         "contextmenu" : true,
37700         /**
37701          * @event mousedown
37702          * The raw mousedown event for the entire grid.
37703          * @param {Roo.EventObject} e
37704          */
37705         "mousedown" : true,
37706         /**
37707          * @event mouseup
37708          * The raw mouseup event for the entire grid.
37709          * @param {Roo.EventObject} e
37710          */
37711         "mouseup" : true,
37712         /**
37713          * @event mouseover
37714          * The raw mouseover event for the entire grid.
37715          * @param {Roo.EventObject} e
37716          */
37717         "mouseover" : true,
37718         /**
37719          * @event mouseout
37720          * The raw mouseout event for the entire grid.
37721          * @param {Roo.EventObject} e
37722          */
37723         "mouseout" : true,
37724         /**
37725          * @event keypress
37726          * The raw keypress event for the entire grid.
37727          * @param {Roo.EventObject} e
37728          */
37729         "keypress" : true,
37730         /**
37731          * @event keydown
37732          * The raw keydown event for the entire grid.
37733          * @param {Roo.EventObject} e
37734          */
37735         "keydown" : true,
37736
37737         // custom events
37738
37739         /**
37740          * @event cellclick
37741          * Fires when a cell is clicked
37742          * @param {Grid} this
37743          * @param {Number} rowIndex
37744          * @param {Number} columnIndex
37745          * @param {Roo.EventObject} e
37746          */
37747         "cellclick" : true,
37748         /**
37749          * @event celldblclick
37750          * Fires when a cell is double clicked
37751          * @param {Grid} this
37752          * @param {Number} rowIndex
37753          * @param {Number} columnIndex
37754          * @param {Roo.EventObject} e
37755          */
37756         "celldblclick" : true,
37757         /**
37758          * @event rowclick
37759          * Fires when a row is clicked
37760          * @param {Grid} this
37761          * @param {Number} rowIndex
37762          * @param {Roo.EventObject} e
37763          */
37764         "rowclick" : true,
37765         /**
37766          * @event rowdblclick
37767          * Fires when a row is double clicked
37768          * @param {Grid} this
37769          * @param {Number} rowIndex
37770          * @param {Roo.EventObject} e
37771          */
37772         "rowdblclick" : true,
37773         /**
37774          * @event headerclick
37775          * Fires when a header is clicked
37776          * @param {Grid} this
37777          * @param {Number} columnIndex
37778          * @param {Roo.EventObject} e
37779          */
37780         "headerclick" : true,
37781         /**
37782          * @event headerdblclick
37783          * Fires when a header cell is double clicked
37784          * @param {Grid} this
37785          * @param {Number} columnIndex
37786          * @param {Roo.EventObject} e
37787          */
37788         "headerdblclick" : true,
37789         /**
37790          * @event rowcontextmenu
37791          * Fires when a row is right clicked
37792          * @param {Grid} this
37793          * @param {Number} rowIndex
37794          * @param {Roo.EventObject} e
37795          */
37796         "rowcontextmenu" : true,
37797         /**
37798          * @event cellcontextmenu
37799          * Fires when a cell is right clicked
37800          * @param {Grid} this
37801          * @param {Number} rowIndex
37802          * @param {Number} cellIndex
37803          * @param {Roo.EventObject} e
37804          */
37805          "cellcontextmenu" : true,
37806         /**
37807          * @event headercontextmenu
37808          * Fires when a header is right clicked
37809          * @param {Grid} this
37810          * @param {Number} columnIndex
37811          * @param {Roo.EventObject} e
37812          */
37813         "headercontextmenu" : true,
37814         /**
37815          * @event bodyscroll
37816          * Fires when the body element is scrolled
37817          * @param {Number} scrollLeft
37818          * @param {Number} scrollTop
37819          */
37820         "bodyscroll" : true,
37821         /**
37822          * @event columnresize
37823          * Fires when the user resizes a column
37824          * @param {Number} columnIndex
37825          * @param {Number} newSize
37826          */
37827         "columnresize" : true,
37828         /**
37829          * @event columnmove
37830          * Fires when the user moves a column
37831          * @param {Number} oldIndex
37832          * @param {Number} newIndex
37833          */
37834         "columnmove" : true,
37835         /**
37836          * @event startdrag
37837          * Fires when row(s) start being dragged
37838          * @param {Grid} this
37839          * @param {Roo.GridDD} dd The drag drop object
37840          * @param {event} e The raw browser event
37841          */
37842         "startdrag" : true,
37843         /**
37844          * @event enddrag
37845          * Fires when a drag operation is complete
37846          * @param {Grid} this
37847          * @param {Roo.GridDD} dd The drag drop object
37848          * @param {event} e The raw browser event
37849          */
37850         "enddrag" : true,
37851         /**
37852          * @event dragdrop
37853          * Fires when dragged row(s) are dropped on a valid DD target
37854          * @param {Grid} this
37855          * @param {Roo.GridDD} dd The drag drop object
37856          * @param {String} targetId The target drag drop object
37857          * @param {event} e The raw browser event
37858          */
37859         "dragdrop" : true,
37860         /**
37861          * @event dragover
37862          * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
37863          * @param {Grid} this
37864          * @param {Roo.GridDD} dd The drag drop object
37865          * @param {String} targetId The target drag drop object
37866          * @param {event} e The raw browser event
37867          */
37868         "dragover" : true,
37869         /**
37870          * @event dragenter
37871          *  Fires when the dragged row(s) first cross another DD target while being dragged
37872          * @param {Grid} this
37873          * @param {Roo.GridDD} dd The drag drop object
37874          * @param {String} targetId The target drag drop object
37875          * @param {event} e The raw browser event
37876          */
37877         "dragenter" : true,
37878         /**
37879          * @event dragout
37880          * Fires when the dragged row(s) leave another DD target while being dragged
37881          * @param {Grid} this
37882          * @param {Roo.GridDD} dd The drag drop object
37883          * @param {String} targetId The target drag drop object
37884          * @param {event} e The raw browser event
37885          */
37886         "dragout" : true,
37887         /**
37888          * @event rowclass
37889          * Fires when a row is rendered, so you can change add a style to it.
37890          * @param {GridView} gridview   The grid view
37891          * @param {Object} rowcfg   contains record  rowIndex and rowClass - set rowClass to add a style.
37892          */
37893         'rowclass' : true,
37894
37895         /**
37896          * @event render
37897          * Fires when the grid is rendered
37898          * @param {Grid} grid
37899          */
37900         'render' : true,
37901             /**
37902              * @event select
37903              * Fires when a date is selected
37904              * @param {DatePicker} this
37905              * @param {Date} date The selected date
37906              */
37907         'select': true,
37908         /**
37909              * @event monthchange
37910              * Fires when the displayed month changes 
37911              * @param {DatePicker} this
37912              * @param {Date} date The selected month
37913              */
37914         'monthchange': true,
37915         /**
37916              * @event evententer
37917              * Fires when mouse over an event
37918              * @param {Calendar} this
37919              * @param {event} Event
37920              */
37921         'evententer': true,
37922         /**
37923              * @event eventleave
37924              * Fires when the mouse leaves an
37925              * @param {Calendar} this
37926              * @param {event}
37927              */
37928         'eventleave': true,
37929         /**
37930              * @event eventclick
37931              * Fires when the mouse click an
37932              * @param {Calendar} this
37933              * @param {event}
37934              */
37935         'eventclick': true,
37936         /**
37937              * @event eventrender
37938              * Fires before each cell is rendered, so you can modify the contents, like cls / title / qtip
37939              * @param {Calendar} this
37940              * @param {data} data to be modified
37941              */
37942         'eventrender': true
37943         
37944     });
37945
37946     Roo.grid.Grid.superclass.constructor.call(this);
37947     this.on('render', function() {
37948         this.view.el.addClass('x-grid-cal'); 
37949         
37950         (function() { this.setDate(new Date()); }).defer(100,this); //default today..
37951
37952     },this);
37953     
37954     if (!Roo.grid.Calendar.style) {
37955         Roo.grid.Calendar.style = Roo.util.CSS.createStyleSheet({
37956             
37957             
37958             '.x-grid-cal .x-grid-col' :  {
37959                 height: 'auto !important',
37960                 'vertical-align': 'top'
37961             },
37962             '.x-grid-cal  .fc-event-hori' : {
37963                 height: '14px'
37964             }
37965              
37966             
37967         }, Roo.id());
37968     }
37969
37970     
37971     
37972 };
37973 Roo.extend(Roo.grid.Calendar, Roo.grid.Grid, {
37974     /**
37975      * @cfg {Store} eventStore The store that loads events.
37976      */
37977     eventStore : 25,
37978
37979      
37980     activeDate : false,
37981     startDay : 0,
37982     autoWidth : true,
37983     monitorWindowResize : false,
37984
37985     
37986     resizeColumns : function() {
37987         var col = (this.view.el.getWidth() / 7) - 3;
37988         // loop through cols, and setWidth
37989         for(var i =0 ; i < 7 ; i++){
37990             this.cm.setColumnWidth(i, col);
37991         }
37992     },
37993      setDate :function(date) {
37994         
37995         Roo.log('setDate?');
37996         
37997         this.resizeColumns();
37998         var vd = this.activeDate;
37999         this.activeDate = date;
38000 //        if(vd && this.el){
38001 //            var t = date.getTime();
38002 //            if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
38003 //                Roo.log('using add remove');
38004 //                
38005 //                this.fireEvent('monthchange', this, date);
38006 //                
38007 //                this.cells.removeClass("fc-state-highlight");
38008 //                this.cells.each(function(c){
38009 //                   if(c.dateValue == t){
38010 //                       c.addClass("fc-state-highlight");
38011 //                       setTimeout(function(){
38012 //                            try{c.dom.firstChild.focus();}catch(e){}
38013 //                       }, 50);
38014 //                       return false;
38015 //                   }
38016 //                   return true;
38017 //                });
38018 //                return;
38019 //            }
38020 //        }
38021         
38022         var days = date.getDaysInMonth();
38023         
38024         var firstOfMonth = date.getFirstDateOfMonth();
38025         var startingPos = firstOfMonth.getDay()-this.startDay;
38026         
38027         if(startingPos < this.startDay){
38028             startingPos += 7;
38029         }
38030         
38031         var pm = date.add(Date.MONTH, -1);
38032         var prevStart = pm.getDaysInMonth()-startingPos;
38033 //        
38034         
38035         
38036         this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
38037         
38038         this.textNodes = this.view.el.query('.x-grid-row .x-grid-col .x-grid-cell-text');
38039         //this.cells.addClassOnOver('fc-state-hover');
38040         
38041         var cells = this.cells.elements;
38042         var textEls = this.textNodes;
38043         
38044         //Roo.each(cells, function(cell){
38045         //    cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
38046         //});
38047         
38048         days += startingPos;
38049
38050         // convert everything to numbers so it's fast
38051         var day = 86400000;
38052         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
38053         //Roo.log(d);
38054         //Roo.log(pm);
38055         //Roo.log(prevStart);
38056         
38057         var today = new Date().clearTime().getTime();
38058         var sel = date.clearTime().getTime();
38059         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
38060         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
38061         var ddMatch = this.disabledDatesRE;
38062         var ddText = this.disabledDatesText;
38063         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
38064         var ddaysText = this.disabledDaysText;
38065         var format = this.format;
38066         
38067         var setCellClass = function(cal, cell){
38068             
38069             //Roo.log('set Cell Class');
38070             cell.title = "";
38071             var t = d.getTime();
38072             
38073             //Roo.log(d);
38074             
38075             
38076             cell.dateValue = t;
38077             if(t == today){
38078                 cell.className += " fc-today";
38079                 cell.className += " fc-state-highlight";
38080                 cell.title = cal.todayText;
38081             }
38082             if(t == sel){
38083                 // disable highlight in other month..
38084                 cell.className += " fc-state-highlight";
38085                 
38086             }
38087             // disabling
38088             if(t < min) {
38089                 //cell.className = " fc-state-disabled";
38090                 cell.title = cal.minText;
38091                 return;
38092             }
38093             if(t > max) {
38094                 //cell.className = " fc-state-disabled";
38095                 cell.title = cal.maxText;
38096                 return;
38097             }
38098             if(ddays){
38099                 if(ddays.indexOf(d.getDay()) != -1){
38100                     // cell.title = ddaysText;
38101                    // cell.className = " fc-state-disabled";
38102                 }
38103             }
38104             if(ddMatch && format){
38105                 var fvalue = d.dateFormat(format);
38106                 if(ddMatch.test(fvalue)){
38107                     cell.title = ddText.replace("%0", fvalue);
38108                    cell.className = " fc-state-disabled";
38109                 }
38110             }
38111             
38112             if (!cell.initialClassName) {
38113                 cell.initialClassName = cell.dom.className;
38114             }
38115             
38116             cell.dom.className = cell.initialClassName  + ' ' +  cell.className;
38117         };
38118
38119         var i = 0;
38120         
38121         for(; i < startingPos; i++) {
38122             cells[i].dayName =  (++prevStart);
38123             Roo.log(textEls[i]);
38124             d.setDate(d.getDate()+1);
38125             
38126             //cells[i].className = "fc-past fc-other-month";
38127             setCellClass(this, cells[i]);
38128         }
38129         
38130         var intDay = 0;
38131         
38132         for(; i < days; i++){
38133             intDay = i - startingPos + 1;
38134             cells[i].dayName =  (intDay);
38135             d.setDate(d.getDate()+1);
38136             
38137             cells[i].className = ''; // "x-date-active";
38138             setCellClass(this, cells[i]);
38139         }
38140         var extraDays = 0;
38141         
38142         for(; i < 42; i++) {
38143             //textEls[i].innerHTML = (++extraDays);
38144             
38145             d.setDate(d.getDate()+1);
38146             cells[i].dayName = (++extraDays);
38147             cells[i].className = "fc-future fc-other-month";
38148             setCellClass(this, cells[i]);
38149         }
38150         
38151         //this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
38152         
38153         var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
38154         
38155         // this will cause all the cells to mis
38156         var rows= [];
38157         var i =0;
38158         for (var r = 0;r < 6;r++) {
38159             for (var c =0;c < 7;c++) {
38160                 this.ds.getAt(r).set('weekday' + c ,cells[i++].dayName );
38161             }    
38162         }
38163         
38164         this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
38165         for(i=0;i<cells.length;i++) {
38166             
38167             this.cells.elements[i].dayName = cells[i].dayName ;
38168             this.cells.elements[i].className = cells[i].className;
38169             this.cells.elements[i].initialClassName = cells[i].initialClassName ;
38170             this.cells.elements[i].title = cells[i].title ;
38171             this.cells.elements[i].dateValue = cells[i].dateValue ;
38172         }
38173         
38174         
38175         
38176         
38177         //this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
38178         //this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
38179         
38180         ////if(totalRows != 6){
38181             //this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
38182            // this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
38183        // }
38184         
38185         this.fireEvent('monthchange', this, date);
38186         
38187         
38188     },
38189  /**
38190      * Returns the grid's SelectionModel.
38191      * @return {SelectionModel}
38192      */
38193     getSelectionModel : function(){
38194         if(!this.selModel){
38195             this.selModel = new Roo.grid.CellSelectionModel();
38196         }
38197         return this.selModel;
38198     },
38199
38200     load: function() {
38201         this.eventStore.load()
38202         
38203         
38204         
38205     },
38206     
38207     findCell : function(dt) {
38208         dt = dt.clearTime().getTime();
38209         var ret = false;
38210         this.cells.each(function(c){
38211             //Roo.log("check " +c.dateValue + '?=' + dt);
38212             if(c.dateValue == dt){
38213                 ret = c;
38214                 return false;
38215             }
38216             return true;
38217         });
38218         
38219         return ret;
38220     },
38221     
38222     findCells : function(rec) {
38223         var s = rec.data.start_dt.clone().clearTime().getTime();
38224        // Roo.log(s);
38225         var e= rec.data.end_dt.clone().clearTime().getTime();
38226        // Roo.log(e);
38227         var ret = [];
38228         this.cells.each(function(c){
38229              ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
38230             
38231             if(c.dateValue > e){
38232                 return ;
38233             }
38234             if(c.dateValue < s){
38235                 return ;
38236             }
38237             ret.push(c);
38238         });
38239         
38240         return ret;    
38241     },
38242     
38243     findBestRow: function(cells)
38244     {
38245         var ret = 0;
38246         
38247         for (var i =0 ; i < cells.length;i++) {
38248             ret  = Math.max(cells[i].rows || 0,ret);
38249         }
38250         return ret;
38251         
38252     },
38253     
38254     
38255     addItem : function(rec)
38256     {
38257         // look for vertical location slot in
38258         var cells = this.findCells(rec);
38259         
38260         rec.row = this.findBestRow(cells);
38261         
38262         // work out the location.
38263         
38264         var crow = false;
38265         var rows = [];
38266         for(var i =0; i < cells.length; i++) {
38267             if (!crow) {
38268                 crow = {
38269                     start : cells[i],
38270                     end :  cells[i]
38271                 };
38272                 continue;
38273             }
38274             if (crow.start.getY() == cells[i].getY()) {
38275                 // on same row.
38276                 crow.end = cells[i];
38277                 continue;
38278             }
38279             // different row.
38280             rows.push(crow);
38281             crow = {
38282                 start: cells[i],
38283                 end : cells[i]
38284             };
38285             
38286         }
38287         
38288         rows.push(crow);
38289         rec.els = [];
38290         rec.rows = rows;
38291         rec.cells = cells;
38292         for (var i = 0; i < cells.length;i++) {
38293             cells[i].rows = Math.max(cells[i].rows || 0 , rec.row + 1 );
38294             
38295         }
38296         
38297         
38298     },
38299     
38300     clearEvents: function() {
38301         
38302         if (!this.eventStore.getCount()) {
38303             return;
38304         }
38305         // reset number of rows in cells.
38306         Roo.each(this.cells.elements, function(c){
38307             c.rows = 0;
38308         });
38309         
38310         this.eventStore.each(function(e) {
38311             this.clearEvent(e);
38312         },this);
38313         
38314     },
38315     
38316     clearEvent : function(ev)
38317     {
38318         if (ev.els) {
38319             Roo.each(ev.els, function(el) {
38320                 el.un('mouseenter' ,this.onEventEnter, this);
38321                 el.un('mouseleave' ,this.onEventLeave, this);
38322                 el.remove();
38323             },this);
38324             ev.els = [];
38325         }
38326     },
38327     
38328     
38329     renderEvent : function(ev,ctr) {
38330         if (!ctr) {
38331              ctr = this.view.el.select('.fc-event-container',true).first();
38332         }
38333         
38334          
38335         this.clearEvent(ev);
38336             //code
38337        
38338         
38339         
38340         ev.els = [];
38341         var cells = ev.cells;
38342         var rows = ev.rows;
38343         this.fireEvent('eventrender', this, ev);
38344         
38345         for(var i =0; i < rows.length; i++) {
38346             
38347             cls = '';
38348             if (i == 0) {
38349                 cls += ' fc-event-start';
38350             }
38351             if ((i+1) == rows.length) {
38352                 cls += ' fc-event-end';
38353             }
38354             
38355             //Roo.log(ev.data);
38356             // how many rows should it span..
38357             var cg = this.eventTmpl.append(ctr,Roo.apply({
38358                 fccls : cls
38359                 
38360             }, ev.data) , true);
38361             
38362             
38363             cg.on('mouseenter' ,this.onEventEnter, this, ev);
38364             cg.on('mouseleave' ,this.onEventLeave, this, ev);
38365             cg.on('click', this.onEventClick, this, ev);
38366             
38367             ev.els.push(cg);
38368             
38369             var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
38370             var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
38371             //Roo.log(cg);
38372              
38373             cg.setXY([sbox.x +2, sbox.y +(ev.row * 20)]);    
38374             cg.setWidth(ebox.right - sbox.x -2);
38375         }
38376     },
38377     
38378     renderEvents: function()
38379     {   
38380         // first make sure there is enough space..
38381         
38382         if (!this.eventTmpl) {
38383             this.eventTmpl = new Roo.Template(
38384                 '<div class="roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable {fccls} {cls}"  style="position: absolute" unselectable="on">' +
38385                     '<div class="fc-event-inner">' +
38386                         '<span class="fc-event-time">{time}</span>' +
38387                         '<span class="fc-event-title" qtip="{qtip}">{title}</span>' +
38388                     '</div>' +
38389                     '<div class="ui-resizable-heandle ui-resizable-e">&nbsp;&nbsp;&nbsp;</div>' +
38390                 '</div>'
38391             );
38392                 
38393         }
38394                
38395         
38396         
38397         this.cells.each(function(c) {
38398             //Roo.log(c.select('.fc-day-content div',true).first());
38399             c.select('.fc-day-content div',true).first().setHeight(Math.max(34, (c.rows || 1) * 20));
38400         });
38401         
38402         var ctr = this.view.el.select('.fc-event-container',true).first();
38403         
38404         var cls;
38405         this.eventStore.each(function(ev){
38406             
38407             this.renderEvent(ev);
38408              
38409              
38410         }, this);
38411         this.view.layout();
38412         
38413     },
38414     
38415     onEventEnter: function (e, el,event,d) {
38416         this.fireEvent('evententer', this, el, event);
38417     },
38418     
38419     onEventLeave: function (e, el,event,d) {
38420         this.fireEvent('eventleave', this, el, event);
38421     },
38422     
38423     onEventClick: function (e, el,event,d) {
38424         this.fireEvent('eventclick', this, el, event);
38425     },
38426     
38427     onMonthChange: function () {
38428         this.store.load();
38429     },
38430     
38431     onLoad: function () {
38432         
38433         //Roo.log('calendar onload');
38434 //         
38435         if(this.eventStore.getCount() > 0){
38436             
38437            
38438             
38439             this.eventStore.each(function(d){
38440                 
38441                 
38442                 // FIXME..
38443                 var add =   d.data;
38444                 if (typeof(add.end_dt) == 'undefined')  {
38445                     Roo.log("Missing End time in calendar data: ");
38446                     Roo.log(d);
38447                     return;
38448                 }
38449                 if (typeof(add.start_dt) == 'undefined')  {
38450                     Roo.log("Missing Start time in calendar data: ");
38451                     Roo.log(d);
38452                     return;
38453                 }
38454                 add.start_dt = typeof(add.start_dt) == 'string' ? Date.parseDate(add.start_dt,'Y-m-d H:i:s') : add.start_dt,
38455                 add.end_dt = typeof(add.end_dt) == 'string' ? Date.parseDate(add.end_dt,'Y-m-d H:i:s') : add.end_dt,
38456                 add.id = add.id || d.id;
38457                 add.title = add.title || '??';
38458                 
38459                 this.addItem(d);
38460                 
38461              
38462             },this);
38463         }
38464         
38465         this.renderEvents();
38466     }
38467     
38468
38469 });
38470 /*
38471  grid : {
38472                 xtype: 'Grid',
38473                 xns: Roo.grid,
38474                 listeners : {
38475                     render : function ()
38476                     {
38477                         _this.grid = this;
38478                         
38479                         if (!this.view.el.hasClass('course-timesheet')) {
38480                             this.view.el.addClass('course-timesheet');
38481                         }
38482                         if (this.tsStyle) {
38483                             this.ds.load({});
38484                             return; 
38485                         }
38486                         Roo.log('width');
38487                         Roo.log(_this.grid.view.el.getWidth());
38488                         
38489                         
38490                         this.tsStyle =  Roo.util.CSS.createStyleSheet({
38491                             '.course-timesheet .x-grid-row' : {
38492                                 height: '80px'
38493                             },
38494                             '.x-grid-row td' : {
38495                                 'vertical-align' : 0
38496                             },
38497                             '.course-edit-link' : {
38498                                 'color' : 'blue',
38499                                 'text-overflow' : 'ellipsis',
38500                                 'overflow' : 'hidden',
38501                                 'white-space' : 'nowrap',
38502                                 'cursor' : 'pointer'
38503                             },
38504                             '.sub-link' : {
38505                                 'color' : 'green'
38506                             },
38507                             '.de-act-sup-link' : {
38508                                 'color' : 'purple',
38509                                 'text-decoration' : 'line-through'
38510                             },
38511                             '.de-act-link' : {
38512                                 'color' : 'red',
38513                                 'text-decoration' : 'line-through'
38514                             },
38515                             '.course-timesheet .course-highlight' : {
38516                                 'border-top-style': 'dashed !important',
38517                                 'border-bottom-bottom': 'dashed !important'
38518                             },
38519                             '.course-timesheet .course-item' : {
38520                                 'font-family'   : 'tahoma, arial, helvetica',
38521                                 'font-size'     : '11px',
38522                                 'overflow'      : 'hidden',
38523                                 'padding-left'  : '10px',
38524                                 'padding-right' : '10px',
38525                                 'padding-top' : '10px' 
38526                             }
38527                             
38528                         }, Roo.id());
38529                                 this.ds.load({});
38530                     }
38531                 },
38532                 autoWidth : true,
38533                 monitorWindowResize : false,
38534                 cellrenderer : function(v,x,r)
38535                 {
38536                     return v;
38537                 },
38538                 sm : {
38539                     xtype: 'CellSelectionModel',
38540                     xns: Roo.grid
38541                 },
38542                 dataSource : {
38543                     xtype: 'Store',
38544                     xns: Roo.data,
38545                     listeners : {
38546                         beforeload : function (_self, options)
38547                         {
38548                             options.params = options.params || {};
38549                             options.params._month = _this.monthField.getValue();
38550                             options.params.limit = 9999;
38551                             options.params['sort'] = 'when_dt';    
38552                             options.params['dir'] = 'ASC';    
38553                             this.proxy.loadResponse = this.loadResponse;
38554                             Roo.log("load?");
38555                             //this.addColumns();
38556                         },
38557                         load : function (_self, records, options)
38558                         {
38559                             _this.grid.view.el.select('.course-edit-link', true).on('click', function() {
38560                                 // if you click on the translation.. you can edit it...
38561                                 var el = Roo.get(this);
38562                                 var id = el.dom.getAttribute('data-id');
38563                                 var d = el.dom.getAttribute('data-date');
38564                                 var t = el.dom.getAttribute('data-time');
38565                                 //var id = this.child('span').dom.textContent;
38566                                 
38567                                 //Roo.log(this);
38568                                 Pman.Dialog.CourseCalendar.show({
38569                                     id : id,
38570                                     when_d : d,
38571                                     when_t : t,
38572                                     productitem_active : id ? 1 : 0
38573                                 }, function() {
38574                                     _this.grid.ds.load({});
38575                                 });
38576                            
38577                            });
38578                            
38579                            _this.panel.fireEvent('resize', [ '', '' ]);
38580                         }
38581                     },
38582                     loadResponse : function(o, success, response){
38583                             // this is overridden on before load..
38584                             
38585                             Roo.log("our code?");       
38586                             //Roo.log(success);
38587                             //Roo.log(response)
38588                             delete this.activeRequest;
38589                             if(!success){
38590                                 this.fireEvent("loadexception", this, o, response);
38591                                 o.request.callback.call(o.request.scope, null, o.request.arg, false);
38592                                 return;
38593                             }
38594                             var result;
38595                             try {
38596                                 result = o.reader.read(response);
38597                             }catch(e){
38598                                 Roo.log("load exception?");
38599                                 this.fireEvent("loadexception", this, o, response, e);
38600                                 o.request.callback.call(o.request.scope, null, o.request.arg, false);
38601                                 return;
38602                             }
38603                             Roo.log("ready...");        
38604                             // loop through result.records;
38605                             // and set this.tdate[date] = [] << array of records..
38606                             _this.tdata  = {};
38607                             Roo.each(result.records, function(r){
38608                                 //Roo.log(r.data);
38609                                 if(typeof(_this.tdata[r.data.when_dt.format('j')]) == 'undefined'){
38610                                     _this.tdata[r.data.when_dt.format('j')] = [];
38611                                 }
38612                                 _this.tdata[r.data.when_dt.format('j')].push(r.data);
38613                             });
38614                             
38615                             //Roo.log(_this.tdata);
38616                             
38617                             result.records = [];
38618                             result.totalRecords = 6;
38619                     
38620                             // let's generate some duumy records for the rows.
38621                             //var st = _this.dateField.getValue();
38622                             
38623                             // work out monday..
38624                             //st = st.add(Date.DAY, -1 * st.format('w'));
38625                             
38626                             var date = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
38627                             
38628                             var firstOfMonth = date.getFirstDayOfMonth();
38629                             var days = date.getDaysInMonth();
38630                             var d = 1;
38631                             var firstAdded = false;
38632                             for (var i = 0; i < result.totalRecords ; i++) {
38633                                 //var d= st.add(Date.DAY, i);
38634                                 var row = {};
38635                                 var added = 0;
38636                                 for(var w = 0 ; w < 7 ; w++){
38637                                     if(!firstAdded && firstOfMonth != w){
38638                                         continue;
38639                                     }
38640                                     if(d > days){
38641                                         continue;
38642                                     }
38643                                     firstAdded = true;
38644                                     var dd = (d > 0 && d < 10) ? "0"+d : d;
38645                                     row['weekday'+w] = String.format(
38646                                                     '<span style="font-size: 16px;"><b>{0}</b></span>'+
38647                                                     '<span class="course-edit-link" style="color:blue;" data-id="0" data-date="{1}"> Add New</span>',
38648                                                     d,
38649                                                     date.format('Y-m-')+dd
38650                                                 );
38651                                     added++;
38652                                     if(typeof(_this.tdata[d]) != 'undefined'){
38653                                         Roo.each(_this.tdata[d], function(r){
38654                                             var is_sub = '';
38655                                             var deactive = '';
38656                                             var id = r.id;
38657                                             var desc = (r.productitem_id_descrip) ? r.productitem_id_descrip : '';
38658                                             if(r.parent_id*1>0){
38659                                                 is_sub = (r.productitem_id_visible*1 < 1) ? 'de-act-sup-link' :'sub-link';
38660                                                 id = r.parent_id;
38661                                             }
38662                                             if(r.productitem_id_visible*1 < 1 && r.parent_id*1 < 1){
38663                                                 deactive = 'de-act-link';
38664                                             }
38665                                             
38666                                             row['weekday'+w] += String.format(
38667                                                     '<br /><span class="course-edit-link {3} {4}" qtip="{5}" data-id="{0}">{2} - {1}</span>',
38668                                                     id, //0
38669                                                     r.product_id_name, //1
38670                                                     r.when_dt.format('h:ia'), //2
38671                                                     is_sub, //3
38672                                                     deactive, //4
38673                                                     desc // 5
38674                                             );
38675                                         });
38676                                     }
38677                                     d++;
38678                                 }
38679                                 
38680                                 // only do this if something added..
38681                                 if(added > 0){ 
38682                                     result.records.push(_this.grid.dataSource.reader.newRow(row));
38683                                 }
38684                                 
38685                                 
38686                                 // push it twice. (second one with an hour..
38687                                 
38688                             }
38689                             //Roo.log(result);
38690                             this.fireEvent("load", this, o, o.request.arg);
38691                             o.request.callback.call(o.request.scope, result, o.request.arg, true);
38692                         },
38693                     sortInfo : {field: 'when_dt', direction : 'ASC' },
38694                     proxy : {
38695                         xtype: 'HttpProxy',
38696                         xns: Roo.data,
38697                         method : 'GET',
38698                         url : baseURL + '/Roo/Shop_course.php'
38699                     },
38700                     reader : {
38701                         xtype: 'JsonReader',
38702                         xns: Roo.data,
38703                         id : 'id',
38704                         fields : [
38705                             {
38706                                 'name': 'id',
38707                                 'type': 'int'
38708                             },
38709                             {
38710                                 'name': 'when_dt',
38711                                 'type': 'string'
38712                             },
38713                             {
38714                                 'name': 'end_dt',
38715                                 'type': 'string'
38716                             },
38717                             {
38718                                 'name': 'parent_id',
38719                                 'type': 'int'
38720                             },
38721                             {
38722                                 'name': 'product_id',
38723                                 'type': 'int'
38724                             },
38725                             {
38726                                 'name': 'productitem_id',
38727                                 'type': 'int'
38728                             },
38729                             {
38730                                 'name': 'guid',
38731                                 'type': 'int'
38732                             }
38733                         ]
38734                     }
38735                 },
38736                 toolbar : {
38737                     xtype: 'Toolbar',
38738                     xns: Roo,
38739                     items : [
38740                         {
38741                             xtype: 'Button',
38742                             xns: Roo.Toolbar,
38743                             listeners : {
38744                                 click : function (_self, e)
38745                                 {
38746                                     var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
38747                                     sd.setMonth(sd.getMonth()-1);
38748                                     _this.monthField.setValue(sd.format('Y-m-d'));
38749                                     _this.grid.ds.load({});
38750                                 }
38751                             },
38752                             text : "Back"
38753                         },
38754                         {
38755                             xtype: 'Separator',
38756                             xns: Roo.Toolbar
38757                         },
38758                         {
38759                             xtype: 'MonthField',
38760                             xns: Roo.form,
38761                             listeners : {
38762                                 render : function (_self)
38763                                 {
38764                                     _this.monthField = _self;
38765                                    // _this.monthField.set  today
38766                                 },
38767                                 select : function (combo, date)
38768                                 {
38769                                     _this.grid.ds.load({});
38770                                 }
38771                             },
38772                             value : (function() { return new Date(); })()
38773                         },
38774                         {
38775                             xtype: 'Separator',
38776                             xns: Roo.Toolbar
38777                         },
38778                         {
38779                             xtype: 'TextItem',
38780                             xns: Roo.Toolbar,
38781                             text : "Blue: in-active, green: in-active sup-event, red: de-active, purple: de-active sup-event"
38782                         },
38783                         {
38784                             xtype: 'Fill',
38785                             xns: Roo.Toolbar
38786                         },
38787                         {
38788                             xtype: 'Button',
38789                             xns: Roo.Toolbar,
38790                             listeners : {
38791                                 click : function (_self, e)
38792                                 {
38793                                     var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
38794                                     sd.setMonth(sd.getMonth()+1);
38795                                     _this.monthField.setValue(sd.format('Y-m-d'));
38796                                     _this.grid.ds.load({});
38797                                 }
38798                             },
38799                             text : "Next"
38800                         }
38801                     ]
38802                 },
38803                  
38804             }
38805         };
38806         
38807         *//*
38808  * Based on:
38809  * Ext JS Library 1.1.1
38810  * Copyright(c) 2006-2007, Ext JS, LLC.
38811  *
38812  * Originally Released Under LGPL - original licence link has changed is not relivant.
38813  *
38814  * Fork - LGPL
38815  * <script type="text/javascript">
38816  */
38817  
38818 /**
38819  * @class Roo.LoadMask
38820  * A simple utility class for generically masking elements while loading data.  If the element being masked has
38821  * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
38822  * process and the mask element will be cached for reuse.  For all other elements, this mask will replace the
38823  * element's UpdateManager load indicator and will be destroyed after the initial load.
38824  * @constructor
38825  * Create a new LoadMask
38826  * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
38827  * @param {Object} config The config object
38828  */
38829 Roo.LoadMask = function(el, config){
38830     this.el = Roo.get(el);
38831     Roo.apply(this, config);
38832     if(this.store){
38833         this.store.on('beforeload', this.onBeforeLoad, this);
38834         this.store.on('load', this.onLoad, this);
38835         this.store.on('loadexception', this.onLoadException, this);
38836         this.removeMask = false;
38837     }else{
38838         var um = this.el.getUpdateManager();
38839         um.showLoadIndicator = false; // disable the default indicator
38840         um.on('beforeupdate', this.onBeforeLoad, this);
38841         um.on('update', this.onLoad, this);
38842         um.on('failure', this.onLoad, this);
38843         this.removeMask = true;
38844     }
38845 };
38846
38847 Roo.LoadMask.prototype = {
38848     /**
38849      * @cfg {Boolean} removeMask
38850      * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
38851      * False to persist the mask element reference for multiple uses (e.g., for paged data widgets).  Defaults to false.
38852      */
38853     removeMask : false,
38854     /**
38855      * @cfg {String} msg
38856      * The text to display in a centered loading message box (defaults to 'Loading...')
38857      */
38858     msg : 'Loading...',
38859     /**
38860      * @cfg {String} msgCls
38861      * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
38862      */
38863     msgCls : 'x-mask-loading',
38864
38865     /**
38866      * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
38867      * @type Boolean
38868      */
38869     disabled: false,
38870
38871     /**
38872      * Disables the mask to prevent it from being displayed
38873      */
38874     disable : function(){
38875        this.disabled = true;
38876     },
38877
38878     /**
38879      * Enables the mask so that it can be displayed
38880      */
38881     enable : function(){
38882         this.disabled = false;
38883     },
38884     
38885     onLoadException : function()
38886     {
38887         Roo.log(arguments);
38888         
38889         if (typeof(arguments[3]) != 'undefined') {
38890             Roo.MessageBox.alert("Error loading",arguments[3]);
38891         } 
38892         /*
38893         try {
38894             if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
38895                 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
38896             }   
38897         } catch(e) {
38898             
38899         }
38900         */
38901     
38902         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
38903     },
38904     // private
38905     onLoad : function()
38906     {
38907         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
38908     },
38909
38910     // private
38911     onBeforeLoad : function(){
38912         if(!this.disabled){
38913             (function() { this.el.mask(this.msg, this.msgCls); }).defer(50, this);
38914         }
38915     },
38916
38917     // private
38918     destroy : function(){
38919         if(this.store){
38920             this.store.un('beforeload', this.onBeforeLoad, this);
38921             this.store.un('load', this.onLoad, this);
38922             this.store.un('loadexception', this.onLoadException, this);
38923         }else{
38924             var um = this.el.getUpdateManager();
38925             um.un('beforeupdate', this.onBeforeLoad, this);
38926             um.un('update', this.onLoad, this);
38927             um.un('failure', this.onLoad, this);
38928         }
38929     }
38930 };/*
38931  * Based on:
38932  * Ext JS Library 1.1.1
38933  * Copyright(c) 2006-2007, Ext JS, LLC.
38934  *
38935  * Originally Released Under LGPL - original licence link has changed is not relivant.
38936  *
38937  * Fork - LGPL
38938  * <script type="text/javascript">
38939  */
38940
38941
38942 /**
38943  * @class Roo.XTemplate
38944  * @extends Roo.Template
38945  * Provides a template that can have nested templates for loops or conditionals. The syntax is:
38946 <pre><code>
38947 var t = new Roo.XTemplate(
38948         '&lt;select name="{name}"&gt;',
38949                 '&lt;tpl for="options"&gt;&lt;option value="{value:trim}"&gt;{text:ellipsis(10)}&lt;/option&gt;&lt;/tpl&gt;',
38950         '&lt;/select&gt;'
38951 );
38952  
38953 // then append, applying the master template values
38954  </code></pre>
38955  *
38956  * Supported features:
38957  *
38958  *  Tags:
38959
38960 <pre><code>
38961       {a_variable} - output encoded.
38962       {a_variable.format:("Y-m-d")} - call a method on the variable
38963       {a_variable:raw} - unencoded output
38964       {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
38965       {a_variable:this.method_on_template(...)} - call a method on the template object.
38966  
38967 </code></pre>
38968  *  The tpl tag:
38969 <pre><code>
38970         &lt;tpl for="a_variable or condition.."&gt;&lt;/tpl&gt;
38971         &lt;tpl if="a_variable or condition"&gt;&lt;/tpl&gt;
38972         &lt;tpl exec="some javascript"&gt;&lt;/tpl&gt;
38973         &lt;tpl name="named_template"&gt;&lt;/tpl&gt; (experimental)
38974   
38975         &lt;tpl for="."&gt;&lt;/tpl&gt; - just iterate the property..
38976         &lt;tpl for=".."&gt;&lt;/tpl&gt; - iterates with the parent (probably the template) 
38977 </code></pre>
38978  *      
38979  */
38980 Roo.XTemplate = function()
38981 {
38982     Roo.XTemplate.superclass.constructor.apply(this, arguments);
38983     if (this.html) {
38984         this.compile();
38985     }
38986 };
38987
38988
38989 Roo.extend(Roo.XTemplate, Roo.Template, {
38990
38991     /**
38992      * The various sub templates
38993      */
38994     tpls : false,
38995     /**
38996      *
38997      * basic tag replacing syntax
38998      * WORD:WORD()
38999      *
39000      * // you can fake an object call by doing this
39001      *  x.t:(test,tesT) 
39002      * 
39003      */
39004     re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
39005
39006     /**
39007      * compile the template
39008      *
39009      * This is not recursive, so I'm not sure how nested templates are really going to be handled..
39010      *
39011      */
39012     compile: function()
39013     {
39014         var s = this.html;
39015      
39016         s = ['<tpl>', s, '</tpl>'].join('');
39017     
39018         var re     = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
39019             nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
39020             ifRe   = /^<tpl\b[^>]*?if="(.*?)"/,
39021             execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
39022             namedRe = /^<tpl\b[^>]*?name="(\w+)"/,  // named templates..
39023             m,
39024             id     = 0,
39025             tpls   = [];
39026     
39027         while(true == !!(m = s.match(re))){
39028             var forMatch   = m[0].match(nameRe),
39029                 ifMatch   = m[0].match(ifRe),
39030                 execMatch   = m[0].match(execRe),
39031                 namedMatch   = m[0].match(namedRe),
39032                 
39033                 exp  = null, 
39034                 fn   = null,
39035                 exec = null,
39036                 name = forMatch && forMatch[1] ? forMatch[1] : '';
39037                 
39038             if (ifMatch) {
39039                 // if - puts fn into test..
39040                 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
39041                 if(exp){
39042                    fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
39043                 }
39044             }
39045             
39046             if (execMatch) {
39047                 // exec - calls a function... returns empty if true is  returned.
39048                 exp = execMatch && execMatch[1] ? execMatch[1] : null;
39049                 if(exp){
39050                    exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
39051                 }
39052             }
39053             
39054             
39055             if (name) {
39056                 // for = 
39057                 switch(name){
39058                     case '.':  name = new Function('values', 'parent', 'with(values){ return values; }'); break;
39059                     case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
39060                     default:   name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
39061                 }
39062             }
39063             var uid = namedMatch ? namedMatch[1] : id;
39064             
39065             
39066             tpls.push({
39067                 id:     namedMatch ? namedMatch[1] : id,
39068                 target: name,
39069                 exec:   exec,
39070                 test:   fn,
39071                 body:   m[1] || ''
39072             });
39073             if (namedMatch) {
39074                 s = s.replace(m[0], '');
39075             } else { 
39076                 s = s.replace(m[0], '{xtpl'+ id + '}');
39077             }
39078             ++id;
39079         }
39080         this.tpls = [];
39081         for(var i = tpls.length-1; i >= 0; --i){
39082             this.compileTpl(tpls[i]);
39083             this.tpls[tpls[i].id] = tpls[i];
39084         }
39085         this.master = tpls[tpls.length-1];
39086         return this;
39087     },
39088     /**
39089      * same as applyTemplate, except it's done to one of the subTemplates
39090      * when using named templates, you can do:
39091      *
39092      * var str = pl.applySubTemplate('your-name', values);
39093      *
39094      * 
39095      * @param {Number} id of the template
39096      * @param {Object} values to apply to template
39097      * @param {Object} parent (normaly the instance of this object)
39098      */
39099     applySubTemplate : function(id, values, parent)
39100     {
39101         
39102         
39103         var t = this.tpls[id];
39104         
39105         
39106         try { 
39107             if(t.test && !t.test.call(this, values, parent)){
39108                 return '';
39109             }
39110         } catch(e) {
39111             Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
39112             Roo.log(e.toString());
39113             Roo.log(t.test);
39114             return ''
39115         }
39116         try { 
39117             
39118             if(t.exec && t.exec.call(this, values, parent)){
39119                 return '';
39120             }
39121         } catch(e) {
39122             Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
39123             Roo.log(e.toString());
39124             Roo.log(t.exec);
39125             return ''
39126         }
39127         try {
39128             var vs = t.target ? t.target.call(this, values, parent) : values;
39129             parent = t.target ? values : parent;
39130             if(t.target && vs instanceof Array){
39131                 var buf = [];
39132                 for(var i = 0, len = vs.length; i < len; i++){
39133                     buf[buf.length] = t.compiled.call(this, vs[i], parent);
39134                 }
39135                 return buf.join('');
39136             }
39137             return t.compiled.call(this, vs, parent);
39138         } catch (e) {
39139             Roo.log("Xtemplate.applySubTemplate : Exception thrown");
39140             Roo.log(e.toString());
39141             Roo.log(t.compiled);
39142             return '';
39143         }
39144     },
39145
39146     compileTpl : function(tpl)
39147     {
39148         var fm = Roo.util.Format;
39149         var useF = this.disableFormats !== true;
39150         var sep = Roo.isGecko ? "+" : ",";
39151         var undef = function(str) {
39152             Roo.log("Property not found :"  + str);
39153             return '';
39154         };
39155         
39156         var fn = function(m, name, format, args)
39157         {
39158             //Roo.log(arguments);
39159             args = args ? args.replace(/\\'/g,"'") : args;
39160             //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
39161             if (typeof(format) == 'undefined') {
39162                 format= 'htmlEncode';
39163             }
39164             if (format == 'raw' ) {
39165                 format = false;
39166             }
39167             
39168             if(name.substr(0, 4) == 'xtpl'){
39169                 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
39170             }
39171             
39172             // build an array of options to determine if value is undefined..
39173             
39174             // basically get 'xxxx.yyyy' then do
39175             // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
39176             //    (function () { Roo.log("Property not found"); return ''; })() :
39177             //    ......
39178             
39179             var udef_ar = [];
39180             var lookfor = '';
39181             Roo.each(name.split('.'), function(st) {
39182                 lookfor += (lookfor.length ? '.': '') + st;
39183                 udef_ar.push(  "(typeof(" + lookfor + ") == 'undefined')"  );
39184             });
39185             
39186             var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
39187             
39188             
39189             if(format && useF){
39190                 
39191                 args = args ? ',' + args : "";
39192                  
39193                 if(format.substr(0, 5) != "this."){
39194                     format = "fm." + format + '(';
39195                 }else{
39196                     format = 'this.call("'+ format.substr(5) + '", ';
39197                     args = ", values";
39198                 }
39199                 
39200                 return "'"+ sep +   udef_st   +    format + name + args + "))"+sep+"'";
39201             }
39202              
39203             if (args.length) {
39204                 // called with xxyx.yuu:(test,test)
39205                 // change to ()
39206                 return "'"+ sep + udef_st  + name + '(' +  args + "))"+sep+"'";
39207             }
39208             // raw.. - :raw modifier..
39209             return "'"+ sep + udef_st  + name + ")"+sep+"'";
39210             
39211         };
39212         var body;
39213         // branched to use + in gecko and [].join() in others
39214         if(Roo.isGecko){
39215             body = "tpl.compiled = function(values, parent){  with(values) { return '" +
39216                    tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
39217                     "';};};";
39218         }else{
39219             body = ["tpl.compiled = function(values, parent){  with (values) { return ['"];
39220             body.push(tpl.body.replace(/(\r\n|\n)/g,
39221                             '\\n').replace(/'/g, "\\'").replace(this.re, fn));
39222             body.push("'].join('');};};");
39223             body = body.join('');
39224         }
39225         
39226         Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
39227        
39228         /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef  */
39229         eval(body);
39230         
39231         return this;
39232     },
39233
39234     applyTemplate : function(values){
39235         return this.master.compiled.call(this, values, {});
39236         //var s = this.subs;
39237     },
39238
39239     apply : function(){
39240         return this.applyTemplate.apply(this, arguments);
39241     }
39242
39243  });
39244
39245 Roo.XTemplate.from = function(el){
39246     el = Roo.getDom(el);
39247     return new Roo.XTemplate(el.value || el.innerHTML);
39248 };